diff --git a/.gitignore b/.gitignore index 4bb3db99..347a84f3 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,8 @@ database_registry.json # Tauri build output and generated schemas src-tauri/target/ src-tauri/gen/ +# Command permissions written by the build script from the COMMANDS list +src-tauri/permissions/autogenerated/ # Rust /target/ diff --git a/README.md b/README.md index b1ae8ca3..6e86b8ea 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ It is a free alternative to paid poker trackers for 3-max Spin & Go, Heads-Up an | 📈 **Detailed statistics** | Stats by spot, stack depth and player profile, compared with a baseline to highlight your **leaks**. | | 🎬 **Interactive hand replayer** | Replay hands street by street, check equities, take notes on opponents. | | 🧮 **Range research** | Interactive 13×13 range grid to study your ranges and compare them with opponent tendencies. | +| 🎯 **My ranges and training** | Build your own preflop ranges (your scenarios, depths, actions and colours; SpinTracker ships none), see how often you follow them on your real hands, then practise with a quiz, your own deviations and a spaced review. A deviation means "not what you planned", never "a mistake". An overview tab shows all your ranges at a glance, and you pick which ranges and depths to export as a versioned `.json` file (import it back anywhere). | | 🎰 **Multipliers analysis** | Break down your results by Spin multiplier. | | 👥 **Player database** | Overview of every opponent you faced and how they play. | | 🔄 **Automatic import** | Detects the room and imports hand histories idempotently — re-importing never creates duplicates. Optionally watches your Winamax and Unibet history folders and imports new hands as they are written (on by default, it starts watching as soon as a history folder is set; Betclic stays a manual export). | diff --git a/crates/core/src/api.rs b/crates/core/src/api.rs index 4b21e669..71a11547 100644 --- a/crates/core/src/api.rs +++ b/crates/core/src/api.rs @@ -29,6 +29,11 @@ use crate::repos::{hands, heatmap, players, tournaments}; use crate::services::analysis::{self, AnalysisFilters, AnalysisHandsRequest}; use crate::services::custom_stats::CustomStatsService; use crate::stats::custom::store::{self as custom_store, SaveError}; +use crate::services::range_adherence; +use crate::services::review; +use crate::services::training; +use crate::services::ranges_io; +use crate::services::user_ranges::{self as ranges, RangeError}; use crate::services::hud::{HudFigureHandsRequest, HudNoteRequest, HudPlayersRequest, HudService, HudTablesRequest}; use crate::services::Importer; use crate::stats::store; @@ -234,7 +239,14 @@ impl Backend { Response::ok(json!({ "success": true, "inserted": inserted, "total": total, "analytics_calculated": total })) } } - ("GET" | "POST", ["db", "hands"]) => Response::data(hands_query::get_hands(&*conn()?, &r.options(hands_query_from_query)?)?), + ("GET" | "POST", ["db", "hands"]) => { + let query = r.options(hands_query_from_query)?; + if let (true, Some(hero)) = (query.range_deviation, query.hero_name.as_deref()) { + // The filter reads the stored range checks: bring them up to date first. + range_adherence::ensure_computed(&mut *conn()?, hero)?; + } + Response::data(hands_query::get_hands(&*conn()?, &query)?) + } ("GET", ["db", "export-summary"]) => Response::data(hands_query::export_summary(&*conn()?)?), ("GET" | "POST", ["db", "tournaments"]) => { let result = tournaments::get_tournaments(&*conn()?, &r.options(tournaments_query_from_query)?)?; @@ -425,12 +437,22 @@ impl Backend { ("POST", ["analysis", "hands"]) => Response::data(analysis::analysis_hands(&*conn()?, &r.body_as_camel::()?)?), ("POST", ["analysis", "range-breakdown"]) => Response::data(analysis::range_breakdown(&*conn()?, &r.body_as_camel::()?)?), ("GET", ["analysis", "replayer", id]) => match analysis::hand_replay(&*conn()?, id, r.query_str("heroName").as_deref())? { - Some(replay) => Response::data(replay), + Some(mut replay) => { + let hero = r.query_str("heroName").unwrap_or_default(); + // Players who built no range get no card: the field is left out. + if let Some(check) = range_adherence::hand_check(&*conn()?, &hero, id)? { + replay["rangeCheck"] = check; + } + Response::data(replay) + } None => Response::failure(404, "Hand not found"), }, ("POST", ["equity"]) => self.equity(r), ("POST", ["equity", "batch"]) => self.equity_batch(r), + // --- The player's own ranges + (_, ["ranges", rest @ ..]) => return self.ranges(r, rest), + // --- Databases (_, ["api", "databases", rest @ ..]) => return self.databases(r, rest), @@ -509,6 +531,141 @@ impl Backend { Response::ok(json!({ "success": true, "data": results, "processed": processed })) } + /// Routes of the player's own ranges (`ranges/...`). + fn ranges(&self, r: &Request, rest: &[&str]) -> Result> { + use std::collections::BTreeMap; + let result: ranges::Res> = (|| { + let mut conn = self.db.conn()?; + let id = |s: &str| s.parse::().map_err(|_| RangeError::Invalid(format!("bad id: {s}"))); + let body = |name: &str| -> ranges::Res { Ok(r.body.as_ref().and_then(|b| b.get(name)).cloned().unwrap_or(Value::Null)) }; + let response = match (r.method, rest) { + ("GET", ["tree"]) => Response::data(ranges::tree(&conn)?), + ("POST", ["spot"]) => { + let input: ranges::SpotInput = r.body_as()?; + let spot = ranges::save_spot(&mut conn, &input)?; + self.db.bump_data_version(); + Response::data(json!({ "id": spot })) + } + ("DELETE", ["spot", spot]) => { + ranges::delete_spot(&mut conn, id(spot)?)?; + self.db.bump_data_version(); + Response::ok(json!({ "success": true })) + } + ("POST", ["spot", spot, "duplicate"]) => { + let copy = ranges::duplicate_spot(&mut conn, id(spot)?, r.body_str("opponent").as_deref())?; + Response::data(json!({ "id": copy })) + } + ("POST", ["spot", spot, "depth"]) => { + let stack = body("stackBb")?.as_f64().ok_or_else(|| RangeError::Invalid("stackBb is required".into()))?; + let start: ranges::StartPoint = serde_json::from_value(body("start")?).unwrap_or_default(); + let scenario = ranges::add_depth(&mut conn, id(spot)?, stack, &start)?; + Response::data(json!({ "id": scenario })) + } + ("GET", ["scenario", scenario]) => Response::data(ranges::scenario(&conn, id(scenario)?)?), + ("DELETE", ["scenario", scenario]) => { + ranges::remove_depth(&mut conn, id(scenario)?)?; + self.db.bump_data_version(); + Response::ok(json!({ "success": true })) + } + ("POST", ["scenario", scenario, "hands"]) => { + let hands: BTreeMap = serde_json::from_value(body("hands")?)?; + ranges::save_hands(&mut conn, id(scenario)?, &hands)?; + self.db.bump_data_version(); + Response::ok(json!({ "success": true })) + } + ("GET", ["actions"]) => Response::data(ranges::list_actions(&conn)?), + ("POST", ["actions"]) => { + let actions: Vec = serde_json::from_value(body("actions")?)?; + Response::data(ranges::save_actions(&mut conn, &actions)?) + } + ("POST", ["actions", action, "delete"]) => { + ranges::delete_action(&mut conn, id(action)?, body("replaceWith")?.as_i64())?; + self.db.bump_data_version(); + Response::ok(json!({ "success": true })) + } + ("GET", ["programs"]) => Response::data(ranges::programs(&conn)?), + ("POST", ["programs"]) => { + let input: ranges::ProgramInput = r.body_as()?; + Response::data(json!({ "id": ranges::save_program(&mut conn, &input)? })) + } + ("DELETE", ["programs", program]) => { + ranges::delete_program(&mut conn, id(program)?)?; + Response::ok(json!({ "success": true })) + } + ("GET", ["adherence"]) => { + let hero = r.query_str("heroName").ok_or_else(|| RangeError::Invalid("heroName is required".into()))?; + range_adherence::ensure_computed(&mut conn, &hero)?; + Response::data(range_adherence::adherence(&conn, &hero, r.query_str("from").as_deref(), r.query_str("to").as_deref(), r.query_str("opponent").as_deref())?) + } + ("GET", ["adherence", scenario]) => { + let hero = r.query_str("heroName").ok_or_else(|| RangeError::Invalid("heroName is required".into()))?; + range_adherence::ensure_computed(&mut conn, &hero)?; + match range_adherence::scenario_detail(&conn, id(scenario)?, &hero, r.query_str("from").as_deref(), r.query_str("to").as_deref())? { + Some(detail) => Response::data(detail), + None => return Ok(None), + } + } + ("POST", ["training", "question"]) => { + let mut request: training::QuestionRequest = r.body_as()?; + // The seed only varies the draw; tests pass their own. + request.today = chrono::Local::now().format("%Y-%m-%d").to_string(); + request.seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_nanos() as u64); + if request.source == "deviation" { + if let Some(hero) = request.hero_name.as_deref() { + range_adherence::ensure_computed(&mut conn, hero)?; + } + } + Response::data(training::next_question(&conn, &request)?.unwrap_or(Value::Null)) + } + ("POST", ["training", "answer"]) => { + let request: training::AnswerRequest = r.body_as()?; + let now = chrono::Local::now().naive_local(); + Response::data(training::check_answer(&conn, &request, now.date(), &now.format("%Y-%m-%dT%H:%M:%S").to_string())?) + } + ("GET", ["review"]) => { + let today = chrono::Local::now().date_naive(); + Response::data(review::overview(&conn, today, r.query_str("heroName").as_deref())?) + } + ("POST", ["review", "answer"]) => { + let (scenario, hand, correct) = (r.body_field::("scenarioId")?, r.body_str("handClass").unwrap_or_default(), r.body_field::("correct")?); + let now = chrono::Local::now().naive_local(); + let (box_number, due) = review::record(&conn, scenario, &hand, correct, now.date(), &now.format("%Y-%m-%dT%H:%M:%S").to_string())?; + Response::data(json!({ "box": box_number, "dueOn": due.format("%Y-%m-%d").to_string() })) + } + ("GET", ["export"]) => { + // `scenarioIds=1,2,3` limits the file to those depths; without it everything is exported. + let chosen: Option> = r.query_str("scenarioIds").map(|list| list.split(',').filter_map(|id| id.trim().parse().ok()).collect()); + Response::data(ranges_io::export(&conn, chosen.as_ref())?) + } + ("POST", ["import"]) => { + let content = r.body_str("content").unwrap_or_default(); + let mode = r.body_str("mode").as_deref().and_then(ranges_io::ImportMode::parse).ok_or_else(|| RangeError::Invalid("mode is replace or merge".into()))?; + let dry_run = r.body.as_ref().and_then(|b| b.get("dryRun")).and_then(Value::as_bool).unwrap_or(false); + let report = ranges_io::import(&mut conn, &content, mode, dry_run)?; + self.db.bump_data_version(); + Response::data(report) + } + ("GET", ["settings"]) => Response::data(ranges::settings(&conn)?), + ("POST", ["settings"]) => { + let updated = ranges::update_settings(&mut conn, r.body.as_ref().unwrap_or(&Value::Null))?; + self.db.bump_data_version(); + Response::data(updated) + } + _ => return Ok(None), + }; + Ok(Some(response)) + })(); + match result { + Ok(response) => Ok(response), + Err(RangeError::Invalid(message)) => Ok(Some(Response::failure(400, &message))), + Err(RangeError::NotFound) => Ok(Some(Response::failure(404, "Not found"))), + Err(RangeError::Conflict { message, existing_id }) => { + Ok(Some(Response { status: 409, body: json!({ "success": false, "error": message, "existingId": existing_id }) })) + } + Err(RangeError::Other(e)) => Err(e), + } + } + fn databases(&self, r: &Request, rest: &[&str]) -> Result> { let response = match (r.method, rest) { ("GET", []) => Response::data(Value::Array(self.registry.get_all().iter().map(database_json).collect())), diff --git a/crates/core/src/db/migrations.rs b/crates/core/src/db/migrations.rs index 8bff537e..2b66a82e 100644 --- a/crates/core/src/db/migrations.rs +++ b/crates/core/src/db/migrations.rs @@ -46,6 +46,11 @@ const MIGRATIONS: &[Migration] = &[ migration!(202611100001, "RecomputeInPositionStats", "202611100001_recompute_in_position_stats.sql"), migration!(202611110001, "AddBuyInIndex", "202611110001_add_buy_in_index.sql"), migration!(202611120001, "AddHandsCoveringIndex", "202611120001_add_hands_covering_index.sql"), + migration!(202611200001, "AddUserRanges", "202611200001_user_ranges.sql"), + migration!(202611200002, "AddHandRangeChecks", "202611200002_hand_range_checks.sql"), + migration!(202611200003, "AddTraining", "202611200003_training.sql"), + migration!(202611200004, "AddTrainingCards", "202611200004_training_cards.sql"), + migration!(202611200005, "AddRangeCheckOpponent", "202611200005_range_check_opponent.sql"), ]; /// Applies the missing migrations in numeric version order (like FluentMigrator). @@ -144,7 +149,7 @@ mod tests { assert_eq!(run(&mut conn).unwrap(), MIGRATIONS.len()); let t = names(&conn, "table"); - for expected in ["hands", "player_hands", "players", "aliases", "VersionInfo", "hand_player_flags", "import_files", "player_notes", "custom_stats", "custom_stat_hits"] { + for expected in ["hands", "player_hands", "players", "aliases", "VersionInfo", "hand_player_flags", "import_files", "player_notes", "custom_stats", "custom_stat_hits", "range_actions", "range_spots", "range_scenarios", "range_hands", "range_programs", "range_program_spots", "range_settings", "hand_range_checks", "training_attempts", "training_cards"] { assert!(t.iter().any(|n| n == expected), "table {expected} missing"); } assert!(!t.iter().any(|n| n == "config"), "config must be dropped"); @@ -196,6 +201,16 @@ mod tests { DROP TABLE player_notes; DROP TABLE custom_stats; DROP TABLE custom_stat_hits; + DROP TABLE range_actions; + DROP TABLE range_spots; + DROP TABLE range_scenarios; + DROP TABLE range_hands; + DROP TABLE range_programs; + DROP TABLE range_program_spots; + DROP TABLE range_settings; + DROP TABLE hand_range_checks; + DROP TABLE training_attempts; + DROP TABLE training_cards; ALTER TABLE players DROP COLUMN alias_id; ALTER TABLE players DROP COLUMN room; ALTER TABLE hands DROP COLUMN position; @@ -216,7 +231,7 @@ mod tests { ) .unwrap(); - assert_eq!(run(&mut conn).unwrap(), 14); + assert_eq!(run(&mut conn).unwrap(), 19); // Existing data survives and the `room` backfill runs. let room: Option = conn .query_row("SELECT room FROM players WHERE name = 'hero'", [], |r| r.get(0)) diff --git a/crates/core/src/db/pool.rs b/crates/core/src/db/pool.rs index 8171046e..6b0bedf3 100644 --- a/crates/core/src/db/pool.rs +++ b/crates/core/src/db/pool.rs @@ -142,7 +142,7 @@ mod tests { let mode: String = conn.query_row("PRAGMA journal_mode", [], |r| r.get(0)).unwrap(); assert_eq!(mode, "wal"); let n: i64 = conn.query_row("SELECT COUNT(*) FROM VersionInfo", [], |r| r.get(0)).unwrap(); - assert_eq!(n, 19); + assert_eq!(n, 24); } #[test] diff --git a/crates/core/src/db/sql/202611200001_user_ranges.sql b/crates/core/src/db/sql/202611200001_user_ranges.sql new file mode 100644 index 00000000..3eae57f6 --- /dev/null +++ b/crates/core/src/db/sql/202611200001_user_ranges.sql @@ -0,0 +1,75 @@ +-- The player's own preflop ranges: a shared action palette, situations ("spots"), one range per +-- stack depth, programs (named lists of spots) and settings. Nothing is shipped but the base actions. +CREATE TABLE range_actions ( + id INTEGER PRIMARY KEY, + label TEXT NOT NULL UNIQUE, + color TEXT NOT NULL, + immediate TEXT NOT NULL, + size_value REAL, + size_unit TEXT, + response TEXT NOT NULL DEFAULT 'none', + sort_order INTEGER NOT NULL DEFAULT 0 +); + +CREATE TABLE range_spots ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + format TEXT NOT NULL, + hero_position TEXT NOT NULL, + line TEXT NOT NULL, + line_sizes TEXT, + opponent TEXT NOT NULL DEFAULT 'any', + study_only INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE UNIQUE INDEX idx_range_spots_situation ON range_spots(format, hero_position, line, opponent); + +CREATE TABLE range_scenarios ( + id INTEGER PRIMARY KEY, + spot_id INTEGER NOT NULL REFERENCES range_spots(id), + stack_bb REAL NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE (spot_id, stack_bb) +); + +CREATE TABLE range_hands ( + scenario_id INTEGER NOT NULL REFERENCES range_scenarios(id), + hand TEXT NOT NULL, + action_id INTEGER NOT NULL REFERENCES range_actions(id), + weight REAL NOT NULL DEFAULT 1.0, + PRIMARY KEY (scenario_id, hand) +); +CREATE INDEX idx_range_hands_action ON range_hands(action_id); + +CREATE TABLE range_programs ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + sort_order INTEGER NOT NULL DEFAULT 0 +); + +CREATE TABLE range_program_spots ( + program_id INTEGER NOT NULL REFERENCES range_programs(id), + spot_id INTEGER NOT NULL REFERENCES range_spots(id), + sort_order INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (program_id, spot_id) +); + +CREATE TABLE range_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +INSERT INTO range_actions (label, color, immediate, size_value, size_unit, response, sort_order) VALUES + ('Fold', '#2a2f39', 'fold', NULL, NULL, 'none', 0), + ('Check', '#3b4352', 'check', NULL, NULL, 'none', 1), + ('Call', '#4caf50', 'call', NULL, NULL, 'none', 2), + ('Limp', '#7aa7ff', 'limp', NULL, NULL, 'none', 3), + ('Raise', '#5b8def', 'raise', NULL, NULL, 'none', 4), + ('All-in', '#ff6b5b', 'allin', NULL, NULL, 'none', 5); + +INSERT INTO range_settings (key, value) VALUES + ('default_stacks', '[25,20,15,10,7]'), + ('depth_rule', 'nearest'), + ('new_cards_per_day', '20'), + ('prioritize_borderline', '1'); diff --git a/crates/core/src/db/sql/202611200002_hand_range_checks.sql b/crates/core/src/db/sql/202611200002_hand_range_checks.sql new file mode 100644 index 00000000..c8f47b46 --- /dev/null +++ b/crates/core/src/db/sql/202611200002_hand_range_checks.sql @@ -0,0 +1,25 @@ +-- How each hero decision compares with the player's own range. Rows are derived data: any change +-- to the ranges clears the table and the next read recomputes what is missing. +CREATE TABLE hand_range_checks ( + hand_id TEXT PRIMARY KEY, + hero_name TEXT, + played_at TEXT, + scenario_id INTEGER, + hand_class TEXT NOT NULL, + cards TEXT, + format TEXT, + hero_position TEXT, + line TEXT, + expected_action_id INTEGER, + played_immediate TEXT, + played_response TEXT, + status TEXT NOT NULL, + deviation_kind TEXT, + depth_used_bb REAL, + stack_bb REAL, + ev_bb REAL, + computed_at TEXT NOT NULL +); +CREATE INDEX idx_hand_range_checks_status ON hand_range_checks(status); +CREATE INDEX idx_hand_range_checks_scenario ON hand_range_checks(scenario_id); +CREATE INDEX idx_hand_range_checks_played_at ON hand_range_checks(played_at); diff --git a/crates/core/src/db/sql/202611200003_training.sql b/crates/core/src/db/sql/202611200003_training.sql new file mode 100644 index 00000000..fc8ea776 --- /dev/null +++ b/crates/core/src/db/sql/202611200003_training.sql @@ -0,0 +1,14 @@ +-- Every answer given in the range quiz. `answer_immediate` holds the id of the palette action the +-- player chose, so two actions with the same immediate play stay distinguishable. +CREATE TABLE training_attempts ( + id INTEGER PRIMARY KEY, + scenario_id INTEGER NOT NULL, + hand_class TEXT NOT NULL, + source TEXT NOT NULL, + hand_id TEXT, + answer_immediate TEXT NOT NULL, + answer_response TEXT, + correct INTEGER NOT NULL, + created_at TEXT NOT NULL +); +CREATE INDEX idx_training_attempts_scenario ON training_attempts(scenario_id, hand_class); diff --git a/crates/core/src/db/sql/202611200004_training_cards.sql b/crates/core/src/db/sql/202611200004_training_cards.sql new file mode 100644 index 00000000..bfc30088 --- /dev/null +++ b/crates/core/src/db/sql/202611200004_training_cards.sql @@ -0,0 +1,11 @@ +-- Spaced-review cards: one per hand of a range the player has been asked about. +CREATE TABLE training_cards ( + scenario_id INTEGER NOT NULL, + hand_class TEXT NOT NULL, + box INTEGER NOT NULL CHECK (box BETWEEN 1 AND 5), + due_on TEXT NOT NULL, + last_answer_at TEXT, + created_on TEXT NOT NULL, + PRIMARY KEY (scenario_id, hand_class) +); +CREATE INDEX idx_training_cards_due ON training_cards(due_on); diff --git a/crates/core/src/db/sql/202611200005_range_check_opponent.sql b/crates/core/src/db/sql/202611200005_range_check_opponent.sql new file mode 100644 index 00000000..2b7d2c20 --- /dev/null +++ b/crates/core/src/db/sql/202611200005_range_check_opponent.sql @@ -0,0 +1,4 @@ +-- Whether the hero's opponent was a regular, so the report can split fish and regulars. +-- The checks are derived data: they are cleared and recomputed on the next read. +ALTER TABLE hand_range_checks ADD COLUMN vs_reg INTEGER NOT NULL DEFAULT 0; +DELETE FROM hand_range_checks; diff --git a/crates/core/src/engines/mod.rs b/crates/core/src/engines/mod.rs index 9ec96793..a69bb7b1 100644 --- a/crates/core/src/engines/mod.rs +++ b/crates/core/src/engines/mod.rs @@ -8,3 +8,7 @@ pub mod equity_cache; pub mod evaluator; pub mod hand_state; pub mod hand_summary; +pub mod preflop_line; +pub mod quiz; +pub mod range_check; +pub mod range_scenarios; diff --git a/crates/core/src/engines/preflop_line.rs b/crates/core/src/engines/preflop_line.rs new file mode 100644 index 00000000..ecee039f --- /dev/null +++ b/crates/core/src/engines/preflop_line.rs @@ -0,0 +1,123 @@ +//! Reading a hand's preflop action line: who did what, in which order. +//! +//! The functions take the raw preflop text and the "Name:POS|Name:POS" seat map, so they do not +//! depend on how a service loads its hands. + +use std::collections::HashMap; + +/// The line without its "HH:MM:SS - " prefix. +pub fn strip_timestamp(line: &str) -> String { + let line = line.trim(); + match line.split_once(" - ") { + Some((_, rest)) => rest.trim().to_string(), + None => line.to_string(), + } +} + +/// Splits "Name: action" or "Name action" into the name and the lower-cased action text. +pub fn split_player_and_content(line: &str) -> Option<(String, String)> { + let line = strip_timestamp(line); + if let Some(colon) = line.find(':') { + return Some((line[..colon].trim().to_string(), line[colon + 1..].trim().to_lowercase())); + } + let space = line.find(' ')?; + Some((line[..space].trim().to_string(), line[space..].trim().to_lowercase())) +} + +/// Seats by lower-cased player name, from "Player1:BTN|Player2:SB". +pub fn player_positions(map: &str) -> HashMap { + let mut out = HashMap::new(); + for pair in map.split('|') { + let parts: Vec<&str> = pair.split(':').collect(); + if let [name, position] = parts[..] { + out.insert(name.to_lowercase(), position.to_string()); + } + } + out +} + +/// The verb of an action text, when it is a betting action. +fn verb_of(content: &str, calls_stay_calls: bool) -> Option<&'static str> { + if calls_stay_calls && content.contains("calls") { + Some("call") + } else if content.contains("all-in") { + Some("all-in") + } else if content.contains("raises") { + Some("raise") + } else if content.contains("bets") { + Some("bet") + } else if content.contains("calls") { + Some("call") + } else if content.contains("checks") { + Some("check") + } else if content.contains("folds") { + Some("fold") + } else { + // Posts, antes and anything unknown are skipped. + None + } +} + +/// The preflop actions as "POSITION:verb" in order, posts excluded. +pub fn preflop_sequence(preflop: &str, positions: &str) -> Vec { + sequence_of(preflop, positions, false) +} + +/// Like `preflop_sequence`, but a call that puts the whole stack in stays a call: a range compares +/// what was done (call or shove), not whether the caller had enough chips left. +pub fn betting_sequence(preflop: &str, positions: &str) -> Vec { + sequence_of(preflop, positions, true) +} + +fn sequence_of(preflop: &str, positions: &str, calls_stay_calls: bool) -> Vec { + let seats = player_positions(positions); + let mut out = Vec::new(); + for line in preflop.split('\n').filter(|l| !l.is_empty()) { + let Some((player, content)) = split_player_and_content(line) else { continue }; + let Some(position) = seats.get(&player.to_lowercase()) else { continue }; + let Some(verb) = verb_of(&content, calls_stay_calls) else { continue }; + out.push(format!("{position}:{verb}")); + } + out +} + +/// Whether the hand's preflop line starts with `sequence` (positions and verbs, case-insensitive). +pub fn matches_action_sequence(preflop: &str, positions: &str, sequence: &[String]) -> bool { + if sequence.is_empty() { + return true; + } + if preflop.is_empty() { + return false; + } + let actual = preflop_sequence(preflop, positions); + actual.len() >= sequence.len() && sequence.iter().zip(&actual).all(|(wanted, got)| wanted.eq_ignore_ascii_case(got)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SEATS: &str = "Hero:BTN|SB:SB|BB:BB"; + + #[test] + fn action_sequences_match_in_order() { + let preflop = "SB: Posts SB 10\nBB: Posts BB 20\nHero: Raises to 50\nSB: Calls 40\nBB: Folds"; + assert!(matches_action_sequence(preflop, SEATS, &["BTN:raise".into(), "SB:call".into()])); + assert!(matches_action_sequence(preflop, SEATS, &["btn:Raise".into()])); + assert!(!matches_action_sequence(preflop, SEATS, &["BTN:call".into()])); + assert!(!matches_action_sequence(preflop, SEATS, &["BTN:raise".into(), "SB:call".into(), "BB:fold".into(), "BTN:check".into()])); + } + + #[test] + fn the_sequence_skips_posts() { + let preflop = "SB: Posts SB 10\nBB: Posts BB 20\nHero: Folds\nSB: Calls 10"; + assert_eq!(preflop_sequence(preflop, SEATS), vec!["BTN:fold", "SB:call"]); + } + + #[test] + fn a_call_for_the_whole_stack_is_a_call_in_the_betting_sequence_only() { + let preflop = "Hero: Raises to 500 and is all-in\nSB: Calls 300 and is all-in"; + assert_eq!(preflop_sequence(preflop, SEATS), vec!["BTN:all-in", "SB:all-in"]); + assert_eq!(betting_sequence(preflop, SEATS), vec!["BTN:all-in", "SB:call"]); + } +} diff --git a/crates/core/src/engines/quiz.rs b/crates/core/src/engines/quiz.rs new file mode 100644 index 00000000..517897e6 --- /dev/null +++ b/crates/core/src/engines/quiz.rs @@ -0,0 +1,196 @@ +//! Pure parts of the range quiz: which hands sit on the edge of an action, and the table a +//! question is drawn on. + +use std::collections::HashMap; + +use crate::engines::range_scenarios::RANKS; + +/// Big blind and small blind in big blinds. +const BIG_BLIND_BB: f64 = 1.0; +const SMALL_BLIND_BB: f64 = 0.5; +/// Size of a raise in front of the hero when the scenario gives none. +pub const DEFAULT_RAISE_BB: f64 = 2.0; + +fn cell_of(hand: &str) -> Option<(usize, usize)> { + let mut chars = hand.chars(); + let (a, b) = (chars.next()?, chars.next()?); + let first = RANKS.iter().position(|r| *r == a)?; + let second = RANKS.iter().position(|r| *r == b)?; + Some(if hand.ends_with('o') { (second, first) } else { (first, second) }) +} + +fn hand_at(row: usize, col: usize) -> String { + use std::cmp::Ordering::{Equal, Greater, Less}; + match row.cmp(&col) { + Equal => format!("{}{}", RANKS[row], RANKS[col]), + Less => format!("{}{}s", RANKS[row], RANKS[col]), + Greater => format!("{}{}o", RANKS[col], RANKS[row]), + } +} + +/// The hands next to `hand` in the grid (up, down, left, right). +pub fn neighbors(hand: &str) -> Vec { + let Some((row, col)) = cell_of(hand) else { return Vec::new() }; + let last = RANKS.len() - 1; + let mut out = Vec::new(); + if row > 0 { + out.push(hand_at(row - 1, col)); + } + if row < last { + out.push(hand_at(row + 1, col)); + } + if col > 0 { + out.push(hand_at(row, col - 1)); + } + if col < last { + out.push(hand_at(row, col + 1)); + } + out +} + +/// The first neighbour of `hand` that has another action: the hand is on the edge of its action. +pub fn borderline_neighbor(hands: &HashMap, hand: &str) -> Option { + let own = hands.get(hand)?; + neighbors(hand).into_iter().find(|n| hands.get(n).is_some_and(|action| action != own)) +} + +/// An action of a seat in front of the hero. +#[derive(Debug, Clone, PartialEq)] +pub struct SeatAction { + pub position: String, + /// "fold", "call", "raise" or "allin". + pub verb: String, + /// What a raise goes to, in big blinds. + pub bet_bb: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Seat { + pub position: String, + pub is_hero: bool, + /// What is left behind after the blind and the bet. + pub stack_bb: f64, + pub action: Option, + pub bet_bb: f64, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct QuizTable { + pub seats: Vec, + pub pot_bb: f64, +} + +fn seats_of(format: &str) -> &'static [&'static str] { + if format == "hu" { + &["SB", "BB"] + } else { + &["BTN", "SB", "BB"] + } +} + +/// The actions a stored line stands for: raises take their size from `sizes`, else the default. +pub fn actions_of_line(line: &str, sizes: &HashMap) -> Vec { + line.split(',') + .filter_map(|entry| entry.split_once(':')) + .map(|(position, verb)| { + let position = position.to_uppercase(); + let verb = match verb { + "call" => "call", + "raise" | "bet" => "raise", + "all-in" => "allin", + _ => "fold", + }; + let bet_bb = (verb == "raise").then(|| sizes.get(&position).copied().unwrap_or(DEFAULT_RAISE_BB)); + SeatAction { position, verb: verb.into(), bet_bb } + }) + .collect() +} + +/// The table when the hero is about to act: blinds posted, the given actions applied. +/// `stacks` are starting stacks by seat; a missing seat gets `default_stack`. +pub fn build_table(format: &str, hero: &str, actions: &[SeatAction], stacks: &HashMap, default_stack: f64) -> QuizTable { + let mut seats: Vec = seats_of(format) + .iter() + .map(|position| { + let blind = match *position { + "SB" => SMALL_BLIND_BB, + "BB" => BIG_BLIND_BB, + _ => 0.0, + }; + Seat { position: position.to_string(), is_hero: *position == hero, stack_bb: stacks.get(*position).copied().unwrap_or(default_stack), action: None, bet_bb: blind } + }) + .collect(); + for seat in &mut seats { + seat.stack_bb -= seat.bet_bb; + } + let mut highest = BIG_BLIND_BB; + for action in actions { + let Some(seat) = seats.iter_mut().find(|s| s.position == action.position) else { continue }; + let total = seat.stack_bb + seat.bet_bb; + let target = match action.verb.as_str() { + "fold" => seat.bet_bb, + "call" => highest.min(total), + "allin" => total, + _ => action.bet_bb.unwrap_or(DEFAULT_RAISE_BB).min(total), + }; + seat.stack_bb = total - target; + seat.bet_bb = target; + seat.action = Some(action.verb.clone()); + highest = highest.max(target); + } + let pot_bb = seats.iter().map(|s| s.bet_bb).sum(); + QuizTable { seats, pot_bb } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn neighbors_stay_inside_the_grid() { + assert_eq!(neighbors("AA").len(), 2); + let mut around = neighbors("K9o"); + around.sort(); + assert_eq!(around, ["A9o", "K8o", "KTo", "Q9o"]); + assert_eq!(neighbors("22").len(), 2); + } + + #[test] + fn a_hand_is_borderline_when_a_neighbour_has_another_action() { + let mut hands: HashMap = crate::engines::range_scenarios::hand_classes().into_iter().map(|h| (h, 1)).collect(); + assert_eq!(borderline_neighbor(&hands, "K9o"), None); + hands.insert("K8o".into(), 2); + assert_eq!(borderline_neighbor(&hands, "K9o").as_deref(), Some("K8o")); + assert!(borderline_neighbor(&hands, "K8o").is_some(), "the other side of the edge is borderline too"); + } + + #[test] + fn bb_against_a_sb_limp_shows_the_blinds_and_the_limp() { + let actions = actions_of_line("btn:fold,sb:call", &HashMap::new()); + let table = build_table("3max", "BB", &actions, &HashMap::new(), 22.0); + assert_eq!(table.pot_bb, 2.0); + let seat = |p: &str| table.seats.iter().find(|s| s.position == p).unwrap(); + assert_eq!((seat("BTN").action.as_deref(), seat("BTN").stack_bb), (Some("fold"), 22.0)); + assert_eq!((seat("SB").action.as_deref(), seat("SB").bet_bb, seat("SB").stack_bb), (Some("call"), 1.0, 21.0)); + assert_eq!((seat("BB").is_hero, seat("BB").stack_bb), (true, 21.0)); + } + + #[test] + fn a_raise_takes_its_size_and_a_shove_the_whole_stack() { + let sizes = HashMap::from([("BTN".to_string(), 3.0)]); + let raise = build_table("3max", "BB", &actions_of_line("btn:raise,sb:fold", &sizes), &HashMap::new(), 20.0); + assert_eq!(raise.pot_bb, 3.0 + 0.5 + 1.0); + let shove = build_table("3max", "BB", &actions_of_line("btn:all-in,sb:fold", &HashMap::new()), &HashMap::new(), 8.0); + assert_eq!(shove.seats[0].bet_bb, 8.0); + assert_eq!(shove.seats[0].stack_bb, 0.0); + let default = build_table("hu", "BB", &actions_of_line("sb:raise", &HashMap::new()), &HashMap::new(), 10.0); + assert_eq!(default.pot_bb, 2.0 + 1.0); + } + + #[test] + fn real_stacks_replace_the_default() { + let stacks = HashMap::from([("BB".to_string(), 12.5)]); + let table = build_table("hu", "BB", &actions_of_line("sb:call", &HashMap::new()), &stacks, 10.0); + assert_eq!(table.seats[1].stack_bb, 11.5); + } +} diff --git a/crates/core/src/engines/range_check.rs b/crates/core/src/engines/range_check.rs new file mode 100644 index 00000000..a82a4c90 --- /dev/null +++ b/crates/core/src/engines/range_check.rs @@ -0,0 +1,446 @@ +//! Compares one preflop decision of the hero with the player's own ranges. +//! +//! The reference is the player's strategy and nothing else: a deviation means "not what you +//! planned", never "a mistake". Pure: the caller loads the ranges and the hands. + +use std::collections::HashMap; + +use crate::engines::actions::{parse_actions, raise_size_bb, ActionKind}; +use crate::engines::preflop_line::{betting_sequence, player_positions}; +use crate::engines::range_scenarios::{canonical_line, pick_scenario, Candidate, DepthRule}; +use crate::repos::heatmap::normalize_cards; +use crate::util::eq_ic; + +/// A played raise within this many big blinds of the planned size still follows the range. +pub const SIZE_TOLERANCE_BB: f64 = 0.5; + +/// An action of the player's palette, as the comparison reads it. +#[derive(Debug, Clone, PartialEq)] +pub struct ActionDef { + pub id: i64, + pub label: String, + pub immediate: String, + pub size_value: Option, + pub size_unit: Option, + pub response: String, +} + +/// Everything stored about the player's ranges. +#[derive(Debug, Clone, Default)] +pub struct RangeBook { + pub candidates: Vec, + pub actions: HashMap, + /// scenario id -> hand class -> action id + pub hands: HashMap>, + pub rule: Option, +} + +#[derive(Debug, Clone, Copy)] +pub struct DecisionInput<'a> { + pub preflop: &'a str, + pub positions: &'a str, + pub hero_position: &'a str, + pub hero_name: &'a str, + pub cards: Option<&'a str>, + pub stack_bb: f64, + pub blinds: &'a str, + pub opponent_is_reg: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + Match, + Deviation, + NoRange, + /// No decision to compare (no known cards, the hero never acted, odd table size). + Skipped, +} + +impl Status { + pub fn as_str(self) -> &'static str { + match self { + Status::Match => "match", + Status::Deviation => "deviation", + Status::NoRange => "no_range", + Status::Skipped => "skipped", + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Check { + pub status: Status, + pub scenario_id: Option, + pub hand_class: String, + pub expected_action_id: Option, + pub played_immediate: String, + pub played_response: Option, + /// "immediate", "size" or "response" for a deviation. + pub deviation_kind: Option<&'static str>, + pub depth_used_bb: Option, + pub format: String, + pub hero_position: String, + pub line: String, +} + +impl Check { + fn skipped() -> Self { + Self { + status: Status::Skipped, + scenario_id: None, + hand_class: String::new(), + expected_action_id: None, + played_immediate: String::new(), + played_response: None, + deviation_kind: None, + depth_used_bb: None, + format: String::new(), + hero_position: String::new(), + line: String::new(), + } + } +} + +/// "BTN SB" and friends are stored for heads-up seats: the seat the range was built for. +fn seat_of(position: &str) -> Option<&'static str> { + if position.contains("BB") { + Some("BB") + } else if position.contains("SB") { + Some("SB") + } else if position.contains("BTN") { + Some("BTN") + } else { + None + } +} + +fn verb_of(entry: &str) -> &str { + entry.split_once(':').map_or("", |(_, verb)| verb) +} + +fn is_raise_like(verb: &str) -> bool { + matches!(verb, "raise" | "bet" | "all-in") +} + +/// The plan's immediate action against what was played ("call" covers a limp). +fn immediate_matches(expected: &str, played: &str) -> bool { + match expected { + "fold" => played == "fold", + "check" => played == "check", + "call" => matches!(played, "call" | "limp"), + "limp" => played == "limp", + "raise" | "iso" | "threebet" => played == "raise", + "allin" => played == "allin", + _ => false, + } +} + +/// The planned size in big blinds, when it can be known. +fn planned_size_bb(action: &ActionDef, stack_bb: f64, facing_raise: bool) -> Option { + let value = action.size_value?; + match action.size_unit.as_deref()? { + "bb" => Some(value), + // A multiple of the bet to match: only the big blind is known when nobody raised. + "x" if !facing_raise => Some(value), + "pct_stack" => Some(value / 100.0 * stack_bb), + _ => None, + } +} + +fn response_of(verb: &str) -> &'static str { + match verb { + "fold" => "fold", + "call" => "call", + _ => "allin", + } +} + +/// Whether the last raise before the hero's second action was an all-in. +fn answered_raise_is_all_in(seq: &[String], first: usize, seat: &str) -> bool { + let own = |entry: &String| entry.split(':').next().is_some_and(|pos| pos.eq_ignore_ascii_case(seat)); + let Some(answer) = seq.iter().skip(first + 1).position(own).map(|i| first + 1 + i) else { return false }; + seq[first + 1..answer].iter().rev().find(|e| is_raise_like(verb_of(e))).is_some_and(|e| verb_of(e) == "all-in") +} + +/// Below this stack (in big blinds) the hero has no real choice. +const MIN_DECISION_STACK_BB: f64 = 1.0; + +/// Compares the hero's first preflop action (and the answer to a raise) with the range. +pub fn evaluate(input: &DecisionInput, book: &RangeBook) -> Check { + // Without a full big blind behind, the blinds already put the hero all-in: nothing to decide. + if input.stack_bb < MIN_DECISION_STACK_BB { + return Check::skipped(); + } + let (Some(seat), Some(cards)) = (seat_of(input.hero_position), input.cards) else { return Check::skipped() }; + let Some(hand_class) = normalize_cards(cards) else { return Check::skipped() }; + let format = match player_positions(input.positions).len() { + 2 => "hu", + 3 => "3max", + _ => return Check::skipped(), + }; + + let seq = betting_sequence(input.preflop, input.positions); + let own = |entry: &String| entry.split(':').next().is_some_and(|pos| pos.eq_ignore_ascii_case(seat)); + let Some(first) = seq.iter().position(own) else { return Check::skipped() }; + let first_verb = verb_of(&seq[first]).to_string(); + let facing_raise = seq[..first].iter().any(|e| is_raise_like(verb_of(e))); + let played_immediate = match first_verb.as_str() { + "fold" => "fold", + "check" => "check", + "call" if facing_raise => "call", + "call" => "limp", + "all-in" => "allin", + _ => "raise", + }; + + // The answer to a raise: the hero's next action once somebody raised after the first one. + let later = seq[first + 1..].iter().enumerate().find(|(_, e)| own(e)).map(|(i, e)| (first + 1 + i, verb_of(e).to_string())); + let played_response = later + .filter(|(index, _)| seq[first + 1..*index].iter().any(|e| is_raise_like(verb_of(e)))) + .map(|(_, verb)| response_of(&verb).to_string()); + + let line = canonical_line(&seq, seat); + let mut check = Check { + status: Status::NoRange, + scenario_id: None, + hand_class: hand_class.clone(), + expected_action_id: None, + played_immediate: played_immediate.to_string(), + played_response: played_response.clone(), + deviation_kind: None, + depth_used_bb: None, + format: format.to_string(), + hero_position: seat.to_string(), + line: line.clone(), + }; + + let rule = book.rule.unwrap_or(DepthRule::Nearest); + let Some(candidate) = pick_scenario(&book.candidates, format, &line, input.opponent_is_reg, input.stack_bb, rule) else { return check }; + let Some(action) = book.hands.get(&candidate.scenario_id).and_then(|h| h.get(&hand_class)).and_then(|id| book.actions.get(id)) else { return check }; + check.scenario_id = Some(candidate.scenario_id); + check.expected_action_id = Some(action.id); + check.depth_used_bb = Some(candidate.stack_bb); + + // A call that uses the whole stack is a shove in everything but name. + let hero_stacks_off: Vec = parse_actions(input.preflop) + .iter() + .filter(|a| eq_ic(&a.player, input.hero_name) && a.kind != ActionKind::Post) + .map(|a| a.kind == ActionKind::Call && a.is_all_in) + .collect(); + let stacks_off_at = |n: usize| hero_stacks_off.get(n).copied().unwrap_or(false); + + let mut kind = None; + let calls_all_in_as_planned = action.immediate == "allin" && matches!(played_immediate, "call" | "limp") && stacks_off_at(0); + if !immediate_matches(&action.immediate, played_immediate) && !calls_all_in_as_planned { + kind = Some("immediate"); + } else if played_immediate == "raise" { + let played_size = parse_actions(input.preflop) + .iter() + .find(|a| eq_ic(&a.player, input.hero_name) && a.kind != ActionKind::Post) + .and_then(|a| raise_size_bb(a, input.blinds)); + if let (Some(planned), Some(played)) = (planned_size_bb(action, input.stack_bb, facing_raise), played_size) { + if (planned - played).abs() > SIZE_TOLERANCE_BB { + kind = Some("size"); + } + } + } + if kind.is_none() && action.response != "none" { + if let Some(answer) = &played_response { + // Calling a raise that is already all-in, or with the whole stack, is the planned all-in. + let calls_a_shove = answer == "call" && action.response == "allin" && (answered_raise_is_all_in(&seq, first, seat) || stacks_off_at(1)); + if *answer != action.response && !calls_a_shove { + kind = Some("response"); + } + } + } + check.status = if kind.is_some() { Status::Deviation } else { Status::Match }; + check.deviation_kind = kind; + check +} + +#[cfg(test)] +mod tests { + use super::*; + + const SEATS: &str = "Hero:BB|Sb:SB|Btn:BTN"; + + fn action(id: i64, label: &str, immediate: &str, response: &str) -> ActionDef { + ActionDef { id, label: label.into(), immediate: immediate.into(), size_value: None, size_unit: None, response: response.into() } + } + + /// BB vs "SB limp" at 10 bb: AKo = Raise (fold if reraised), everything else = Check. + fn book() -> RangeBook { + let mut hands = HashMap::new(); + let mut range: HashMap = HashMap::new(); + for hand in crate::engines::range_scenarios::hand_classes() { + range.insert(hand, 1); + } + range.insert("AKo".into(), 2); + hands.insert(7, range); + RangeBook { + candidates: vec![Candidate { scenario_id: 7, spot_id: 1, format: "3max".into(), line: "btn:fold,sb:call".into(), opponent: "any".into(), stack_bb: 10.0 }], + actions: HashMap::from([(1, action(1, "CHECK", "check", "none")), (2, action(2, "ISO", "iso", "fold")), (3, action(3, "SHOVE", "allin", "none"))]), + hands, + rule: Some(DepthRule::Nearest), + } + } + + fn input<'a>(preflop: &'a str, cards: &'a str) -> DecisionInput<'a> { + DecisionInput { preflop, positions: SEATS, hero_position: "BB", hero_name: "Hero", cards: Some(cards), stack_bb: 10.0, blinds: "10/20", opponent_is_reg: false } + } + + const LIMP: &str = "Btn: Folds\nSb: Calls 10"; + + #[test] + fn playing_the_planned_action_matches() { + let check = evaluate(&input(&format!("{LIMP} +Hero: Raises 40 to 60 +Sb: Folds"), "Ah Kc"), &book()); + assert_eq!((check.status, check.expected_action_id, check.deviation_kind), (Status::Match, Some(2), None)); + } + + #[test] + fn a_different_immediate_action_is_a_deviation() { + let check = evaluate(&input(&format!("{LIMP}\nHero: Checks"), "Ah Kc"), &book()); + assert_eq!(check.status, Status::Deviation); + assert_eq!(check.deviation_kind, Some("immediate")); + assert_eq!((check.expected_action_id, check.played_immediate.as_str()), (Some(2), "check")); + } + + #[test] + fn a_hand_the_range_plays_as_planned_is_a_match() { + let check = evaluate(&input(&format!("{LIMP}\nHero: Checks"), "7h 2c"), &book()); + assert_eq!((check.status, check.scenario_id, check.depth_used_bb), (Status::Match, Some(7), Some(10.0))); + assert_eq!(check.hand_class, "72o"); + } + + #[test] + fn a_raise_of_another_size_still_follows_an_unsized_raise() { + let check = evaluate(&input(&format!("{LIMP}\nHero: Raises 40 to 60\nSb: Folds"), "Ah Kc"), &book()); + assert_eq!(check.status, Status::Match); + } + + #[test] + fn a_planned_size_is_compared_within_the_tolerance() { + let mut b = book(); + let iso = b.actions.get_mut(&2).unwrap(); + iso.size_value = Some(3.0); + iso.size_unit = Some("bb".into()); + let close = evaluate(&input(&format!("{LIMP}\nHero: Raises 40 to 70\nSb: Folds"), "Ah Kc"), &b); + assert_eq!(close.status, Status::Match, "3.5 bb is within 0.5 of 3 bb"); + let far = evaluate(&input(&format!("{LIMP}\nHero: Raises 40 to 100\nSb: Folds"), "Ah Kc"), &b); + assert_eq!((far.status, far.deviation_kind), (Status::Deviation, Some("size"))); + } + + #[test] + fn the_answer_to_a_raise_is_compared_with_the_planned_response() { + let call = evaluate(&input(&format!("{LIMP}\nHero: Raises 40 to 60\nSb: Raises 80 to 140\nHero: Calls 80"), "Ah Kc"), &book()); + assert_eq!((call.status, call.deviation_kind), (Status::Deviation, Some("response"))); + assert_eq!((call.played_immediate.as_str(), call.played_response.as_deref()), ("raise", Some("call"))); + let fold = evaluate(&input(&format!("{LIMP}\nHero: Raises 40 to 60\nSb: Raises 80 to 140\nHero: Folds"), "Ah Kc"), &book()); + assert_eq!(fold.status, Status::Match); + } + + fn book_planning_to_stack_off() -> RangeBook { + let mut b = book(); + b.actions.insert(4, action(4, "ISO/BROKE", "iso", "allin")); + b.hands.get_mut(&7).expect("scenario 7 exists").insert("AKo".into(), 4); + b + } + + #[test] + fn calling_a_shove_follows_a_planned_all_in_answer() { + let preflop = format!("{LIMP}\nHero: Raises 40 to 60\nSb: Raises 400 to 460 and is all-in\nHero: Calls 400"); + let check = evaluate(&input(&preflop, "Ah Kc"), &book_planning_to_stack_off()); + assert_eq!((check.status, check.played_response.as_deref()), (Status::Match, Some("call"))); + } + + #[test] + fn calling_a_raise_that_is_not_all_in_still_deviates_from_a_planned_all_in_answer() { + let preflop = format!("{LIMP}\nHero: Raises 40 to 60\nSb: Raises 80 to 140\nHero: Calls 80"); + let check = evaluate(&input(&preflop, "Ah Kc"), &book_planning_to_stack_off()); + assert_eq!((check.status, check.deviation_kind), (Status::Deviation, Some("response"))); + } + + /// Hero in the BB at 10 bb: everything = Call, AKo = Shove (a re-raise all-in), 72o = Fold. + fn book_against_an_open(line: &str) -> RangeBook { + let mut range: HashMap = HashMap::new(); + for hand in crate::engines::range_scenarios::hand_classes() { + range.insert(hand, 1); + } + range.insert("AKo".into(), 3); + range.insert("72o".into(), 4); + RangeBook { + candidates: vec![Candidate { scenario_id: 9, spot_id: 1, format: "3max".into(), line: line.into(), opponent: "any".into(), stack_bb: 10.0 }], + actions: HashMap::from([(1, action(1, "CALL", "call", "none")), (3, action(3, "SHOVE", "allin", "none")), (4, action(4, "FOLD", "fold", "none"))]), + hands: HashMap::from([(9, range)]), + rule: Some(DepthRule::Nearest), + } + } + + #[test] + fn calling_an_open_with_the_whole_stack_is_still_a_call() { + let preflop = "Btn: Raises 40 to 60\nSb: Folds\nHero: Calls 140 and is all-in"; + let check = evaluate(&input(preflop, "7h 2c"), &book_against_an_open("btn:raise,sb:fold")); + assert_eq!((check.status, check.played_immediate.as_str()), (Status::Deviation, "call"), "the plan is Fold"); + let calling = evaluate(&input(preflop, "9h 9c"), &book_against_an_open("btn:raise,sb:fold")); + assert_eq!((calling.status, calling.played_immediate.as_str()), (Status::Match, "call")); + } + + #[test] + fn calling_all_in_for_less_follows_a_planned_shove() { + let preflop = "Btn: Raises 40 to 60\nSb: Folds\nHero: Calls 140 and is all-in"; + let check = evaluate(&input(preflop, "Ah Kc"), &book_against_an_open("btn:raise,sb:fold")); + assert_eq!(check.status, Status::Match); + } + + #[test] + fn an_opponent_calling_all_in_is_read_as_a_call_in_the_line() { + let preflop = "Btn: Raises 40 to 60\nSb: Calls 30 and is all-in\nHero: Folds"; + let check = evaluate(&input(preflop, "7h 2c"), &book_against_an_open("btn:raise,sb:call")); + assert_eq!((check.status, check.line.as_str()), (Status::Match, "btn:raise,sb:call")); + } + + #[test] + fn a_hero_left_with_less_than_a_big_blind_has_no_decision() { + let preflop = "Hero: Posts BB 20\nSb: Calls 10 and is all-in"; + let check = evaluate(&DecisionInput { stack_bb: 0.5, ..input(preflop, "3h 3c") }, &book()); + assert_eq!(check.status, Status::Skipped); + } + + #[test] + fn limping_all_in_follows_a_planned_shove() { + let mut b = book(); + b.actions.insert(5, action(5, "SHOVE", "allin", "none")); + b.hands.get_mut(&7).expect("scenario 7 exists").insert("33".into(), 5); + let check = evaluate(&input(&format!("{LIMP}\nHero: Calls 10 and is all-in"), "3h 3c"), &b); + assert_eq!(check.status, Status::Match); + } + + #[test] + fn a_situation_without_a_range_is_reported_as_such() { + let preflop = "Btn: Raises 40 to 60\nSb: Folds\nHero: Calls 40"; + let check = evaluate(&input(preflop, "Ah Kc"), &book()); + assert_eq!((check.status, check.scenario_id, check.line.as_str()), (Status::NoRange, None, "btn:raise,sb:fold")); + } + + #[test] + fn a_reg_variant_is_used_only_against_a_reg() { + let mut b = book(); + let mut range = b.hands[&7].clone(); + range.insert("72o".into(), 3); + b.hands.insert(8, range); + b.candidates.push(Candidate { scenario_id: 8, spot_id: 2, format: "3max".into(), line: "btn:fold,sb:call".into(), opponent: "reg".into(), stack_bb: 10.0 }); + let preflop = format!("{LIMP}\nHero: Checks"); + let normal = evaluate(&input(&preflop, "7h 2c"), &b); + assert_eq!(normal.scenario_id, Some(7)); + let reg = evaluate(&DecisionInput { opponent_is_reg: true, ..input(&preflop, "7h 2c") }, &b); + assert_eq!((reg.scenario_id, reg.status), (Some(8), Status::Deviation)); + } + + #[test] + fn hands_without_a_decision_are_skipped() { + assert_eq!(evaluate(&DecisionInput { cards: None, ..input(LIMP, "Ah Kc") }, &book()).status, Status::Skipped); + assert_eq!(evaluate(&input("Btn: Folds\nSb: Folds", "Ah Kc"), &book()).status, Status::Skipped, "the hero never acted"); + } +} diff --git a/crates/core/src/engines/range_scenarios.rs b/crates/core/src/engines/range_scenarios.rs new file mode 100644 index 00000000..f93da040 --- /dev/null +++ b/crates/core/src/engines/range_scenarios.rs @@ -0,0 +1,286 @@ +//! Pure rules of the player's own range scenarios: situation keys, scenario choice, names, colours. + +/// Light and dark text colours tried on an action colour. +const LIGHT_TEXT: &str = "#ffffff"; +const DARK_TEXT: &str = "#000000"; + +/// How a stack between two depths picks its range. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DepthRule { + /// The closest depth, the smaller one on a tie. + Nearest, + /// The deepest depth that does not exceed the stack, else the smallest. + Below, +} + +impl DepthRule { + pub fn parse(value: &str) -> Self { + if value.eq_ignore_ascii_case("below") { + Self::Below + } else { + Self::Nearest + } + } +} + +/// A stored range a hand could belong to. +#[derive(Debug, Clone, PartialEq)] +pub struct Candidate { + pub scenario_id: i64, + pub spot_id: i64, + pub format: String, + pub line: String, + /// "any" or "reg". + pub opponent: String, + pub stack_bb: f64, +} + +/// The actions of the players who speak before the hero, lower-cased and comma-separated +/// ("BTN:fold,SB:call"); empty when the hero speaks first. +pub fn canonical_line(seq: &[String], hero_pos: &str) -> String { + seq.iter() + .take_while(|entry| !entry.split(':').next().is_some_and(|pos| pos.eq_ignore_ascii_case(hero_pos))) + .map(|entry| entry.to_lowercase()) + .collect::>() + .join(",") +} + +/// The range a decision falls in: same format and line, the reg variant first when the opponent +/// is a reg (then "any"), then the depth chosen by `rule`. +pub fn pick_scenario<'a>( + candidates: &'a [Candidate], + format: &str, + line: &str, + opponent_is_reg: bool, + stack_bb: f64, + rule: DepthRule, +) -> Option<&'a Candidate> { + let same_situation = |c: &&Candidate| c.format == format && c.line == line; + let with_opponent = |kind: &str| candidates.iter().filter(same_situation).filter(|c| c.opponent == kind).collect::>(); + + let mut pool = if opponent_is_reg { with_opponent("reg") } else { Vec::new() }; + if pool.is_empty() { + pool = with_opponent("any"); + } + match rule { + DepthRule::Nearest => pool.into_iter().min_by(|a, b| { + let (da, db) = ((a.stack_bb - stack_bb).abs(), (b.stack_bb - stack_bb).abs()); + da.total_cmp(&db).then(a.stack_bb.total_cmp(&b.stack_bb)) + }), + DepthRule::Below => pool + .iter() + .filter(|c| c.stack_bb <= stack_bb) + .max_by(|a, b| a.stack_bb.total_cmp(&b.stack_bb)) + .or_else(|| pool.iter().min_by(|a, b| a.stack_bb.total_cmp(&b.stack_bb))) + .copied(), + } +} + +/// A short reading of a line: "SB limp", "BTN open, SB call", "BTN shove". +fn describe_line(line: &str) -> String { + let mut raised = false; + let mut parts = Vec::new(); + for entry in line.split(',').filter(|e| !e.is_empty()) { + let Some((pos, verb)) = entry.split_once(':') else { continue }; + let pos = pos.to_uppercase(); + let text = match verb { + "fold" => continue, + "call" if raised => "call", + "call" => "limp", + "raise" | "bet" if raised => "3bet", + "raise" | "bet" => { + raised = true; + "open" + } + "all-in" => { + raised = true; + "shove" + } + other => other, + }; + parts.push(format!("{pos} {text}")); + } + parts.join(", ") +} + +/// The name the wizard proposes: "BB vs SB limp · Reg", "BTN first in", "BB (HU) vs SB open". +pub fn default_name(format: &str, hero_position: &str, line: &str, opponent: &str) -> String { + let hero = hero_position.to_uppercase(); + let seat = if format == "hu" { format!("{hero} (HU)") } else { hero }; + let described = describe_line(line); + let mut name = if line.is_empty() { + format!("{seat} first in") + } else if described.is_empty() { + format!("{seat} vs folds") + } else { + format!("{seat} vs {described}") + }; + if opponent == "reg" { + name.push_str(" · Reg"); + } + name +} + +fn channel(value: u8) -> f64 { + let v = f64::from(value) / 255.0; + if v <= 0.03928 { + v / 12.92 + } else { + ((v + 0.055) / 1.055).powf(2.4) + } +} + +/// Parses "#rrggbb" (or "#rgb"). +pub fn parse_hex(hex: &str) -> Option<[u8; 3]> { + let digits = hex.strip_prefix('#')?; + let expanded: String = match digits.len() { + 3 => digits.chars().flat_map(|c| [c, c]).collect(), + 6 => digits.to_string(), + _ => return None, + }; + let value = u32::from_str_radix(&expanded, 16).ok()?; + Some([(value >> 16) as u8, (value >> 8) as u8, value as u8]) +} + +fn luminance(rgb: [u8; 3]) -> f64 { + 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]) +} + +/// WCAG contrast ratio between two colours. +pub fn contrast(a: [u8; 3], b: [u8; 3]) -> f64 { + let (la, lb) = (luminance(a), luminance(b)); + let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) }; + (hi + 0.05) / (lo + 0.05) +} + +/// The more readable of a light and a dark text colour on `bg_hex`. +pub fn text_color(bg_hex: &str) -> &'static str { + let Some(bg) = parse_hex(bg_hex) else { return LIGHT_TEXT }; + let (light, dark) = (parse_hex(LIGHT_TEXT).unwrap_or([255; 3]), parse_hex(DARK_TEXT).unwrap_or([0; 3])); + if contrast(bg, light) >= contrast(bg, dark) { + LIGHT_TEXT + } else { + DARK_TEXT + } +} + + +/// Card ranks from the highest, the order of the 13 x 13 grid. +pub const RANKS: [char; 13] = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2']; +/// Distinct two-card hand classes. +pub const HAND_CLASS_COUNT: usize = 169; +/// Every two-card combination of a deck. +pub const TOTAL_COMBOS: u32 = 1326; + +/// The 169 hand classes in grid order: pairs on the diagonal, suited above it, offsuit below. +pub fn hand_classes() -> Vec { + let mut out = Vec::with_capacity(HAND_CLASS_COUNT); + for (i, a) in RANKS.iter().enumerate() { + for (j, b) in RANKS.iter().enumerate() { + out.push(match i.cmp(&j) { + std::cmp::Ordering::Equal => format!("{a}{b}"), + std::cmp::Ordering::Less => format!("{a}{b}s"), + std::cmp::Ordering::Greater => format!("{b}{a}o"), + }); + } + } + out +} + +/// Whether `hand` is one of the 169 classes. +pub fn is_hand_class(hand: &str) -> bool { + let chars: Vec = hand.chars().collect(); + let rank = |c: &char| RANKS.iter().position(|r| r == c); + match chars.as_slice() { + [a, b] => a == b && rank(a).is_some(), + [a, b, kind @ ('s' | 'o')] => matches!((rank(a), rank(b)), (Some(i), Some(j)) if i < j) && matches!(kind, 's' | 'o'), + _ => false, + } +} + +/// Number of card combinations of a hand class: 6 for a pair, 4 suited, 12 offsuit. +pub fn combos(hand: &str) -> u32 { + match hand.len() { + 2 => 6, + _ if hand.ends_with('s') => 4, + _ => 12, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn seq(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + fn cand(id: i64, opponent: &str, stack: f64) -> Candidate { + Candidate { scenario_id: id, spot_id: id, format: "3max".into(), line: "btn:fold,sb:call".into(), opponent: opponent.into(), stack_bb: stack } + } + + #[test] + fn canonical_line_stops_at_the_hero() { + assert_eq!(canonical_line(&seq(&["BTN:fold", "SB:call", "BB:check"]), "BB"), "btn:fold,sb:call"); + assert_eq!(canonical_line(&seq(&["BTN:raise", "SB:fold"]), "BTN"), ""); + assert_eq!(canonical_line(&seq(&["SB:call", "BB:check"]), "BB"), "sb:call", "heads-up line"); + assert_eq!(canonical_line(&seq(&["SB:raise", "BB:fold"]), "SB"), ""); + } + + #[test] + fn a_stack_between_depths_follows_the_rule() { + let c = [cand(1, "any", 15.0), cand(2, "any", 10.0)]; + let pick = |stack, rule| pick_scenario(&c, "3max", "btn:fold,sb:call", false, stack, rule).map(|c| c.stack_bb); + assert_eq!(pick(12.0, DepthRule::Below), Some(10.0)); + assert_eq!(pick(12.0, DepthRule::Nearest), Some(10.0)); + assert_eq!(pick(13.0, DepthRule::Nearest), Some(15.0)); + assert_eq!(pick(12.5, DepthRule::Nearest), Some(10.0), "a tie takes the smaller depth"); + assert_eq!(pick(8.0, DepthRule::Below), Some(10.0), "below every depth takes the smallest"); + assert_eq!(pick(30.0, DepthRule::Below), Some(15.0)); + } + + #[test] + fn the_reg_variant_is_used_only_against_a_reg() { + let c = [cand(1, "any", 10.0), cand(2, "reg", 10.0)]; + let id = |reg| pick_scenario(&c, "3max", "btn:fold,sb:call", reg, 10.0, DepthRule::Nearest).map(|c| c.scenario_id); + assert_eq!(id(true), Some(2)); + assert_eq!(id(false), Some(1)); + let only_reg = [cand(2, "reg", 10.0)]; + assert_eq!(pick_scenario(&only_reg, "3max", "btn:fold,sb:call", false, 10.0, DepthRule::Nearest), None); + let only_any = [cand(1, "any", 10.0)]; + assert_eq!(pick_scenario(&only_any, "3max", "btn:fold,sb:call", true, 10.0, DepthRule::Nearest).map(|c| c.scenario_id), Some(1), "falls back to any"); + assert_eq!(pick_scenario(&c, "hu", "btn:fold,sb:call", false, 10.0, DepthRule::Nearest), None); + } + + #[test] + fn default_names_read_like_the_table() { + assert_eq!(default_name("3max", "BB", "btn:fold,sb:call", "reg"), "BB vs SB limp · Reg"); + assert_eq!(default_name("3max", "BTN", "", "any"), "BTN first in"); + assert_eq!(default_name("hu", "BB", "sb:raise", "any"), "BB (HU) vs SB open"); + assert_eq!(default_name("3max", "BB", "btn:raise,sb:all-in", "any"), "BB vs BTN open, SB shove"); + assert_eq!(default_name("3max", "BB", "btn:fold,sb:fold", "any"), "BB vs folds"); + } + + #[test] + fn the_grid_holds_169_classes_and_1326_combos() { + let classes = hand_classes(); + assert_eq!(classes.len(), HAND_CLASS_COUNT); + assert_eq!(classes.iter().map(|h| combos(h)).sum::(), TOTAL_COMBOS); + assert_eq!((classes[0].as_str(), classes[1].as_str(), classes[13].as_str()), ("AA", "AKs", "AKo")); + assert!(classes.iter().all(|h| is_hand_class(h))); + assert!(!is_hand_class("KAs") && !is_hand_class("AAs") && !is_hand_class("AK") && !is_hand_class("A1o")); + } + + #[test] + fn text_is_readable_on_every_proposed_shade() { + let shades = [ + "#2a2f39", "#3b4352", "#6b7080", "#4caf50", "#34c27a", "#7fd18f", "#5b8def", "#7aa7ff", "#6b7aa1", "#a07cf0", "#5d4a8c", "#e0a23f", + "#8a6a33", "#f97316", "#ff6b5b", "#e0c341", + ]; + for shade in shades { + let bg = parse_hex(shade).unwrap(); + let fg = parse_hex(text_color(shade)).unwrap(); + assert!(contrast(bg, fg) >= 4.5, "{shade} has contrast {}", contrast(bg, fg)); + } + } +} diff --git a/crates/core/src/repos/hands_query.rs b/crates/core/src/repos/hands_query.rs index dcfaef2e..d6dcd9d0 100644 --- a/crates/core/src/repos/hands_query.rs +++ b/crates/core/src/repos/hands_query.rs @@ -46,6 +46,8 @@ pub struct HandsQuery { pub max_pot: Option, pub hero_name: Option, pub sort_by: Option, + /// Only the hands where the hero left their own range (needs the stored range checks). + pub range_deviation: bool, } impl Default for HandsQuery { @@ -62,6 +64,7 @@ impl Default for HandsQuery { max_pot: None, hero_name: None, sort_by: None, + range_deviation: false, } } } @@ -226,6 +229,9 @@ pub fn get_hands(conn: &Connection, q: &HandsQuery) -> Result { clauses.push("total_pot <= @maxPot".into()); binds.push(("@maxPot", SqlValue::Real(p))); } + if q.range_deviation { + clauses.push("h.id IN (SELECT hand_id FROM hand_range_checks WHERE status = 'deviation')".into()); + } match non_empty(&q.result).map(str::to_lowercase).as_deref() { Some("won") => clauses.push("ph.net_profit > 0".into()), Some("lost") => clauses.push("ph.net_profit < 0".into()), diff --git a/crates/core/src/services/analysis.rs b/crates/core/src/services/analysis.rs index 06054c4b..3737dc73 100644 --- a/crates/core/src/services/analysis.rs +++ b/crates/core/src/services/analysis.rs @@ -14,6 +14,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::engines::actions::{parse_actions, ActionKind}; +use crate::engines::preflop_line::{matches_action_sequence, player_positions, split_player_and_content, strip_timestamp}; use crate::parsers::regex; use crate::repos::hands_query::{self, hero_resolution_sql}; use crate::repos::heatmap::normalize_cards; @@ -55,6 +56,8 @@ pub struct AnalysisFilters { pub date_to: Option, /// "all", "reg" or "fish". pub opponent_type: Option, + /// Restricts the read to one hand. + pub hand_id: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -130,6 +133,10 @@ pub fn hands_for_analysis(conn: &Connection, f: &AnalysisFilters) -> Result= @dateFrom".into()); binds.push(("@dateFrom".into(), SqlValue::Text(d.into()))); @@ -202,25 +209,6 @@ pub fn hands_for_analysis(conn: &Connection, f: &AnalysisFilters) -> Result String { - let line = line.trim(); - match line.split_once(" - ") { - Some((_, rest)) => rest.trim().to_string(), - None => line.to_string(), - } -} - -/// Splits "Name: action" or "Name action" into the name and the lower-cased action text. -fn split_player_and_content(line: &str) -> Option<(String, String)> { - let line = strip_timestamp(line); - if let Some(colon) = line.find(':') { - return Some((line[..colon].trim().to_string(), line[colon + 1..].trim().to_lowercase())); - } - let space = line.find(' ')?; - Some((line[..space].trim().to_string(), line[space..].trim().to_lowercase())) -} - /// The action text when `line` is an action of `player`. fn action_of_player(line: &str, player: &str) -> Option { if line.trim().is_empty() { @@ -240,17 +228,6 @@ fn action_of_player(line: &str, player: &str) -> Option { None } -fn player_positions(map: &str) -> HashMap { - let mut out = HashMap::new(); - for pair in map.split('|') { - let parts: Vec<&str> = pair.split(':').collect(); - if let [name, position] = parts[..] { - out.insert(name.to_lowercase(), position.to_string()); - } - } - out -} - fn big_blind(blinds: &str) -> f64 { crate::engines::actions::big_blind(blinds) as f64 } @@ -298,45 +275,6 @@ fn matches_street_by_position(text: &str, btn: &Option, sb: &Option Vec { - let seats = player_positions(&hand.player_positions); - let mut out = Vec::new(); - for line in hand.preflop.split('\n').filter(|l| !l.is_empty()) { - let Some((player, content)) = split_player_and_content(line) else { continue }; - let Some(position) = seats.get(&player.to_lowercase()) else { continue }; - let verb = if content.contains("all-in") { - "all-in" - } else if content.contains("raises") { - "raise" - } else if content.contains("bets") { - "bet" - } else if content.contains("calls") { - "call" - } else if content.contains("checks") { - "check" - } else if content.contains("folds") { - "fold" - } else { - // Posts, antes and anything unknown are skipped. - continue; - }; - out.push(format!("{position}:{verb}")); - } - out -} - -fn matches_action_sequence(hand: &AnalysisHand, sequence: &[String]) -> bool { - if sequence.is_empty() { - return true; - } - if hand.preflop.is_empty() { - return false; - } - let actual = preflop_sequence(hand); - actual.len() >= sequence.len() && sequence.iter().zip(&actual).all(|(wanted, got)| wanted.eq_ignore_ascii_case(got)) -} - fn matches_situation(hand: &AnalysisHand, situation: &str) -> bool { match situation.to_lowercase().as_str() { "flop" => !hand.flop.is_empty(), @@ -441,14 +379,14 @@ fn matches_situation_id(hand: &AnalysisHand, situation_id: &str, positions: Opti } /// Lower-cased names of the regulars, read once for a whole analysis. -fn regular_players(conn: &Connection) -> Result> { +pub(crate) fn regular_players(conn: &Connection) -> Result> { let mut stmt = conn.prepare("SELECT name FROM players WHERE is_reg = 1")?; let names = stmt.query_map([], |r| r.get::<_, String>(0))?.collect::, _>>()?; Ok(names.into_iter().map(|n| n.to_lowercase()).collect()) } /// Whether at least one opponent of the hero in this hand is a regular. -fn opponent_is_reg(regulars: &HashSet, hand: &AnalysisHand, hero: Option<&str>) -> bool { +pub(crate) fn opponent_is_reg(regulars: &HashSet, hand: &AnalysisHand, hero: Option<&str>) -> bool { let Some(hero) = hero.or(hand.hero_name.as_deref()).filter(|h| !h.is_empty()) else { return false }; hand.player_positions .split('|') @@ -492,7 +430,7 @@ fn filter_hands(conn: &Connection, hands: Vec, f: &AnalysisFilters } match f.action_sequence.as_ref().filter(|s| !s.is_empty()) { Some(sequence) => { - if !matches_action_sequence(&hand, sequence) { + if !matches_action_sequence(&hand.preflop, &hand.player_positions, sequence) { continue; } } @@ -1007,15 +945,6 @@ mod tests { assert_eq!(counts, [1, 0, 0, 0, 1]); } - #[test] - fn action_sequences_match_in_order() { - let h = hand("SB: Posts SB 10\nBB: Posts BB 20\nHero: Raises to 50\nSB: Calls 40\nBB: Folds", "Hero:BTN|SB:SB|BB:BB"); - assert!(matches_action_sequence(&h, &["BTN:raise".into(), "SB:call".into()])); - assert!(matches_action_sequence(&h, &["btn:Raise".into()])); - assert!(!matches_action_sequence(&h, &["BTN:call".into()])); - assert!(!matches_action_sequence(&h, &["BTN:raise".into(), "SB:call".into(), "BB:fold".into(), "BTN:check".into()])); - } - #[test] fn street_filters_need_every_named_seat_to_act() { let h = hand("SB: Posts SB 10\nHero: Raises to 50\nSB: Folds", "Hero:BTN|SB:SB|BB:BB"); diff --git a/crates/core/src/services/mod.rs b/crates/core/src/services/mod.rs index 19d435d5..bb7ca5c1 100644 --- a/crates/core/src/services/mod.rs +++ b/crates/core/src/services/mod.rs @@ -6,7 +6,12 @@ pub mod hud; pub mod importer; pub mod live_import; pub mod summaries; +pub mod range_adherence; +pub mod ranges_io; +pub mod review; pub mod table_pairing; +pub mod training; +pub mod user_ranges; pub use importer::{ImportSummary, Importer}; pub use live_import::{is_history_file, list_history_files, LiveImport, LiveMode}; diff --git a/crates/core/src/services/range_adherence.rs b/crates/core/src/services/range_adherence.rs new file mode 100644 index 00000000..8dcebca1 --- /dev/null +++ b/crates/core/src/services/range_adherence.rs @@ -0,0 +1,734 @@ +//! How well the hero follows their own ranges: the stored comparison of every preflop decision, +//! its summaries, and the check of a single hand. +//! +//! The stored rows are derived data. Any change to the ranges clears them (`invalidate`) and the +//! next read recomputes what is missing (`ensure_computed`), so they never describe old ranges. + +use std::collections::{HashMap, HashSet}; + +use rusqlite::types::Value as SqlValue; +use rusqlite::{params, Connection, OptionalExtension, ToSql}; +use serde_json::{json, Value}; + +use crate::engines::actions::stack_in_bb; +use crate::engines::range_check::{evaluate, ActionDef, Check, DecisionInput, RangeBook, Status}; +use crate::engines::range_scenarios::{Candidate, DepthRule}; +use crate::repos::hands_query::hero_resolution_sql; +use crate::services::analysis::{hands_for_analysis, opponent_is_reg, regular_players, AnalysisFilters, AnalysisHand}; +use crate::services::user_ranges; +use crate::Result; + +/// Deviations listed in the detail of a scenario. +const RECENT_DEVIATIONS: i64 = 20; +/// Hands per query when reading the other players' stacks. +const STACK_CHUNK: usize = 400; +/// Lines shown as "without a range". +const FREQUENT_LINES: i64 = 3; + +/// Clears the stored comparisons: the ranges they were computed from changed. +pub fn invalidate(conn: &Connection) -> Result<()> { + conn.execute("DELETE FROM hand_range_checks", [])?; + Ok(()) +} + +fn load_book(conn: &Connection) -> Result { + let mut book = RangeBook { rule: Some(DepthRule::parse(&user_ranges::setting(conn, "depth_rule").ok().flatten().unwrap_or_default())), ..Default::default() }; + { + let mut stmt = conn.prepare("SELECT id, label, immediate, size_value, size_unit, response FROM range_actions")?; + for row in stmt.query_map([], |r| { + Ok(ActionDef { id: r.get(0)?, label: r.get(1)?, immediate: r.get(2)?, size_value: r.get(3)?, size_unit: r.get(4)?, response: r.get(5)? }) + })? { + let action = row?; + book.actions.insert(action.id, action); + } + } + { + let mut stmt = conn.prepare( + "SELECT sc.id, sc.spot_id, sp.format, sp.line, sp.opponent, sc.stack_bb FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id", + )?; + for row in stmt.query_map([], |r| { + Ok(Candidate { scenario_id: r.get(0)?, spot_id: r.get(1)?, format: r.get(2)?, line: r.get(3)?, opponent: r.get(4)?, stack_bb: r.get(5)? }) + })? { + book.candidates.push(row?); + } + } + let mut stmt = conn.prepare("SELECT scenario_id, hand, action_id FROM range_hands")?; + for row in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))? { + let (scenario, hand, action) = row?; + book.hands.entry(scenario).or_default().insert(hand, action); + } + Ok(book) +} + +/// Stacks of every player in the given hands: hand id -> (player, stack). +pub(crate) fn stacks_of(conn: &Connection, ids: &[&str]) -> Result>> { + let mut out: HashMap> = HashMap::new(); + for chunk in ids.chunks(STACK_CHUNK) { + let marks = vec!["?"; chunk.len()].join(","); + let mut stmt = conn.prepare(&format!("SELECT hand_id, player_name, stack FROM player_hands WHERE hand_id IN ({marks})"))?; + let binds: Vec<&dyn ToSql> = chunk.iter().map(|id| id as &dyn ToSql).collect(); + for row in stmt.query_map(&binds[..], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option>(2)?.unwrap_or(0.0))))? { + let (hand, player, stack) = row?; + out.entry(hand).or_default().push((player, stack)); + } + } + Ok(out) +} + +/// The stack that decides the depth: the hero's, capped by the deepest opponent's. +fn effective_stack_bb(hand: &AnalysisHand, players: &[(String, f64)]) -> Option { + let hero = hand.hero_name.as_deref().unwrap_or_default(); + let deepest_opponent = players.iter().filter(|(name, _)| !name.eq_ignore_ascii_case(hero)).map(|(_, stack)| *stack).fold(0.0, f64::max); + let stack = if deepest_opponent > 0.0 { hand.hero_stack.min(deepest_opponent) } else { hand.hero_stack }; + stack_in_bb(stack, &hand.blinds) +} + +fn check_of(hand: &AnalysisHand, stack_bb: f64, regulars: &HashSet, book: &RangeBook) -> Check { + let hero = hand.hero_name.as_deref().unwrap_or_default(); + evaluate( + &DecisionInput { + preflop: &hand.preflop, + positions: &hand.player_positions, + hero_position: &hand.hero_position, + hero_name: hero, + cards: hand.hero_cards.as_deref(), + stack_bb, + blinds: &hand.blinds, + opponent_is_reg: opponent_is_reg(regulars, hand, Some(hero)), + }, + book, + ) +} + +fn played_at(hand: &AnalysisHand) -> String { + hand.date.format("%Y-%m-%dT%H:%M:%S").to_string() +} + +fn ev_bb(hand: &AnalysisHand) -> Option { + let bb = crate::engines::actions::big_blind(&hand.blinds) as f64; + (bb > 0.0).then(|| hand.ev_chips.unwrap_or(hand.profit) / bb) +} + +/// Computes the comparison of the hero's hands that have none yet. Returns how many were computed. +/// Without any scenario there is nothing to compare with and nothing is stored. +pub fn ensure_computed(conn: &mut Connection, hero: &str) -> Result { + if hero.trim().is_empty() { + return Ok(0); + } + let book = load_book(conn)?; + if book.candidates.is_empty() { + return Ok(0); + } + let all = hands_for_analysis(conn, &AnalysisFilters { hero_name: Some(hero.to_string()), ..Default::default() })?; + let known: HashSet = { + let mut stmt = conn.prepare("SELECT hand_id FROM hand_range_checks")?; + let ids = stmt.query_map([], |r| r.get(0))?.collect::, _>>()?; + ids + }; + let missing: Vec<&AnalysisHand> = all.iter().filter(|h| !known.contains(&h.hand_id)).collect(); + if missing.is_empty() { + return Ok(0); + } + let regulars = regular_players(conn)?; + let ids: Vec<&str> = missing.iter().map(|h| h.hand_id.as_str()).collect(); + let stacks = stacks_of(conn, &ids)?; + + let tx = conn.transaction()?; + { + let mut insert = tx.prepare( + "INSERT OR REPLACE INTO hand_range_checks + (hand_id, hero_name, played_at, scenario_id, hand_class, cards, format, hero_position, line, expected_action_id, + played_immediate, played_response, status, deviation_kind, depth_used_bb, stack_bb, ev_bb, computed_at, vs_reg) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)", + )?; + let now = user_ranges::now(); + for hand in &missing { + let players = stacks.get(&hand.hand_id).map(Vec::as_slice).unwrap_or_default(); + let stack_bb = effective_stack_bb(hand, players); + let check = match stack_bb { + Some(stack) => check_of(hand, stack, ®ulars, &book), + None => skipped_check(), + }; + insert.execute(params![ + hand.hand_id, + hand.hero_name, + played_at(hand), + check.scenario_id, + check.hand_class, + hand.hero_cards, + check.format, + check.hero_position, + check.line, + check.expected_action_id, + check.played_immediate, + check.played_response, + check.status.as_str(), + check.deviation_kind, + check.depth_used_bb, + stack_bb, + ev_bb(hand), + now, + opponent_is_reg(®ulars, hand, hand.hero_name.as_deref()) + ])?; + } + } + tx.commit()?; + Ok(missing.len()) +} + +/// A hand with no usable stack has no decision to compare. +fn skipped_check() -> Check { + evaluate(&DecisionInput { preflop: "", positions: "", hero_position: "", hero_name: "", cards: None, stack_bb: 0.0, blinds: "", opponent_is_reg: false }, &RangeBook::default()) +} + +// --------------------------------------------------------------------------------------------- +// Reading +// --------------------------------------------------------------------------------------------- + +/// A date bound as the stored rows write it: the app's filters send "2026-11-01 00:00:00" while +/// `played_at` keeps the ISO "T", and the two only compare correctly in one format. +fn stored_bound(bound: &str) -> String { + bound.replacen(' ', "T", 1) +} + +/// Period and hero of a read: the SQL conditions on the stored rows and their parameters. +struct Scope { + clauses: Vec, + binds: Vec<(String, SqlValue)>, +} + +impl Scope { + fn new(hero: &str, from: Option<&str>, to: Option<&str>) -> Self { + let mut clauses = vec![format!("c.hero_name IN {}", hero_resolution_sql("@hero")), "c.status != 'skipped'".to_string()]; + let mut binds = vec![("@hero".to_string(), SqlValue::Text(hero.to_string()))]; + if let Some(from) = from.filter(|f| !f.is_empty()) { + clauses.push("c.played_at >= @from".into()); + binds.push(("@from".into(), SqlValue::Text(stored_bound(from)))); + } + if let Some(to) = to.filter(|t| !t.is_empty()) { + let to = if to.len() == 10 { format!("{to}T23:59:59") } else { stored_bound(to) }; + clauses.push("c.played_at <= @to".into()); + binds.push(("@to".into(), SqlValue::Text(to))); + } + Self { clauses, binds } + } + + fn and(mut self, clause: &str, name: &str, value: SqlValue) -> Self { + self.clauses.push(clause.to_string()); + self.binds.push((name.to_string(), value)); + self + } + + fn and_clause(mut self, clause: &str) -> Self { + self.clauses.push(clause.to_string()); + self + } + + fn where_sql(&self) -> String { + self.clauses.join(" AND ") + } + + fn params(&self) -> Vec<(&str, &dyn ToSql)> { + self.binds.iter().map(|(n, v)| (n.as_str(), v as &dyn ToSql)).collect() + } +} + +/// The opponent filter of a read: "any" (fish), "reg", or none for both. +fn opponent_clause(opponent: Option<&str>) -> Option<&'static str> { + match opponent { + Some("any") => Some("c.vs_reg = 0"), + Some("reg") => Some("c.vs_reg = 1"), + _ => None, + } +} + +/// Counts of the stored rows by status. +#[derive(Default, Clone, Copy)] +struct Tally { + matches: i64, + deviations: i64, + no_range: i64, +} + +impl Tally { + fn add(&mut self, status: &str, n: i64) { + match status { + "match" => self.matches += n, + "deviation" => self.deviations += n, + _ => self.no_range += n, + } + } + + fn json(self) -> Value { + json!({ "compared": self.matches + self.deviations, "matches": self.matches, "deviations": self.deviations, "noRange": self.no_range }) + } +} + +/// Seat order of the report: 3-handed first, then heads-up. +fn position_rank(format: &str, position: &str) -> usize { + let seats = ["BTN", "SB", "BB"]; + let seat = seats.iter().position(|s| *s == position).unwrap_or(seats.len()); + (usize::from(format == "hu") * seats.len()) + seat +} + +/// The palette action that stands for what was played, if the player has one. +fn played_action_id(book: &RangeBook, played: &str, response: Option<&str>) -> Option { + let families: &[&str] = match played { + "fold" => &["fold"], + "check" => &["check"], + "call" => &["call", "limp"], + "limp" => &["limp", "call"], + "raise" => &["raise", "iso", "threebet"], + "allin" => &["allin"], + _ => return None, + }; + let mut actions: Vec<&ActionDef> = book.actions.values().collect(); + actions.sort_by_key(|a| a.id); + // Several actions can share an immediate play (LIMP/FOLD, LIMP/CALL...): the answer tells them apart. + families.iter().find_map(|family| { + let same_play = || actions.iter().filter(|a| a.immediate == *family); + let by_answer = response.and_then(|answer| same_play().find(|a| a.response == answer)); + by_answer.or_else(|| same_play().next()).map(|a| a.id) + }) +} + +fn action_json(book: &RangeBook, conn: &Connection, id: i64) -> Value { + let color: Option = conn.query_row("SELECT color FROM range_actions WHERE id = ?1", [id], |r| r.get(0)).optional().ok().flatten(); + match book.actions.get(&id) { + Some(action) => json!({ "id": id, "label": action.label, "color": color }), + None => Value::Null, + } +} + +/// Totals, "without a range" lines and the table by scenario. +pub fn adherence(conn: &Connection, hero: &str, from: Option<&str>, to: Option<&str>, opponent: Option<&str>) -> Result { + let book = load_book(conn)?; + let mut scope = Scope::new(hero, from, to); + if let Some(clause) = opponent_clause(opponent) { + scope = scope.and_clause(clause); + } + let period = Scope::new(hero, from, to); + + // Fish and regulars, whatever the opponent filter: they are the switch of the report. + let mut by_kind = [Tally::default(), Tally::default()]; + { + let mut stmt = conn.prepare(&format!("SELECT c.vs_reg, c.status, COUNT(*) FROM hand_range_checks c WHERE {} GROUP BY c.vs_reg, c.status", period.where_sql()))?; + for row in stmt.query_map(&period.params()[..], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))? { + let (vs_reg, status, n) = row?; + by_kind[usize::from(vs_reg != 0)].add(&status, n); + } + } + + let mut by_position: Vec<(String, String, Tally)> = Vec::new(); + { + let mut stmt = conn.prepare(&format!( + "SELECT COALESCE(c.format, ''), COALESCE(c.hero_position, ''), c.status, COUNT(*) FROM hand_range_checks c WHERE {} GROUP BY c.format, c.hero_position, c.status", + scope.where_sql() + ))?; + for row in stmt.query_map(&scope.params()[..], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, i64>(3)?)))? { + let (format, position, status, n) = row?; + if format.is_empty() || position.is_empty() { + continue; + } + match by_position.iter_mut().find(|(f, p, _)| *f == format && *p == position) { + Some((_, _, tally)) => tally.add(&status, n), + None => { + let mut tally = Tally::default(); + tally.add(&status, n); + by_position.push((format, position, tally)); + } + } + } + } + by_position.sort_by_key(|(format, position, _)| position_rank(format, position)); + + let (mut matches, mut deviations, mut response_deviations, mut no_range) = (0_i64, 0_i64, 0_i64, 0_i64); + { + let mut stmt = conn.prepare(&format!( + "SELECT c.status, c.deviation_kind, COUNT(*) FROM hand_range_checks c WHERE {} GROUP BY c.status, c.deviation_kind", + scope.where_sql() + ))?; + for row in stmt.query_map(&scope.params()[..], |r| Ok((r.get::<_, String>(0)?, r.get::<_, Option>(1)?, r.get::<_, i64>(2)?)))? { + let (status, kind, n) = row?; + match status.as_str() { + "match" => matches += n, + "deviation" => { + deviations += n; + if kind.as_deref() == Some("response") { + response_deviations += n; + } + } + _ => no_range += n, + } + } + } + + let frequent_lines: Vec = { + let mut stmt = conn.prepare(&format!( + "SELECT c.format, c.hero_position, c.line, COUNT(*) AS n FROM hand_range_checks c WHERE {} AND c.status = 'no_range' + GROUP BY c.format, c.hero_position, c.line ORDER BY n DESC LIMIT {FREQUENT_LINES}", + scope.where_sql() + ))?; + let rows = stmt + .query_map(&scope.params()[..], |r| Ok(json!({ "format": r.get::<_, String>(0)?, "heroPosition": r.get::<_, String>(1)?, "line": r.get::<_, String>(2)?, "count": r.get::<_, i64>(3)? })))? + .collect::, _>>()?; + rows + }; + + // The most frequent deviation of every scenario. + let mut top: HashMap = HashMap::new(); + { + let mut stmt = conn.prepare(&format!( + "SELECT c.scenario_id, c.expected_action_id, c.played_immediate, c.played_response, c.deviation_kind, COUNT(*) FROM hand_range_checks c + WHERE {} AND c.status = 'deviation' GROUP BY c.scenario_id, c.expected_action_id, c.played_immediate, c.played_response, c.deviation_kind", + scope.where_sql() + ))?; + for row in stmt.query_map(&scope.params()[..], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?, r.get::<_, String>(2)?, r.get::<_, Option>(3)?, r.get::<_, Option>(4)?, r.get::<_, i64>(5)?)) + })? { + let (scenario, expected, played, response, kind, n) = row?; + if top.get(&scenario).map_or(true, |(best, _)| n > *best) { + top.insert( + scenario, + (n, json!({ "expectedActionId": expected, "playedImmediate": played, "playedActionId": played_action_id(&book, &played, response.as_deref()), "playedResponse": response, "kind": kind, "count": n })), + ); + } + } + } + + let scenarios: Vec = { + let mut stmt = conn.prepare(&format!( + "SELECT c.scenario_id, sp.id, sp.name, sp.format, sp.hero_position, sp.line, sp.opponent, sc.stack_bb, COUNT(*), + SUM(c.status = 'match'), AVG(CASE WHEN c.status = 'match' THEN c.ev_bb END), AVG(CASE WHEN c.status = 'deviation' THEN c.ev_bb END) + FROM hand_range_checks c JOIN range_scenarios sc ON sc.id = c.scenario_id JOIN range_spots sp ON sp.id = sc.spot_id + WHERE {} AND c.status IN ('match', 'deviation') GROUP BY c.scenario_id ORDER BY COUNT(*) DESC", + scope.where_sql() + ))?; + let rows = stmt + .query_map(&scope.params()[..], |r| { + let scenario: i64 = r.get(0)?; + let (decisions, followed): (i64, i64) = (r.get(8)?, r.get(9)?); + Ok(json!({ + "scenarioId": scenario, "spotId": r.get::<_, i64>(1)?, "name": r.get::<_, String>(2)?, "format": r.get::<_, String>(3)?, + "heroPosition": r.get::<_, String>(4)?, "line": r.get::<_, String>(5)?, "opponent": r.get::<_, String>(6)?, "stackBb": r.get::<_, f64>(7)?, + "decisions": decisions, "matches": followed, "respect": if decisions > 0 { followed as f64 / decisions as f64 } else { 0.0 }, + "evMatch": r.get::<_, Option>(10)?, "evDeviation": r.get::<_, Option>(11)?, + })) + })? + .collect::, _>>()?; + rows + }; + let scenarios: Vec = scenarios + .into_iter() + .map(|mut s| { + let id = s["scenarioId"].as_i64().unwrap_or(-1); + s["topDeviation"] = top.remove(&id).map_or(Value::Null, |(_, v)| v); + s + }) + .collect(); + + let compared = matches + deviations; + Ok(json!({ + "compared": compared, "matches": matches, "deviations": deviations, "responseDeviations": response_deviations, "noRange": no_range, + "respect": if compared > 0 { Some(matches as f64 / compared as f64) } else { None }, + "noRangeShare": if compared + no_range > 0 { Some(no_range as f64 / (compared + no_range) as f64) } else { None }, + "frequentLines": frequent_lines, "scenarios": scenarios, + "byOpponent": { "any": by_kind[0].json(), "reg": by_kind[1].json() }, + "byPosition": by_position.into_iter().map(|(format, position, tally)| { + let mut entry = tally.json(); + entry["format"] = json!(format); + entry["heroPosition"] = json!(position); + entry + }).collect::>(), + })) +} + +/// The grid, the stacks the hands were played at and the latest deviations of one range. +pub fn scenario_detail(conn: &Connection, scenario_id: i64, hero: &str, from: Option<&str>, to: Option<&str>) -> Result> { + let head: Option<(i64, String, String, String, String, String, f64)> = conn + .query_row( + "SELECT sp.id, sp.name, sp.format, sp.hero_position, sp.line, sp.opponent, sc.stack_bb FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sc.id = ?1", + [scenario_id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?)), + ) + .optional()?; + let Some((spot_id, name, format, hero_position, line, opponent, stack_bb)) = head else { return Ok(None) }; + let book = load_book(conn)?; + let scope = Scope::new(hero, from, to).and("c.scenario_id = @scenario", "@scenario", SqlValue::Integer(scenario_id)); + + let mut hand_stats: HashMap = HashMap::new(); + let (mut min_stack, mut max_stack) = (f64::MAX, f64::MIN); + { + let mut stmt = conn.prepare(&format!("SELECT c.hand_class, c.status, COUNT(*), MIN(c.stack_bb), MAX(c.stack_bb) FROM hand_range_checks c WHERE {} GROUP BY c.hand_class, c.status", scope.where_sql()))?; + for row in stmt.query_map(&scope.params()[..], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?, r.get::<_, Option>(3)?, r.get::<_, Option>(4)?)) + })? { + let (hand, status, n, lo, hi) = row?; + let entry = hand_stats.entry(hand).or_default(); + if status == "deviation" { + entry.1 += n; + } else { + entry.0 += n; + } + min_stack = min_stack.min(lo.unwrap_or(f64::MAX)); + max_stack = max_stack.max(hi.unwrap_or(f64::MIN)); + } + } + // What was played instead of the plan, per hand: the most frequent first. + let mut played_by_hand: HashMap> = HashMap::new(); + { + let mut stmt = conn.prepare(&format!( + "SELECT c.hand_class, c.played_immediate, c.played_response, c.deviation_kind, COUNT(*) AS n FROM hand_range_checks c WHERE {} AND c.status = 'deviation' GROUP BY c.hand_class, c.played_immediate, c.played_response, c.deviation_kind ORDER BY n DESC", + scope.where_sql() + ))?; + for row in stmt.query_map(&scope.params()[..], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option>(2)?, r.get::<_, Option>(3)?, r.get::<_, i64>(4)?)))? { + let (hand, played, response, kind, count) = row?; + played_by_hand.entry(hand).or_default().push(json!({ + "playedImmediate": played, "playedActionId": played_action_id(&book, &played, response.as_deref()), "playedResponse": response, "kind": kind, "count": count, + })); + } + } + let stats: serde_json::Map = hand_stats + .into_iter() + .map(|(hand, (m, d))| { + let played = played_by_hand.remove(&hand).unwrap_or_default(); + (hand, json!({ "matches": m, "deviations": d, "played": played })) + }) + .collect(); + + let range: HashMap = book.hands.get(&scenario_id).cloned().unwrap_or_default(); + let deviation_scope = Scope::new(hero, from, to).and("c.scenario_id = @scenario", "@scenario", SqlValue::Integer(scenario_id)).and_clause("c.status = 'deviation'"); + let total: i64 = conn.query_row(&format!("SELECT COUNT(*) FROM hand_range_checks c WHERE {}", deviation_scope.where_sql()), &deviation_scope.params()[..], |r| r.get(0))?; + let deviations: Vec = { + let mut stmt = conn.prepare(&format!( + "SELECT c.hand_id, c.played_at, c.cards, c.hand_class, c.expected_action_id, c.played_immediate, c.played_response, c.deviation_kind + FROM hand_range_checks c WHERE {} ORDER BY c.played_at DESC LIMIT {RECENT_DEVIATIONS}", + deviation_scope.where_sql() + ))?; + let rows = stmt + .query_map(&deviation_scope.params()[..], |r| { + let played: String = r.get(5)?; + let response: Option = r.get(6)?; + Ok(json!({ + "handId": r.get::<_, String>(0)?, "playedAt": r.get::<_, Option>(1)?, "cards": r.get::<_, Option>(2)?, "handClass": r.get::<_, String>(3)?, + "expectedActionId": r.get::<_, Option>(4)?, "playedImmediate": played, "playedActionId": played_action_id(&book, &played, response.as_deref()), + "playedResponse": response, "kind": r.get::<_, Option>(7)?, + })) + })? + .collect::, _>>()?; + rows + }; + + Ok(Some(json!({ + "scenarioId": scenario_id, "spotId": spot_id, "name": name, "format": format, "heroPosition": hero_position, "line": line, "opponent": opponent, "stackBb": stack_bb, + "observedMinBb": (min_stack != f64::MAX).then_some(min_stack), "observedMaxBb": (max_stack != f64::MIN).then_some(max_stack), + "hands": range, "handStats": stats, "deviations": deviations, "deviationTotal": total, + }))) +} + +/// The comparison of one hand (the replayer's card); `None` when there is no decision to compare. +pub fn hand_check(conn: &Connection, hero: &str, hand_id: &str) -> Result> { + if hero.trim().is_empty() { + return Ok(None); + } + let book = load_book(conn)?; + if book.candidates.is_empty() { + return Ok(None); + } + let hands = hands_for_analysis(conn, &AnalysisFilters { hero_name: Some(hero.to_string()), hand_id: Some(hand_id.to_string()), ..Default::default() })?; + let Some(hand) = hands.first() else { return Ok(None) }; + let players = stacks_of(conn, &[hand.hand_id.as_str()])?; + let Some(stack_bb) = effective_stack_bb(hand, players.get(&hand.hand_id).map(Vec::as_slice).unwrap_or_default()) else { return Ok(None) }; + let regulars = regular_players(conn)?; + let check = check_of(hand, stack_bb, ®ulars, &book); + if check.status == Status::Skipped { + return Ok(None); + } + let spot: Option<(i64, String)> = match check.scenario_id { + Some(id) => conn.query_row("SELECT sp.id, sp.name FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sc.id = ?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).optional()?, + None => None, + }; + let played_id = played_action_id(&book, &check.played_immediate, check.played_response.as_deref()); + Ok(Some(json!({ + "status": check.status.as_str(), "scenarioId": check.scenario_id, "spotId": spot.as_ref().map(|s| s.0), "scenarioName": spot.map(|s| s.1), + "expectedAction": check.expected_action_id.map_or(Value::Null, |id| action_json(&book, conn, id)), + "playedAction": played_id.map_or(Value::Null, |id| action_json(&book, conn, id)), + "playedImmediate": check.played_immediate, "playedResponse": check.played_response, "deviationKind": check.deviation_kind, + "depthUsedBb": check.depth_used_bb, "stackBb": stack_bb, "handClass": check.hand_class, "format": check.format, "heroPosition": check.hero_position, "line": check.line, + }))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::migrations; + use crate::services::user_ranges::{save_hands, save_spot, SpotInput, StartPoint}; + use std::collections::BTreeMap; + + fn db() -> Connection { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn + } + + /// A 3-handed hand where the hero (BB) saw "BTN fold, SB limp" with `cards` and `hero_acts`. + fn insert_hand(conn: &Connection, id: &str, cards: &str, hero_acts: &str, sb_name: &str) { + let preflop = format!("Btn: Folds\n{sb_name}: Calls 10\n{hero_acts}"); + conn.execute( + "INSERT INTO hands (id, room, date_time, blinds, player_count, preflop_action) VALUES (?1, 'Winamax', '2026-11-10 20:00:00', '10/20', 3, ?2)", + params![id, preflop], + ) + .unwrap(); + for (name, position, hand_cards, stack) in [("Btn", "BTN", None, 200.0), (sb_name, "SB", None, 200.0), ("Hero", "BB", Some(cards), 200.0)] { + conn.execute( + "INSERT INTO player_hands (hand_id, player_name, position, cards, stack, net_profit) VALUES (?1, ?2, ?3, ?4, ?5, 0)", + params![id, name, position, hand_cards, stack], + ) + .unwrap(); + } + conn.execute("INSERT OR IGNORE INTO players (name) VALUES ('Hero')", []).unwrap(); + } + + fn range_with(conn: &mut Connection, opponent: &str, paint: &[(&str, &str)]) -> i64 { + let spot = SpotInput { + format: "3max".into(), + hero_position: "BB".into(), + line: "btn:fold,sb:call".into(), + opponent: opponent.into(), + depths: vec![10.0], + start: StartPoint { kind: "empty".into(), ..Default::default() }, + ..Default::default() + }; + save_spot(conn, &spot).unwrap(); + let scenario: i64 = conn.query_row("SELECT sc.id FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sp.opponent = ?1", [opponent], |r| r.get(0)).unwrap(); + let mut hands = BTreeMap::new(); + for (hand, label) in paint { + let id: i64 = conn.query_row("SELECT id FROM range_actions WHERE label = ?1", [label], |r| r.get(0)).unwrap(); + hands.insert(hand.to_string(), id); + } + save_hands(conn, scenario, &hands).unwrap(); + scenario + } + + #[test] + fn every_status_is_stored_and_summarised() { + let mut conn = db(); + // Range: AKo = Raise, everything else = Fold. The hero checks in the BB. + range_with(&mut conn, "any", &[("AKo", "Raise")]); + insert_hand(&conn, "h_match", "7h 2c", "Hero: Checks", "Sb"); + insert_hand(&conn, "h_dev", "Ah Kc", "Hero: Checks", "Sb"); + conn.execute("INSERT INTO hands (id, room, date_time, blinds, player_count, preflop_action) VALUES ('h_none', 'Winamax', '2026-11-10 21:00:00', '10/20', 3, 'Btn: Raises 40 to 60\nSb: Folds\nHero: Folds')", []).unwrap(); + for (name, position, cards) in [("Btn", "BTN", None), ("Sb", "SB", None), ("Hero", "BB", Some("9h 3c"))] { + conn.execute("INSERT INTO player_hands (hand_id, player_name, position, cards, stack, net_profit) VALUES ('h_none', ?1, ?2, ?3, 200, 0)", params![name, position, cards]).unwrap(); + } + // The planned play is Fold for 72o: checking is a deviation too, so paint it as Check. + let check: i64 = conn.query_row("SELECT id FROM range_actions WHERE label = 'Check'", [], |r| r.get(0)).unwrap(); + let scenario: i64 = conn.query_row("SELECT id FROM range_scenarios", [], |r| r.get(0)).unwrap(); + save_hands(&mut conn, scenario, &BTreeMap::from([("72o".to_string(), check)])).unwrap(); + + assert_eq!(ensure_computed(&mut conn, "Hero").unwrap(), 3); + assert_eq!(ensure_computed(&mut conn, "Hero").unwrap(), 0, "nothing is computed twice"); + let status = |id: &str| -> (String, Option) { conn.query_row("SELECT status, deviation_kind FROM hand_range_checks WHERE hand_id = ?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).unwrap() }; + assert_eq!(status("h_match").0, "match"); + assert_eq!(status("h_dev"), ("deviation".to_string(), Some("immediate".to_string()))); + assert_eq!(status("h_none").0, "no_range"); + + let summary = adherence(&conn, "Hero", None, None, None).unwrap(); + assert_eq!((summary["compared"].as_i64(), summary["matches"].as_i64(), summary["deviations"].as_i64(), summary["noRange"].as_i64()), (Some(2), Some(1), Some(1), Some(1))); + assert_eq!(summary["respect"], 0.5); + assert_eq!(summary["scenarios"][0]["topDeviation"]["playedImmediate"], "check"); + assert_eq!(summary["frequentLines"][0]["line"], "btn:raise,sb:fold"); + + let detail = scenario_detail(&conn, scenario, "Hero", None, None).unwrap().unwrap(); + assert_eq!(detail["deviationTotal"], 1); + assert_eq!(detail["handStats"]["AKo"]["deviations"], 1); + let played = &detail["handStats"]["AKo"]["played"][0]; + assert_eq!((played["playedImmediate"].as_str(), played["kind"].as_str(), played["count"].as_i64()), (Some("check"), Some("immediate"), Some(1))); + assert_eq!(detail["handStats"]["72o"]["played"], json!([]), "a followed hand lists nothing played instead"); + assert_eq!(detail["deviations"][0]["handId"], "h_dev"); + } + + #[test] + fn a_period_given_as_the_app_filters_write_it_selects_the_same_day() { + let mut conn = db(); + range_with(&mut conn, "any", &[("72o", "Check")]); + insert_hand(&conn, "h1", "7h 2c", "Hero: Checks", "Sb"); + ensure_computed(&mut conn, "Hero").unwrap(); + let compared = |from: Option<&str>, to: Option<&str>| adherence(&conn, "Hero", from, to, None).unwrap()["compared"].as_i64(); + // The hand was played on 2026-11-10 at 20:00. + assert_eq!(compared(Some("2026-11-10 00:00:00"), Some("2026-11-10 23:59:59")), Some(1)); + assert_eq!(compared(Some("2026-11-10 20:30:00"), None), Some(0)); + assert_eq!(compared(None, Some("2026-11-10 19:00:00")), Some(0)); + assert_eq!(compared(Some("2026-11-10"), Some("2026-11-10")), Some(1)); + } + + #[test] + fn a_range_change_triggers_a_recompute() { + let mut conn = db(); + let scenario = range_with(&mut conn, "any", &[("72o", "Check")]); + insert_hand(&conn, "h1", "7h 2c", "Hero: Checks", "Sb"); + ensure_computed(&mut conn, "Hero").unwrap(); + let status = |conn: &Connection| -> String { conn.query_row("SELECT status FROM hand_range_checks WHERE hand_id = 'h1'", [], |r| r.get(0)).unwrap() }; + assert_eq!(status(&conn), "match"); + + let fold: i64 = conn.query_row("SELECT id FROM range_actions WHERE label = 'Fold'", [], |r| r.get(0)).unwrap(); + save_hands(&mut conn, scenario, &BTreeMap::from([("72o".to_string(), fold)])).unwrap(); + assert_eq!(conn.query_row("SELECT COUNT(*) FROM hand_range_checks", [], |r| r.get::<_, i64>(0)).unwrap(), 0, "the stale rows are gone"); + assert_eq!(ensure_computed(&mut conn, "Hero").unwrap(), 1); + assert_eq!(status(&conn), "deviation"); + } + + #[test] + fn the_reg_variant_is_chosen_only_against_a_reg() { + let mut conn = db(); + range_with(&mut conn, "any", &[("72o", "Check")]); + let reg_scenario = range_with(&mut conn, "reg", &[("72o", "Fold")]); + insert_hand(&conn, "vs_fish", "7h 2c", "Hero: Checks", "Fish"); + insert_hand(&conn, "vs_reg", "7h 2c", "Hero: Checks", "Villain"); + conn.execute("INSERT INTO players (name, is_reg) VALUES ('Villain', 1)", []).unwrap(); + ensure_computed(&mut conn, "Hero").unwrap(); + let scenario_of = |id: &str| -> i64 { conn.query_row("SELECT scenario_id FROM hand_range_checks WHERE hand_id = ?1", [id], |r| r.get(0)).unwrap() }; + assert_eq!(scenario_of("vs_reg"), reg_scenario); + assert_ne!(scenario_of("vs_fish"), reg_scenario); + } + + #[test] + fn the_report_splits_fish_and_regulars_and_positions() { + let mut conn = db(); + range_with(&mut conn, "any", &[("72o", "Check")]); + insert_hand(&conn, "vs_fish", "7h 2c", "Hero: Checks", "Fish"); + insert_hand(&conn, "vs_fish_dev", "9h 3c", "Hero: Raises 40 to 60", "Fish"); + insert_hand(&conn, "vs_reg", "7h 2c", "Hero: Checks", "Villain"); + conn.execute("INSERT INTO players (name, is_reg) VALUES ('Villain', 1)", []).unwrap(); + ensure_computed(&mut conn, "Hero").unwrap(); + + let all = adherence(&conn, "Hero", None, None, None).unwrap(); + assert_eq!(all["byOpponent"]["any"]["compared"], 2); + assert_eq!(all["byOpponent"]["reg"]["compared"], 1, "a hand against a regular counts on its side only"); + assert_eq!(all["byOpponent"]["any"]["matches"], 1); + assert_eq!(all["byPosition"][0]["format"], "3max"); + assert_eq!(all["byPosition"][0]["heroPosition"], "BB"); + assert_eq!(all["byPosition"][0]["compared"], all["compared"]); + + // The switch keeps both sides visible while the rest follows the filter. + let fish = adherence(&conn, "Hero", None, None, Some("any")).unwrap(); + assert_eq!(fish["compared"], 2); + assert_eq!(fish["byOpponent"]["reg"]["compared"], 1); + let reg = adherence(&conn, "Hero", None, None, Some("reg")).unwrap(); + assert_eq!(reg["compared"], 1); + } + + #[test] + fn one_hand_is_checked_without_storing_anything() { + let mut conn = db(); + range_with(&mut conn, "any", &[("72o", "Check")]); + insert_hand(&conn, "h1", "7h 2c", "Hero: Checks", "Sb"); + let check = hand_check(&conn, "Hero", "h1").unwrap().unwrap(); + assert_eq!(check["status"], "match"); + assert_eq!(check["expectedAction"]["label"], "Check"); + assert_eq!(check["scenarioName"], "BB vs SB limp"); + assert_eq!(conn.query_row("SELECT COUNT(*) FROM hand_range_checks", [], |r| r.get::<_, i64>(0)).unwrap(), 0); + assert!(hand_check(&conn, "Hero", "missing").unwrap().is_none()); + let _ = ensure_computed(&mut conn, "Nobody"); + } +} diff --git a/crates/core/src/services/ranges_io.rs b/crates/core/src/services/ranges_io.rs new file mode 100644 index 00000000..41361038 --- /dev/null +++ b/crates/core/src/services/ranges_io.rs @@ -0,0 +1,496 @@ +//! Saving and sharing the player's ranges: a versioned JSON file that is validated strictly and +//! reports what it had to ignore. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use rusqlite::{params, Connection, OptionalExtension}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::engines::range_scenarios::{hand_classes, is_hand_class, HAND_CLASS_COUNT}; +use crate::services::user_ranges::{self as ranges, ActionInput, RangeError, Res}; + +pub const FORMAT: &str = "spintracker-ranges"; +pub const VERSION: i64 = 1; + +/// How an imported file meets the ranges already stored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImportMode { + /// Everything stored is dropped first. + Replace, + /// Actions of the same label are reused and spots of the same name are replaced. + Merge, +} + +impl ImportMode { + pub fn parse(value: &str) -> Option { + match value { + "replace" => Some(Self::Replace), + "merge" => Some(Self::Merge), + _ => None, + } + } +} + +fn ids_of(tx: &rusqlite::Transaction, sql: &str, id: i64) -> Res> { + let mut stmt = tx.prepare(sql)?; + let ids = stmt.query_map([id], |r| r.get(0))?.collect::, _>>()?; + Ok(ids) +} + +// --------------------------------------------------------------------------------------------- +// Export +// --------------------------------------------------------------------------------------------- + +type SpotRow = (i64, String, String, String, String, Option, String, bool); + +/// The range data as the JSON file format. With `only`, just those scenarios (depths) are written, +/// with the spots, actions and programs they need. +pub fn export(conn: &Connection, only: Option<&HashSet>) -> Res { + let mut labels: HashMap = HashMap::new(); + let mut actions = Vec::new(); + { + let mut stmt = conn.prepare("SELECT id, label, color, immediate, size_value, size_unit, response FROM range_actions ORDER BY sort_order, id")?; + for row in stmt.query_map([], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?, r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, String>(6)?)) + })? { + let (id, label, color, immediate, size_value, size_unit, response) = row?; + actions.push(json!({ "label": label, "color": color, "immediate": immediate, "sizeValue": size_value, "sizeUnit": size_unit, "response": response })); + labels.insert(id, label); + } + } + + let mut spot_names: HashMap = HashMap::new(); + let mut used_labels: HashSet = HashSet::new(); + let mut spots = Vec::new(); + let spot_rows: Vec = { + let mut stmt = conn.prepare("SELECT id, name, format, hero_position, line, line_sizes, opponent, study_only FROM range_spots ORDER BY id")?; + let rows = stmt + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get::<_, i64>(7)? != 0)))? + .collect::, _>>()?; + rows + }; + for (id, name, format, hero, line, sizes, opponent, study) in spot_rows { + let depth_rows: Vec<(i64, f64)> = { + let mut stmt = conn.prepare("SELECT id, stack_bb FROM range_scenarios WHERE spot_id = ?1 ORDER BY stack_bb DESC")?; + let rows = stmt.query_map([id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::, _>>()?; + rows + }; + let mut scenarios = Vec::new(); + for (scenario_id, stack) in depth_rows.into_iter().filter(|(id, _)| only.map_or(true, |chosen| chosen.contains(id))) { + let mut hands = BTreeMap::new(); + let mut hand_stmt = conn.prepare("SELECT hand, action_id FROM range_hands WHERE scenario_id = ?1")?; + for row in hand_stmt.query_map([scenario_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + let (hand, action) = row?; + let label = labels.get(&action).cloned().unwrap_or_default(); + used_labels.insert(label.clone()); + hands.insert(hand, label); + } + scenarios.push(json!({ "stackBb": stack, "hands": hands })); + } + if only.is_some() && scenarios.is_empty() { + continue; + } + spots.push(json!({ + "name": name, "format": format, "heroPosition": hero, "line": line, + "lineSizes": sizes.and_then(|s| serde_json::from_str::(&s).ok()), "opponent": opponent, "studyOnly": study, "scenarios": scenarios, + })); + spot_names.insert(id, name); + } + + let programs: Vec = ranges::programs(conn)? + .as_array() + .map(|items| { + items + .iter() + .filter_map(|p| { + let names: Vec = p["spotIds"].as_array().into_iter().flatten().filter_map(Value::as_i64).filter_map(|id| spot_names.get(&id)).map(|n| json!(n)).collect(); + (only.is_none() || !names.is_empty()).then(|| json!({ "name": p["name"], "spots": names })) + }) + .collect() + }) + .unwrap_or_default(); + + if only.is_some() { + actions.retain(|a| a["label"].as_str().is_some_and(|label| used_labels.contains(label))); + } + Ok(json!({ "format": FORMAT, "version": VERSION, "actions": actions, "spots": spots, "programs": programs })) +} + +// --------------------------------------------------------------------------------------------- +// Import +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct FileSpot { + name: String, + format: String, + hero_position: String, + line: String, + #[serde(default)] + line_sizes: Option, + #[serde(default)] + opponent: Option, + #[serde(default)] + study_only: bool, + #[serde(default)] + scenarios: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct FileScenario { + stack_bb: f64, + #[serde(default)] + hands: BTreeMap, +} + +#[derive(Debug, Deserialize)] +struct FileProgram { + name: String, + #[serde(default)] + spots: Vec, +} + +fn items Deserialize<'de>>(file: &Value, key: &str, warnings: &mut Vec) -> Vec { + let Some(list) = file.get(key).and_then(Value::as_array) else { return Vec::new() }; + list.iter() + .enumerate() + .filter_map(|(i, item)| match serde_json::from_value::(item.clone()) { + Ok(v) => Some(v), + Err(e) => { + warnings.push(format!("{key} #{}: unreadable ({e})", i + 1)); + None + } + }) + .collect() +} + +/// Imports a file. Problems with the file as a whole (not JSON, wrong format or version, no usable +/// action) reject it and change nothing; problems with one item are listed in the report and the +/// item is skipped or repaired. A dry run builds the same report and leaves the data untouched. +pub fn import(conn: &mut Connection, content: &str, mode: ImportMode, dry_run: bool) -> Res { + let file: Value = serde_json::from_str(content).map_err(|e| RangeError::Invalid(format!("not a valid JSON file: {e}")))?; + if file.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(RangeError::Invalid("not a SpinTracker ranges file".into())); + } + if file.get("version").and_then(Value::as_i64) != Some(VERSION) { + return Err(RangeError::Invalid(format!("unsupported file version (expected {VERSION})"))); + } + + let mut warnings = Vec::new(); + let file_actions: Vec = items(&file, "actions", &mut warnings); + let mut valid_actions = Vec::new(); + for action in file_actions { + match ranges::validate_action(&action) { + Ok(()) => valid_actions.push(action), + Err(RangeError::Invalid(message)) => warnings.push(format!("action {}: {message}", action.label)), + Err(e) => return Err(e), + } + } + let file_spots: Vec = items(&file, "spots", &mut warnings); + let file_programs: Vec = items(&file, "programs", &mut warnings); + + if mode == ImportMode::Replace && valid_actions.is_empty() { + return Err(RangeError::Invalid("the file holds no usable action".into())); + } + let tx = conn.transaction()?; + if mode == ImportMode::Replace { + let all: Vec = { + let mut stmt = tx.prepare("SELECT id FROM range_scenarios")?; + let ids = stmt.query_map([], |r| r.get(0))?.collect::, _>>()?; + ids + }; + ranges::purge_scenarios(&tx, &all)?; + for table in ["range_program_spots", "range_programs", "range_spots", "range_actions"] { + tx.execute(&format!("DELETE FROM {table}"), [])?; + } + } + + // Actions: a label already stored is reused as it is. + let mut action_ids: HashMap = HashMap::new(); + let mut created_actions = 0; + for action in &valid_actions { + let label = action.label.trim().to_string(); + if action_ids.contains_key(&label) { + warnings.push(format!("action {label}: duplicated in the file")); + continue; + } + let existing: Option = tx.query_row("SELECT id FROM range_actions WHERE label = ?1", [&label], |r| r.get(0)).optional()?; + let id = match existing { + Some(id) => id, + None => { + let order: i64 = tx.query_row("SELECT COALESCE(MAX(sort_order), -1) + 1 FROM range_actions", [], |r| r.get(0))?; + tx.execute( + "INSERT INTO range_actions (label, color, immediate, size_value, size_unit, response, sort_order) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![label, action.color, action.immediate, action.size_value, action.size_unit, action.response, order], + )?; + created_actions += 1; + tx.last_insert_rowid() + } + }; + action_ids.insert(label, id); + } + let fallback = ranges::first_action(&tx)?; + let fallback_label: String = tx.query_row("SELECT label FROM range_actions WHERE id = ?1", [fallback], |r| r.get(0))?; + // Labels of the stored palette resolve too, so a merge can point at actions the file does not define. + { + let mut stmt = tx.prepare("SELECT label, id FROM range_actions")?; + for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + let (label, id) = row?; + action_ids.entry(label).or_insert(id); + } + } + + let (mut spot_count, mut scenario_count) = (0, 0); + let mut spot_ids: HashMap = HashMap::new(); + for spot in file_spots { + let name = spot.name.trim().to_string(); + let hero = spot.hero_position.to_uppercase(); + let line = match ranges::normalize_line(&spot.format, &hero, &spot.line) { + Ok(line) if matches!(spot.format.as_str(), "3max" | "hu") => line, + _ => { + warnings.push(format!("scenario {name}: unreadable situation, ignored")); + continue; + } + }; + let opponent = spot.opponent.as_deref().filter(|o| !o.is_empty()).unwrap_or("any").to_string(); + if !matches!(opponent.as_str(), "any" | "reg") || name.is_empty() || spot.scenarios.is_empty() { + warnings.push(format!("scenario {name}: invalid, ignored")); + continue; + } + if mode == ImportMode::Merge { + let same_name: Option = tx.query_row("SELECT id FROM range_spots WHERE name = ?1", [&name], |r| r.get(0)).optional()?; + if let Some(id) = same_name { + let scenarios = ids_of(&tx, "SELECT id FROM range_scenarios WHERE spot_id = ?1", id)?; + ranges::purge_scenarios(&tx, &scenarios)?; + tx.execute("DELETE FROM range_program_spots WHERE spot_id = ?1", [id])?; + tx.execute("DELETE FROM range_spots WHERE id = ?1", [id])?; + } + } + let clash: Option = tx + .query_row( + "SELECT name FROM range_spots WHERE format = ?1 AND hero_position = ?2 AND line = ?3 AND opponent = ?4", + params![spot.format, hero, line, opponent], + |r| r.get(0), + ) + .optional()?; + if let Some(other) = clash { + warnings.push(format!("scenario {name}: same situation as {other}, ignored")); + continue; + } + let sizes = spot.line_sizes.as_ref().filter(|v| !v.is_null()).map(Value::to_string); + let stamp = ranges::now(); + tx.execute( + "INSERT INTO range_spots (name, format, hero_position, line, line_sizes, opponent, study_only, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8)", + params![name, spot.format, hero, line, sizes, opponent, spot.study_only, stamp], + )?; + let spot_id = tx.last_insert_rowid(); + + let mut seen_depths = HashSet::new(); + for scenario in spot.scenarios { + if ranges::validate_depth(scenario.stack_bb).is_err() || !seen_depths.insert(scenario.stack_bb.to_bits()) { + warnings.push(format!("scenario {name}: depth {} ignored", scenario.stack_bb)); + continue; + } + tx.execute("INSERT INTO range_scenarios (spot_id, stack_bb, updated_at) VALUES (?1, ?2, ?3)", params![spot_id, scenario.stack_bb, stamp])?; + let scenario_id = tx.last_insert_rowid(); + let mut chosen: HashMap = HashMap::new(); + for (hand, label) in &scenario.hands { + if !is_hand_class(hand) { + warnings.push(format!("{name} {}: unknown hand {hand}, ignored", scenario.stack_bb)); + continue; + } + match action_ids.get(label.trim()) { + Some(id) => { + chosen.insert(hand.clone(), *id); + } + None => warnings.push(format!("{name} {}: unknown action {label} for {hand} -> replaced by {fallback_label}", scenario.stack_bb)), + } + } + let known_hands = scenario.hands.keys().filter(|h| is_hand_class(h)).count(); + if known_hands < HAND_CLASS_COUNT { + warnings.push(format!("incomplete range: {name} {} ({known_hands}/{HAND_CLASS_COUNT})", scenario.stack_bb)); + } + for hand in hand_classes() { + let action = chosen.get(&hand).copied().unwrap_or(fallback); + tx.execute("INSERT INTO range_hands (scenario_id, hand, action_id, weight) VALUES (?1, ?2, ?3, 1.0)", params![scenario_id, hand, action])?; + } + scenario_count += 1; + } + if seen_depths.is_empty() { + tx.execute("DELETE FROM range_spots WHERE id = ?1", [spot_id])?; + warnings.push(format!("scenario {name}: no usable depth, ignored")); + } else { + spot_ids.insert(name.clone(), spot_id); + spot_count += 1; + } + } + + let mut program_count = 0; + for program in file_programs { + let name = program.name.trim().to_string(); + if name.is_empty() { + warnings.push("program without a name, ignored".into()); + continue; + } + let existing: Option = tx.query_row("SELECT id FROM range_programs WHERE name = ?1", [&name], |r| r.get(0)).optional()?; + let id = match existing { + Some(id) => { + tx.execute("DELETE FROM range_program_spots WHERE program_id = ?1", [id])?; + id + } + None => { + let order: i64 = tx.query_row("SELECT COALESCE(MAX(sort_order), -1) + 1 FROM range_programs", [], |r| r.get(0))?; + tx.execute("INSERT INTO range_programs (name, sort_order) VALUES (?1, ?2)", params![name, order])?; + tx.last_insert_rowid() + } + }; + let mut linked = HashSet::new(); + for spot_name in &program.spots { + let spot_id = match spot_ids.get(spot_name) { + Some(id) => Some(*id), + None => tx.query_row("SELECT id FROM range_spots WHERE name = ?1", [spot_name], |r| r.get(0)).optional()?, + }; + match spot_id { + Some(spot_id) if linked.insert(spot_id) => { + let order = linked.len() as i64 - 1; + tx.execute("INSERT INTO range_program_spots (program_id, spot_id, sort_order) VALUES (?1, ?2, ?3)", params![id, spot_id, order])?; + } + Some(_) => {} + None => warnings.push(format!("program {name}: unknown scenario {spot_name}, ignored")), + } + } + program_count += 1; + } + if dry_run { + tx.rollback()?; + } else { + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + } + Ok(json!({ "actions": created_actions, "spots": spot_count, "scenarios": scenario_count, "programs": program_count, "warnings": warnings })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::migrations; + + const FIXTURE: &str = include_str!("../../tests/fixtures/ranges_v1.json"); + + fn db() -> Connection { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn + } + + fn count(conn: &Connection, table: &str) -> i64 { + conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0)).unwrap() + } + + #[test] + fn export_import_export_is_identical() { + let mut conn = db(); + let report = import(&mut conn, FIXTURE, ImportMode::Replace, false).unwrap(); + assert_eq!(report["warnings"], json!([]), "the fixture is a complete, valid file"); + assert_eq!((report["spots"].as_i64(), report["scenarios"].as_i64(), report["programs"].as_i64()), (Some(3), Some(4), Some(1))); + let first = export(&conn, None).unwrap(); + + let mut other = db(); + import(&mut other, &first.to_string(), ImportMode::Replace, false).unwrap(); + assert_eq!(export(&other, None).unwrap(), first); + assert_eq!(first["actions"].as_array().unwrap().len(), 4); + assert_eq!(count(&conn, "range_hands"), 4 * 169); + } + + #[test] + fn exporting_chosen_depths_keeps_only_what_they_need() { + let mut conn = db(); + import(&mut conn, FIXTURE, ImportMode::Replace, false).unwrap(); + let first: i64 = conn.query_row("SELECT id FROM range_scenarios ORDER BY id LIMIT 1", [], |r| r.get(0)).unwrap(); + let chosen = HashSet::from([first]); + let file = export(&conn, Some(&chosen)).unwrap(); + + let spots = file["spots"].as_array().unwrap(); + assert_eq!(spots.len(), 1, "only the spot of the chosen depth"); + assert_eq!(spots[0]["scenarios"].as_array().unwrap().len(), 1); + let kept = file["actions"].as_array().unwrap().len(); + assert!(kept >= 1 && kept < 4, "only the actions the chosen hands use, got {kept}"); + for program in file["programs"].as_array().unwrap() { + assert_eq!(program["spots"].as_array().unwrap().len(), 1, "a program lists only exported spots"); + } + + let mut other = db(); + let report = import(&mut other, &file.to_string(), ImportMode::Replace, false).unwrap(); + assert_eq!(report["warnings"], json!([])); + assert_eq!(export(&other, None).unwrap(), file); + } + + #[test] + fn exporting_no_depth_at_all_gives_an_empty_file() { + let mut conn = db(); + import(&mut conn, FIXTURE, ImportMode::Replace, false).unwrap(); + let file = export(&conn, Some(&HashSet::new())).unwrap(); + assert_eq!((file["spots"].as_array().unwrap().len(), file["programs"].as_array().unwrap().len()), (0, 0)); + } + + #[test] + fn a_dry_run_reports_without_changing_anything() { + let mut conn = db(); + let report = import(&mut conn, FIXTURE, ImportMode::Replace, true).unwrap(); + assert_eq!(report["spots"], 3); + assert_eq!(count(&conn, "range_spots"), 0); + assert_eq!(count(&conn, "range_actions"), 6, "the base palette is untouched"); + } + + #[test] + fn merging_reuses_actions_with_the_same_label() { + let mut conn = db(); + import(&mut conn, FIXTURE, ImportMode::Replace, false).unwrap(); + let before = count(&conn, "range_actions"); + let report = import(&mut conn, FIXTURE, ImportMode::Merge, false).unwrap(); + assert_eq!(count(&conn, "range_actions"), before); + assert_eq!(report["actions"], 0); + assert_eq!(count(&conn, "range_spots"), 3, "spots of the same name are replaced, not added"); + assert_eq!(count(&conn, "range_programs"), 1); + assert_eq!(count(&conn, "range_program_spots"), 2); + } + + #[test] + fn unknown_hands_and_actions_are_reported_and_nothing_breaks() { + let mut file: Value = serde_json::from_str(FIXTURE).unwrap(); + file["spots"][0]["scenarios"][0]["hands"]["ZZs"] = json!("Fold"); + file["spots"][0]["scenarios"][0]["hands"]["AKs"] = json!("Missing action"); + file["spots"][0]["scenarios"][0]["hands"].as_object_mut().unwrap().remove("72o"); + let mut conn = db(); + let report = import(&mut conn, &file.to_string(), ImportMode::Replace, false).unwrap(); + let warnings: Vec = report["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect(); + assert!(warnings.iter().any(|w| w.contains("unknown hand ZZs")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("unknown action Missing action")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("incomplete range")), "{warnings:?}"); + assert_eq!(count(&conn, "range_hands"), 4 * 169, "every range stays complete"); + } + + #[test] + fn a_file_that_is_not_ours_changes_nothing() { + let mut conn = db(); + import(&mut conn, FIXTURE, ImportMode::Replace, false).unwrap(); + for bad in ["not json", r#"{"format":"other","version":1}"#, r#"{"format":"spintracker-ranges","version":2}"#, r#"{"format":"spintracker-ranges","version":1}"#] { + assert!(matches!(import(&mut conn, bad, ImportMode::Replace, false), Err(RangeError::Invalid(_))), "{bad}"); + } + assert_eq!(count(&conn, "range_spots"), 3); + } + + #[test] + fn a_spot_with_a_broken_situation_is_skipped() { + let mut file: Value = serde_json::from_str(FIXTURE).unwrap(); + file["spots"][1]["line"] = json!("BTN:dance"); + let mut conn = db(); + let report = import(&mut conn, &file.to_string(), ImportMode::Replace, false).unwrap(); + assert_eq!(report["spots"], 2); + assert!(report["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("unreadable situation"))); + assert_eq!(count(&conn, "range_program_spots"), 1, "the program keeps only the spots that exist"); + } +} diff --git a/crates/core/src/services/review.rs b/crates/core/src/services/review.rs new file mode 100644 index 00000000..bbd7ec01 --- /dev/null +++ b/crates/core/src/services/review.rs @@ -0,0 +1,388 @@ +//! Spaced review of the player's own ranges: one card per hand of a scenario, five boxes. +//! +//! A right answer moves a card up one box, a wrong one sends it back to box 1 for tomorrow. Every +//! function takes today's date, so nothing here reads the clock. + +use std::collections::{HashMap, HashSet}; + +use chrono::{Duration, NaiveDate}; +use rusqlite::{params, Connection, OptionalExtension}; +use serde_json::{json, Value}; + +use crate::engines::quiz::borderline_neighbor; +use crate::engines::range_scenarios::hand_classes; +use crate::repos::hands_query::hero_resolution_sql; +use crate::services::user_ranges::{self, Res}; + +/// Days before a card comes back, by box (box 1 is "every day"). +pub const INTERVAL_DAYS: [i64; 5] = [0, 1, 3, 7, 21]; +const BOX_COUNT: i64 = 5; +/// Boxes whose cards count as mastered. +const MASTERED_FROM_BOX: i64 = 4; +/// What a card costs to answer, for the time estimate. +const SECONDS_PER_CARD: i64 = 12; +const DEFAULT_NEW_CARDS_PER_DAY: i64 = 20; +const HARDEST_HANDS: i64 = 5; +const DATE_FORMAT: &str = "%Y-%m-%d"; + +pub fn parse_day(text: &str) -> Option { + NaiveDate::parse_from_str(text, DATE_FORMAT).ok() +} + +fn day(date: NaiveDate) -> String { + date.format(DATE_FORMAT).to_string() +} + +/// The box and due date of a card after an answer. A card not yet in a box counts as box 1. +pub fn next_state(current_box: Option, correct: bool, today: NaiveDate) -> (i64, NaiveDate) { + if !correct { + return (1, today + Duration::days(1)); + } + let next = (current_box.unwrap_or(1) + 1).min(BOX_COUNT); + (next, today + Duration::days(INTERVAL_DAYS[(next - 1) as usize])) +} + +/// Stores an answer on its card, creating the card on the first one. Returns the new box and the +/// day the card is due. +pub fn record(conn: &Connection, scenario_id: i64, hand_class: &str, correct: bool, today: NaiveDate, answered_at: &str) -> Res<(i64, NaiveDate)> { + let current: Option = conn + .query_row("SELECT box FROM training_cards WHERE scenario_id = ?1 AND hand_class = ?2", params![scenario_id, hand_class], |r| r.get(0)) + .optional()?; + let (new_box, due) = next_state(current, correct, today); + conn.execute( + "INSERT INTO training_cards (scenario_id, hand_class, box, due_on, last_answer_at, created_on) VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT(scenario_id, hand_class) DO UPDATE SET box = excluded.box, due_on = excluded.due_on, last_answer_at = excluded.last_answer_at", + params![scenario_id, hand_class, new_box, day(due), answered_at, day(today)], + )?; + Ok((new_box, due)) +} + +/// A hand of a range that has no card yet, with what decides its place in the queue. +#[derive(Debug, Clone, PartialEq)] +pub struct NewCandidate { + pub scenario_id: i64, + pub hand: String, + /// Next to a hand with another action. + pub borderline: bool, + /// How often the hero was dealt it in this scenario. + pub frequency: i64, + pub grid_index: usize, +} + +/// New cards come in this order: borderline hands, then the hands met most often in real games, +/// then grid order. +pub fn order_new_cards(mut candidates: Vec) -> Vec { + candidates.sort_by(|a, b| { + b.borderline + .cmp(&a.borderline) + .then(b.frequency.cmp(&a.frequency)) + .then(a.grid_index.cmp(&b.grid_index)) + .then(a.scenario_id.cmp(&b.scenario_id)) + }); + candidates +} + +fn new_cards_per_day(conn: &Connection) -> Res { + Ok(user_ranges::setting(conn, "new_cards_per_day")?.and_then(|v| v.parse().ok()).unwrap_or(DEFAULT_NEW_CARDS_PER_DAY)) +} + +/// How many new cards can still be introduced today. +fn new_remaining(conn: &Connection, today: NaiveDate) -> Res { + let introduced: i64 = conn.query_row("SELECT COUNT(*) FROM training_cards WHERE created_on = ?1", [day(today)], |r| r.get(0))?; + Ok((new_cards_per_day(conn)? - introduced).max(0)) +} + +/// Hands of the quiz scenarios (study-only ones excluded) that have no card yet, in queue order. +pub fn new_candidates(conn: &Connection) -> Res> { + let mut frequency: HashMap<(i64, String), i64> = HashMap::new(); + { + let mut stmt = conn.prepare("SELECT scenario_id, hand_class, COUNT(*) FROM hand_range_checks WHERE scenario_id IS NOT NULL AND status IN ('match', 'deviation') GROUP BY scenario_id, hand_class")?; + for row in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))? { + let (scenario, hand, n) = row?; + frequency.insert((scenario, hand), n); + } + } + let carded: HashSet<(i64, String)> = { + let mut stmt = conn.prepare("SELECT scenario_id, hand_class FROM training_cards")?; + let rows = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?.collect::, _>>()?; + rows + }; + let scenarios: Vec = { + let mut stmt = conn.prepare("SELECT sc.id FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sp.study_only = 0 ORDER BY sc.id")?; + let ids = stmt.query_map([], |r| r.get(0))?.collect::, _>>()?; + ids + }; + let classes = hand_classes(); + let mut out = Vec::new(); + for scenario in scenarios { + let mut stmt = conn.prepare("SELECT hand, action_id FROM range_hands WHERE scenario_id = ?1")?; + let hands = stmt.query_map([scenario], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?.collect::, _>>()?; + for (index, hand) in classes.iter().enumerate() { + if !hands.contains_key(hand) || carded.contains(&(scenario, hand.clone())) { + continue; + } + out.push(NewCandidate { + scenario_id: scenario, + borderline: borderline_neighbor(&hands, hand).is_some(), + frequency: frequency.get(&(scenario, hand.clone())).copied().unwrap_or(0), + grid_index: index, + hand: hand.clone(), + }); + } + } + Ok(order_new_cards(out)) +} + +fn due_cards(conn: &Connection, today: NaiveDate) -> Res> { + let mut stmt = conn.prepare( + "SELECT c.scenario_id, c.hand_class FROM training_cards c + JOIN range_scenarios sc ON sc.id = c.scenario_id JOIN range_spots sp ON sp.id = sc.spot_id + WHERE c.due_on <= ?1 AND sp.study_only = 0 ORDER BY c.due_on, c.box, c.scenario_id, c.hand_class", + )?; + let rows = stmt.query_map([day(today)], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::, _>>()?; + Ok(rows) +} + +/// The next card of the review: due cards first, then new ones while today's quota lasts. +pub fn next_card(conn: &Connection, today: NaiveDate) -> Res> { + if let Some(card) = due_cards(conn, today)?.into_iter().next() { + return Ok(Some(card)); + } + if new_remaining(conn, today)? == 0 { + return Ok(None); + } + Ok(new_candidates(conn)?.into_iter().next().map(|c| (c.scenario_id, c.hand))) +} + +/// The hands missed most often, as (scenario, hand) pairs. +pub fn hardest_hands(conn: &Connection, limit: i64) -> Res> { + let mut stmt = conn.prepare( + "SELECT a.scenario_id, a.hand_class, SUM(a.correct = 0) AS missed, COUNT(*) AS attempts FROM training_attempts a + JOIN range_scenarios sc ON sc.id = a.scenario_id JOIN range_spots sp ON sp.id = sc.spot_id + WHERE sp.study_only = 0 GROUP BY a.scenario_id, a.hand_class HAVING missed > 0 ORDER BY missed DESC, attempts DESC, a.hand_class LIMIT ?1", + )?; + let rows = stmt.query_map([limit], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))?.collect::, _>>()?; + Ok(rows) +} + +/// The review screen: today's plan, the boxes, progress by program and by scenario, the hands +/// missed most. `hero` adds the count of real deviations that have no card yet. +pub fn overview(conn: &Connection, today: NaiveDate, hero: Option<&str>) -> Res { + let due = due_cards(conn, today)?.len() as i64; + let remaining = new_remaining(conn, today)?; + let available = (new_candidates(conn)?.len() as i64).min(remaining); + let minutes = ((due + available) * SECONDS_PER_CARD + 59) / 60; + + let mut boxes = vec![0_i64; BOX_COUNT as usize]; + let (mut mastered, mut total) = (0_i64, 0_i64); + { + let mut stmt = conn.prepare( + "SELECT c.box, COUNT(*) FROM training_cards c JOIN range_scenarios sc ON sc.id = c.scenario_id JOIN range_spots sp ON sp.id = sc.spot_id + WHERE sp.study_only = 0 GROUP BY c.box", + )?; + for row in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)))? { + let (box_number, n) = row?; + boxes[(box_number - 1) as usize] = n; + total += n; + if box_number >= MASTERED_FROM_BOX { + mastered += n; + } + } + } + + let since = day(today - Duration::days(7)); + let (answers, right): (i64, i64) = + conn.query_row("SELECT COUNT(*), COALESCE(SUM(correct), 0) FROM training_attempts WHERE created_at >= ?1", [&since], |r| Ok((r.get(0)?, r.get(1)?)))?; + + let by_scenario: Vec = { + let mut stmt = conn.prepare( + "SELECT sc.id, sp.id, sp.name, sc.stack_bb, COUNT(c.hand_class), COALESCE(SUM(c.box >= ?2), 0), COALESCE(SUM(c.due_on <= ?1), 0), MAX(c.last_answer_at) + FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id LEFT JOIN training_cards c ON c.scenario_id = sc.id + WHERE sp.study_only = 0 GROUP BY sc.id ORDER BY sp.id, sc.stack_bb DESC", + )?; + let rows = stmt + .query_map(params![day(today), MASTERED_FROM_BOX], |r| { + Ok(json!({ + "scenarioId": r.get::<_, i64>(0)?, "spotId": r.get::<_, i64>(1)?, "name": r.get::<_, String>(2)?, "stackBb": r.get::<_, f64>(3)?, + "cards": r.get::<_, i64>(4)?, "mastered": r.get::<_, i64>(5)?, "dueToday": r.get::<_, i64>(6)?, "lastSession": r.get::<_, Option>(7)?, + })) + })? + .collect::, _>>()?; + rows + }; + + let programs: Vec = { + let list = user_ranges::programs(conn)?; + let mut out = Vec::new(); + for program in list.as_array().into_iter().flatten() { + let spot_ids: Vec = program["spotIds"].as_array().into_iter().flatten().filter_map(Value::as_i64).collect(); + let rows: Vec<&Value> = by_scenario.iter().filter(|s| spot_ids.contains(&s["spotId"].as_i64().unwrap_or(-1))).collect(); + let sum = |key: &str| rows.iter().map(|s| s[key].as_i64().unwrap_or(0)).sum::(); + out.push(json!({ "id": program["id"], "name": program["name"], "scenarios": spot_ids.len(), "cards": sum("cards"), "mastered": sum("mastered") })); + } + out + }; + + let hardest: Vec = { + let mut out = Vec::new(); + for (scenario, hand, missed, attempts) in hardest_hands(conn, HARDEST_HANDS)? { + let (name, stack): (String, f64) = conn.query_row("SELECT sp.name, sc.stack_bb FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sc.id = ?1", [scenario], |r| Ok((r.get(0)?, r.get(1)?)))?; + out.push(json!({ "scenarioId": scenario, "handClass": hand, "name": name, "stackBb": stack, "missed": missed, "attempts": attempts })); + } + out + }; + + let new_deviations: i64 = match hero.filter(|h| !h.is_empty()) { + Some(hero) => conn.query_row( + &format!( + "SELECT COUNT(*) FROM hand_range_checks c WHERE c.status = 'deviation' AND c.hero_name IN {} + AND NOT EXISTS (SELECT 1 FROM training_cards t WHERE t.scenario_id = c.scenario_id AND t.hand_class = c.hand_class)", + hero_resolution_sql("@hero") + ), + rusqlite::named_params! { "@hero": hero }, + |r| r.get(0), + )?, + None => 0, + }; + + Ok(json!({ + "today": { "due": due, "newAvailable": available, "minutes": minutes }, + "boxes": boxes, + "success7": { "rate": (answers > 0).then(|| right as f64 / answers as f64), "answers": answers }, + "mastered": { "count": mastered, "total": total }, + "programs": programs, "scenarios": by_scenario, "hardest": hardest, "newDeviations": new_deviations, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::migrations; + use crate::services::user_ranges::{save_spot, SpotInput, StartPoint}; + + fn date(text: &str) -> NaiveDate { + parse_day(text).unwrap() + } + + fn db() -> Connection { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn + } + + fn scenario(conn: &mut Connection, hero: &str, line: &str, study_only: bool) -> i64 { + let spot = SpotInput { + format: "3max".into(), + hero_position: hero.into(), + line: line.into(), + opponent: "any".into(), + study_only, + depths: vec![10.0], + start: StartPoint { kind: "empty".into(), ..Default::default() }, + ..Default::default() + }; + let id = save_spot(conn, &spot).unwrap(); + conn.query_row("SELECT id FROM range_scenarios WHERE spot_id = ?1", [id], |r| r.get(0)).unwrap() + } + + fn state(conn: &Connection, scenario: i64, hand: &str) -> (i64, String) { + conn.query_row("SELECT box, due_on FROM training_cards WHERE scenario_id = ?1 AND hand_class = ?2", params![scenario, hand], |r| Ok((r.get(0)?, r.get(1)?))).unwrap() + } + + #[test] + fn a_right_answer_climbs_one_box_and_a_wrong_one_falls_to_the_first() { + let today = date("2026-11-14"); + assert_eq!(next_state(None, true, today), (2, date("2026-11-15")), "a new card answered right goes to box 2"); + assert_eq!(next_state(Some(2), true, today), (3, date("2026-11-17"))); + assert_eq!(next_state(Some(3), true, today), (4, date("2026-11-21"))); + assert_eq!(next_state(Some(4), true, today), (5, date("2026-12-05"))); + assert_eq!(next_state(Some(5), true, today), (5, date("2026-12-05")), "box 5 is the last"); + assert_eq!(next_state(Some(5), false, today), (1, date("2026-11-15")), "a miss is due tomorrow"); + assert_eq!(next_state(None, false, today), (1, date("2026-11-15"))); + } + + #[test] + fn answers_move_the_stored_card_on_the_injected_dates() { + let mut conn = db(); + let s = scenario(&mut conn, "BTN", "", false); + record(&conn, s, "AKs", true, date("2026-11-14"), "2026-11-14T10:00:00").unwrap(); + assert_eq!(state(&conn, s, "AKs"), (2, "2026-11-15".to_string())); + record(&conn, s, "AKs", true, date("2026-11-15"), "2026-11-15T10:00:00").unwrap(); + assert_eq!(state(&conn, s, "AKs"), (3, "2026-11-18".to_string())); + record(&conn, s, "AKs", false, date("2026-11-18"), "2026-11-18T10:00:00").unwrap(); + assert_eq!(state(&conn, s, "AKs"), (1, "2026-11-19".to_string())); + let created: String = conn.query_row("SELECT created_on FROM training_cards", [], |r| r.get(0)).unwrap(); + assert_eq!(created, "2026-11-14", "the creation day stays"); + } + + #[test] + fn new_cards_go_borderline_first_then_by_frequency_then_grid_order() { + let candidate = |hand: &str, borderline: bool, frequency: i64, grid_index: usize| NewCandidate { scenario_id: 1, hand: hand.into(), borderline, frequency, grid_index }; + let ordered = order_new_cards(vec![ + candidate("AA", false, 0, 0), + candidate("72o", false, 9, 100), + candidate("KQs", false, 9, 14), + candidate("T9s", true, 0, 60), + candidate("J9s", true, 4, 70), + ]); + let hands: Vec<&str> = ordered.iter().map(|c| c.hand.as_str()).collect(); + assert_eq!(hands, ["J9s", "T9s", "KQs", "72o", "AA"]); + } + + #[test] + fn the_daily_quota_limits_new_cards_and_due_cards_come_first() { + let mut conn = db(); + let s = scenario(&mut conn, "BTN", "", false); + conn.execute("UPDATE range_settings SET value = '2' WHERE key = 'new_cards_per_day'", []).unwrap(); + let today = date("2026-11-14"); + // Two new cards fill today's quota. + for _ in 0..2 { + let (_, hand) = next_card(&conn, today).unwrap().unwrap(); + record(&conn, s, &hand, true, today, "2026-11-14T10:00:00").unwrap(); + } + assert_eq!(next_card(&conn, today).unwrap(), None, "the quota is used up and nothing is due"); + // Tomorrow the two cards are due and come before anything new. + let tomorrow = date("2026-11-15"); + let (scenario_id, _) = next_card(&conn, tomorrow).unwrap().unwrap(); + assert_eq!(scenario_id, s); + let due = due_cards(&conn, tomorrow).unwrap(); + assert_eq!(due.len(), 2); + assert_eq!(next_card(&conn, tomorrow).unwrap(), Some(due[0].clone())); + } + + #[test] + fn study_only_scenarios_never_enter_the_review() { + let mut conn = db(); + let study = scenario(&mut conn, "BTN", "", true); + assert!(new_candidates(&conn).unwrap().is_empty()); + record(&conn, study, "AA", false, date("2026-11-14"), "2026-11-14T10:00:00").unwrap(); + assert!(due_cards(&conn, date("2026-11-15")).unwrap().is_empty()); + assert_eq!(overview(&conn, date("2026-11-15"), None).unwrap()["mastered"]["total"], 0); + } + + #[test] + fn the_overview_counts_boxes_progress_and_the_hands_missed_most() { + let mut conn = db(); + let s = scenario(&mut conn, "BTN", "", false); + let today = date("2026-11-14"); + for (hand, correct) in [("AA", true), ("KK", true), ("QQ", false)] { + conn.execute( + "INSERT INTO training_attempts (scenario_id, hand_class, source, answer_immediate, correct, created_at) VALUES (?1, ?2, 'scenario', '1', ?3, '2026-11-13T10:00:00')", + params![s, hand, correct], + ) + .unwrap(); + record(&conn, s, hand, correct, today, "2026-11-14T10:00:00").unwrap(); + } + for _ in 0..3 { + record(&conn, s, "AA", true, today, "2026-11-14T10:00:00").unwrap(); + } + let view = overview(&conn, date("2026-11-20"), None).unwrap(); + let boxes: Vec = view["boxes"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + assert_eq!(boxes.iter().sum::(), 3); + assert_eq!(boxes[4], 1, "AA climbed to box 5 after four right answers"); + assert_eq!(view["mastered"], json!({ "count": 1, "total": 3 })); + assert_eq!(view["success7"]["answers"], 3); + assert_eq!(view["hardest"][0]["handClass"], "QQ"); + assert_eq!(view["today"]["due"], 2, "KK (due the 17th) and QQ (due the 15th) are due on the 20th"); + } +} diff --git a/crates/core/src/services/training.rs b/crates/core/src/services/training.rs new file mode 100644 index 00000000..87cf0e55 --- /dev/null +++ b/crates/core/src/services/training.rs @@ -0,0 +1,515 @@ +//! The range quiz: drawing a question from the player's own ranges and checking the answer. +//! +//! The reference is the player's strategy. "Wrong" only means "not what your range says". + +use std::collections::HashMap; + +use rusqlite::{params, Connection, OptionalExtension}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::engines::actions::{big_blind, parse_actions, ActionKind}; +use crate::engines::preflop_line::player_positions; +use crate::engines::quiz::{actions_of_line, borderline_neighbor, build_table, QuizTable, SeatAction}; +use crate::engines::range_scenarios::hand_classes; +use crate::repos::hands_query::hero_resolution_sql; +use crate::services::analysis::{hands_for_analysis, AnalysisFilters, AnalysisHand}; +use crate::services::range_adherence::stacks_of; +use crate::services::review; +use crate::services::user_ranges::{self, RangeError, Res}; +use crate::util::eq_ic; + +const SUITS: [char; 4] = ['s', 'h', 'd', 'c']; +/// With the borderline priority on, one draw in this many is a borderline hand. +const BORDERLINE_ONE_IN: usize = 2; +/// How many of the most-missed hands the "missed" source draws from. +const HARDEST_POOL: i64 = 5; + +/// A small deterministic generator: the caller owns the seed, so a draw can be replayed in tests. +pub struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Self { + Self(seed | 1) + } + + fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + pub fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct QuestionRequest { + /// "scenario", "program", "deviation", "review" (the cards due today, then new ones) or "missed". + pub source: String, + pub spot_id: Option, + pub program_id: Option, + /// Restricts the deviation source to one range. + pub scenario_id: Option, + pub hero_name: Option, + /// Today as "YYYY-MM-DD", for the review sources. + pub today: String, + /// Overrides the stored setting. + pub prioritize_borderline: Option, + pub seed: u64, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct AnswerRequest { + pub scenario_id: i64, + pub hand_class: String, + pub source: String, + pub hand_id: Option, + /// The palette action chosen. + pub answer_action_id: i64, + /// "fold", "call" or "allin", when the chosen action plans a response. + pub answer_response: Option, +} + +struct Palette { + list: Vec, + response_of: HashMap, +} + +fn load_palette(conn: &Connection) -> Res { + let mut stmt = conn.prepare("SELECT id, label, color, immediate, size_value, size_unit, response FROM range_actions ORDER BY sort_order, id")?; + let mut list = Vec::new(); + let mut response_of = HashMap::new(); + for row in stmt.query_map([], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?, r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, String>(6)?)) + })? { + let (id, label, color, immediate, size_value, size_unit, response) = row?; + list.push(json!({ "actionId": id, "label": label, "color": color, "immediate": immediate, "sizeValue": size_value, "sizeUnit": size_unit, "response": response })); + response_of.insert(id, response); + } + Ok(Palette { list, response_of }) +} + +fn range_of(conn: &Connection, scenario_id: i64) -> Res> { + let mut stmt = conn.prepare("SELECT hand, action_id FROM range_hands WHERE scenario_id = ?1")?; + let rows = stmt.query_map([scenario_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?.collect::, _>>()?; + Ok(rows) +} + +struct ScenarioInfo { + id: i64, + spot_id: i64, + name: String, + format: String, + hero_position: String, + line: String, + line_sizes: HashMap, + opponent: String, + stack_bb: f64, +} + +fn scenario_info(conn: &Connection, scenario_id: i64) -> Res> { + Ok(conn + .query_row( + "SELECT sc.id, sp.id, sp.name, sp.format, sp.hero_position, sp.line, sp.line_sizes, sp.opponent, sc.stack_bb + FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sc.id = ?1", + [scenario_id], + |r| { + let sizes: Option = r.get(6)?; + Ok(ScenarioInfo { + id: r.get(0)?, + spot_id: r.get(1)?, + name: r.get(2)?, + format: r.get(3)?, + hero_position: r.get(4)?, + line: r.get(5)?, + line_sizes: sizes.and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default(), + opponent: r.get(7)?, + stack_bb: r.get(8)?, + }) + }, + ) + .optional()?) +} + +/// Two cards of a hand class with random suits. +fn cards_of(hand: &str, rng: &mut Rng) -> [String; 2] { + let (first, second) = (&hand[0..1], &hand[1..2]); + let a = SUITS[rng.below(4)]; + let b = if hand.ends_with('s') { + a + } else { + let others: Vec = SUITS.iter().copied().filter(|s| *s != a).collect(); + others[rng.below(3)] + }; + [format!("{first}{a}"), format!("{second}{b}")] +} + +fn table_json(table: &QuizTable) -> Value { + json!({ + "potBb": table.pot_bb, + "seats": table.seats.iter().map(|s| json!({ "position": s.position, "isHero": s.is_hero, "stackBb": s.stack_bb, "action": s.action, "betBb": s.bet_bb })).collect::>(), + }) +} + +/// The actions in front of the hero in a real hand, with their real sizes. +fn real_actions(hand: &AnalysisHand, hero_seat: &str) -> Vec { + let seats = player_positions(&hand.player_positions); + let bb = big_blind(&hand.blinds) as f64; + let mut out = Vec::new(); + for action in parse_actions(&hand.preflop) { + if action.kind == ActionKind::Post { + continue; + } + let Some(position) = seats.get(&action.player.to_lowercase()) else { continue }; + if position == hero_seat { + break; + } + let verb = match (action.kind, action.is_all_in) { + (_, true) => "allin", + (ActionKind::Fold, _) => "fold", + (ActionKind::Call, _) => "call", + (ActionKind::Raise | ActionKind::Bet, _) => "raise", + _ => continue, + }; + let bet_bb = (verb == "raise" && bb > 0.0).then(|| action.amount_to.unwrap_or(0.0) / bb).filter(|b| *b > 0.0); + out.push(SeatAction { position: position.clone(), verb: verb.into(), bet_bb }); + } + out +} + +/// A question about one hand of a range. +#[allow(clippy::too_many_arguments)] +fn question_json(info: &ScenarioInfo, hands: &HashMap, palette: &Palette, hand_class: &str, cards: [String; 2], table: &QuizTable, source: &str, hand_id: Option<&str>) -> Value { + let used: Vec = hands.values().copied().collect(); + let choices: Vec<&Value> = palette.list.iter().filter(|a| used.contains(&a["actionId"].as_i64().unwrap_or(-1))).collect(); + json!({ + "scenarioId": info.id, "spotId": info.spot_id, "name": info.name, "format": info.format, "heroPosition": info.hero_position, "line": info.line, + "opponent": info.opponent, "stackBb": info.stack_bb, "handClass": hand_class, "cards": cards, "choices": choices, "table": table_json(table), + "source": source, "handId": hand_id, + }) +} + +fn prioritize(conn: &Connection, request: &QuestionRequest) -> Res { + Ok(match request.prioritize_borderline { + Some(flag) => flag, + None => user_ranges::setting(conn, "prioritize_borderline")?.map_or(true, |v| v == "1"), + }) +} + +/// A scenario of a spot for the quiz: study-only spots never come up. +fn pick_scenario(conn: &Connection, spot_ids: &[i64], rng: &mut Rng) -> Res> { + let mut pool = Vec::new(); + for spot in spot_ids { + let mut stmt = conn.prepare("SELECT sc.id FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sp.id = ?1 AND sp.study_only = 0")?; + let ids = stmt.query_map([spot], |r| r.get(0))?.collect::, _>>()?; + pool.extend(ids); + } + Ok((!pool.is_empty()).then(|| pool[rng.below(pool.len())])) +} + +fn pick_hand(hands: &HashMap, borderline_first: bool, rng: &mut Rng) -> String { + let all = hand_classes(); + if borderline_first && rng.below(BORDERLINE_ONE_IN) == 0 { + let edge: Vec<&String> = all.iter().filter(|h| borderline_neighbor(hands, h).is_some()).collect(); + if !edge.is_empty() { + return edge[rng.below(edge.len())].clone(); + } + } + all[rng.below(all.len())].clone() +} + +/// Draws the next question; `None` when the source holds nothing to ask. +pub fn next_question(conn: &Connection, request: &QuestionRequest) -> Res> { + let mut rng = Rng::new(request.seed); + let palette = load_palette(conn)?; + if request.source == "deviation" { + return deviation_question(conn, request, &palette, &mut rng); + } + if request.source == "review" { + let today = review::parse_day(&request.today).ok_or_else(|| RangeError::Invalid("today is required".into()))?; + let Some((scenario_id, hand)) = review::next_card(conn, today)? else { return Ok(None) }; + return question_for(conn, &palette, scenario_id, Some(&hand), false, "review", &mut rng).map(Some); + } + if request.source == "missed" { + let missed = review::hardest_hands(conn, HARDEST_POOL)?; + if missed.is_empty() { + return Ok(None); + } + let (scenario_id, hand, _, _) = &missed[rng.below(missed.len())]; + return question_for(conn, &palette, *scenario_id, Some(hand), false, "missed", &mut rng).map(Some); + } + + let spots: Vec = match request.source.as_str() { + "scenario" => request.spot_id.into_iter().collect(), + "program" => { + let Some(program) = request.program_id else { return Err(RangeError::Invalid("programId is required".into())) }; + let mut stmt = conn.prepare("SELECT spot_id FROM range_program_spots WHERE program_id = ?1 ORDER BY sort_order")?; + let ids = stmt.query_map([program], |r| r.get(0))?.collect::, _>>()?; + ids + } + other => return Err(RangeError::Invalid(format!("unknown source: {other}"))), + }; + let Some(scenario_id) = pick_scenario(conn, &spots, &mut rng)? else { return Ok(None) }; + let borderline = prioritize(conn, request)?; + question_for(conn, &palette, scenario_id, None, borderline, &request.source, &mut rng).map(Some) +} + +/// A question about one hand of a scenario; without a hand one is drawn. +fn question_for(conn: &Connection, palette: &Palette, scenario_id: i64, hand: Option<&str>, borderline_first: bool, source: &str, rng: &mut Rng) -> Res { + let info = scenario_info(conn, scenario_id)?.ok_or(RangeError::NotFound)?; + let hands = range_of(conn, scenario_id)?; + let hand = hand.map_or_else(|| pick_hand(&hands, borderline_first, rng), str::to_string); + let table = build_table(&info.format, &info.hero_position, &actions_of_line(&info.line, &info.line_sizes), &HashMap::new(), info.stack_bb); + let cards = cards_of(&hand, rng); + Ok(question_json(&info, &hands, palette, &hand, cards, &table, source, None)) +} + +/// A hand where the hero left their range, on the real table. +fn deviation_question(conn: &Connection, request: &QuestionRequest, palette: &Palette, rng: &mut Rng) -> Res> { + let Some(hero) = request.hero_name.as_deref().filter(|h| !h.is_empty()) else { return Err(RangeError::Invalid("heroName is required".into())) }; + let filter = "c.status = 'deviation' AND c.hero_name IN ".to_string() + + &hero_resolution_sql("@hero") + + " AND c.scenario_id IN (SELECT sc.id FROM range_scenarios sc JOIN range_spots sp ON sp.id = sc.spot_id WHERE sp.study_only = 0)" + + " AND (@scenario IS NULL OR c.scenario_id = @scenario)"; + let named = |extra: &mut Vec<(&str, rusqlite::types::Value)>| { + extra.push(("@hero", rusqlite::types::Value::Text(hero.to_string()))); + extra.push(("@scenario", request.scenario_id.map_or(rusqlite::types::Value::Null, rusqlite::types::Value::Integer))); + }; + let mut binds = Vec::new(); + named(&mut binds); + let params: Vec<(&str, &dyn rusqlite::ToSql)> = binds.iter().map(|(n, v)| (*n, v as &dyn rusqlite::ToSql)).collect(); + let total: i64 = conn.query_row(&format!("SELECT COUNT(*) FROM hand_range_checks c WHERE {filter}"), ¶ms[..], |r| r.get(0))?; + if total == 0 { + return Ok(None); + } + let offset = rng.below(total as usize) as i64; + let row: (String, i64, String, Option) = conn.query_row( + &format!("SELECT c.hand_id, c.scenario_id, c.hand_class, c.cards FROM hand_range_checks c WHERE {filter} ORDER BY c.played_at DESC LIMIT 1 OFFSET {offset}"), + ¶ms[..], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + )?; + let (hand_id, scenario_id, hand_class, raw_cards) = row; + let info = scenario_info(conn, scenario_id)?.ok_or(RangeError::NotFound)?; + let hands = range_of(conn, scenario_id)?; + + let real = hands_for_analysis(conn, &AnalysisFilters { hero_name: Some(hero.to_string()), hand_id: Some(hand_id.clone()), ..Default::default() })?; + let table = match real.first() { + Some(hand) => { + let bb = big_blind(&hand.blinds) as f64; + let seats = player_positions(&hand.player_positions); + let mut stacks = HashMap::new(); + if bb > 0.0 { + for (name, stack) in stacks_of(conn, &[hand.hand_id.as_str()])?.remove(&hand.hand_id).unwrap_or_default() { + if let Some(position) = seats.get(&name.to_lowercase()) { + stacks.insert(position.clone(), stack / bb); + } + } + } + let hero_name = hand.hero_name.as_deref().unwrap_or(hero); + let hero_seat = seats.iter().find(|(name, _)| eq_ic(name, hero_name)).map_or(info.hero_position.clone(), |(_, p)| p.clone()); + build_table(&info.format, &info.hero_position, &real_actions(hand, &hero_seat), &stacks, info.stack_bb) + } + None => build_table(&info.format, &info.hero_position, &actions_of_line(&info.line, &info.line_sizes), &HashMap::new(), info.stack_bb), + }; + let cards = raw_cards.map(|c| c.split_whitespace().map(str::to_string).collect::>()).filter(|c| c.len() == 2).map(|c| [c[0].clone(), c[1].clone()]).unwrap_or_else(|| cards_of(&hand_class, rng)); + Ok(Some(question_json(&info, &hands, palette, &hand_class, cards, &table, "deviation", Some(&hand_id)))) +} + +/// Checks an answer against the range and records the attempt. A compound answer (action, then +/// answer to a raise) is right only when both parts are. +pub fn check_answer(conn: &Connection, request: &AnswerRequest, today: chrono::NaiveDate, now: &str) -> Res { + let hands = range_of(conn, request.scenario_id)?; + let Some(expected_id) = hands.get(&request.hand_class).copied() else { return Err(RangeError::NotFound) }; + let palette = load_palette(conn)?; + let planned = palette.response_of.get(&expected_id).filter(|r| r.as_str() != "none").cloned(); + + let immediate_correct = request.answer_action_id == expected_id; + // The answer to a raise only counts once the action itself is right. + let response_correct = match (&planned, immediate_correct) { + (Some(expected), true) => Some(request.answer_response.as_deref() == Some(expected.as_str())), + _ => None, + }; + let correct = immediate_correct && response_correct.unwrap_or(true); + let neighbor = borderline_neighbor(&hands, &request.hand_class); + + conn.execute( + "INSERT INTO training_attempts (scenario_id, hand_class, source, hand_id, answer_immediate, answer_response, correct, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![request.scenario_id, request.hand_class, request.source, request.hand_id, request.answer_action_id.to_string(), request.answer_response, correct, now], + )?; + // The answer also moves the hand's review card. + let (box_number, due) = review::record(conn, request.scenario_id, &request.hand_class, correct, today, now)?; + Ok(json!({ + "box": box_number, "dueOn": due.format("%Y-%m-%d").to_string(), + "correct": correct, "immediateCorrect": immediate_correct, "responseCorrect": response_correct, + "expectedActionId": expected_id, "expectedResponse": planned, "answeredActionId": request.answer_action_id, + "handClass": request.hand_class, "scenarioId": request.scenario_id, "hands": hands, + "borderline": neighbor.is_some(), "neighbor": neighbor, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::migrations; + use crate::services::range_adherence::ensure_computed; + use crate::services::user_ranges::{save_actions, save_hands, save_program, save_spot, ActionInput, ProgramInput, SpotInput, StartPoint}; + use std::collections::BTreeMap; + + fn db() -> Connection { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn + } + + fn action_id(conn: &Connection, label: &str) -> i64 { + conn.query_row("SELECT id FROM range_actions WHERE label = ?1", [label], |r| r.get(0)).unwrap() + } + + /// BB vs "SB limp": AKo = ISO (fold if raised), everything else = Check. + fn spot(conn: &mut Connection, study_only: bool, line: &str, hero: &str) -> (i64, i64) { + let input = SpotInput { + format: "3max".into(), + hero_position: hero.into(), + line: line.into(), + opponent: "any".into(), + study_only, + depths: vec![10.0], + start: StartPoint { kind: "empty".into(), ..Default::default() }, + ..Default::default() + }; + let spot = save_spot(conn, &input).unwrap(); + let scenario: i64 = conn.query_row("SELECT id FROM range_scenarios WHERE spot_id = ?1", [spot], |r| r.get(0)).unwrap(); + (spot, scenario) + } + + fn iso_and_check(conn: &mut Connection) -> (i64, i64) { + save_actions( + conn, + &[ActionInput { id: None, label: "ISO".into(), color: "#a07cf0".into(), immediate: "iso".into(), size_value: None, size_unit: None, response: "fold".into() }], + ) + .unwrap(); + (action_id(conn, "ISO"), action_id(conn, "Check")) + } + + fn request(source: &str, spot: i64, seed: u64) -> QuestionRequest { + QuestionRequest { source: source.into(), spot_id: Some(spot), seed, prioritize_borderline: Some(false), ..Default::default() } + } + + #[test] + fn the_quiz_never_asks_about_a_study_only_scenario() { + let mut conn = db(); + let (study, _) = spot(&mut conn, true, "btn:fold,sb:call", "BB"); + let (quiz, _) = spot(&mut conn, false, "", "BTN"); + assert!(next_question(&conn, &request("scenario", study, 1)).unwrap().is_none()); + let program = save_program(&mut conn, &ProgramInput { name: "Mixed".into(), spot_ids: vec![study, quiz], ..Default::default() }).unwrap(); + for seed in 1..60 { + let question = next_question(&conn, &QuestionRequest { source: "program".into(), program_id: Some(program), seed, ..Default::default() }).unwrap().unwrap(); + assert_eq!(question["spotId"], quiz); + } + } + + #[test] + fn a_question_carries_the_table_and_one_button_per_action_in_the_range() { + let mut conn = db(); + let (spot_id, scenario) = spot(&mut conn, false, "btn:fold,sb:call", "BB"); + let (iso, _) = iso_and_check(&mut conn); + save_hands(&mut conn, scenario, &BTreeMap::from([("AKo".to_string(), iso)])).unwrap(); + let question = next_question(&conn, &request("scenario", spot_id, 7)).unwrap().unwrap(); + assert_eq!(question["table"]["potBb"], 2.0); + assert_eq!(question["choices"].as_array().unwrap().len(), 2, "Fold (the default) and ISO"); + assert_eq!(question["cards"].as_array().unwrap().len(), 2); + let hand = question["handClass"].as_str().unwrap(); + let cards: Vec<&str> = question["cards"].as_array().unwrap().iter().map(|c| c.as_str().unwrap()).collect(); + assert_eq!(cards[0].ends_with(cards[1].chars().last().unwrap()), hand.ends_with('s'), "suited hands share a suit"); + } + + #[test] + fn the_borderline_priority_draws_edge_hands_about_half_the_time() { + let mut conn = db(); + let (spot_id, scenario) = spot(&mut conn, false, "", "BTN"); + let (iso, _) = iso_and_check(&mut conn); + save_hands(&mut conn, scenario, &BTreeMap::from([("AKo".to_string(), iso)])).unwrap(); + let hands = range_of(&conn, scenario).unwrap(); + let edge_share = |prioritize: bool| { + let edge = (1..=300u64) + .filter(|seed| { + let q = next_question(&conn, &QuestionRequest { prioritize_borderline: Some(prioritize), ..request("scenario", spot_id, *seed) }).unwrap().unwrap(); + borderline_neighbor(&hands, q["handClass"].as_str().unwrap()).is_some() + }) + .count(); + edge as f64 / 300.0 + }; + assert!(edge_share(true) > 0.35, "half of the draws are edge hands"); + assert!(edge_share(false) < 0.1, "uniform draws rarely are"); + } + + #[test] + fn a_compound_answer_is_right_only_when_both_parts_are() { + let mut conn = db(); + let (_, scenario) = spot(&mut conn, false, "btn:fold,sb:call", "BB"); + let (iso, check) = iso_and_check(&mut conn); + save_hands(&mut conn, scenario, &BTreeMap::from([("AKo".to_string(), iso)])).unwrap(); + let date = chrono::NaiveDate::from_ymd_opt(2026, 11, 14).unwrap(); + let answer = |action: i64, response: Option<&str>| AnswerRequest { + scenario_id: scenario, + hand_class: "AKo".into(), + source: "scenario".into(), + answer_action_id: action, + answer_response: response.map(str::to_string), + ..Default::default() + }; + let right = check_answer(&conn, &answer(iso, Some("fold")), date, "2026-11-14T10:00:00").unwrap(); + assert_eq!(right["correct"], true); + let half = check_answer(&conn, &answer(iso, Some("call")), date, "2026-11-14T10:00:01").unwrap(); + assert_eq!((half["correct"].clone(), half["immediateCorrect"].clone(), half["responseCorrect"].clone()), (json!(false), json!(true), json!(false))); + let wrong = check_answer(&conn, &answer(check, None), date, "2026-11-14T10:00:02").unwrap(); + assert_eq!((wrong["correct"].clone(), wrong["immediateCorrect"].clone(), wrong["responseCorrect"].clone()), (json!(false), json!(false), Value::Null)); + assert_eq!(wrong["expectedActionId"], iso); + assert_eq!((wrong["box"].clone(), wrong["dueOn"].clone()), (json!(1), json!("2026-11-15")), "a miss goes back to box 1 for tomorrow"); + let review = next_question(&conn, &QuestionRequest { source: "review".into(), today: "2026-11-15".into(), seed: 1, ..Default::default() }).unwrap().unwrap(); + assert_eq!((review["handClass"].clone(), review["source"].clone()), (json!("AKo"), json!("review")), "the missed hand is the first card due tomorrow"); + assert_eq!(conn.query_row("SELECT COUNT(*) FROM training_attempts WHERE correct = 0", [], |r| r.get::<_, i64>(0)).unwrap(), 2); + assert!(right["borderline"].as_bool().unwrap(), "AKo has neighbours on another action"); + } + + #[test] + fn my_deviations_only_returns_deviations_on_the_real_table() { + let mut conn = db(); + let (_, scenario) = spot(&mut conn, false, "btn:fold,sb:call", "BB"); + let (iso, _) = iso_and_check(&mut conn); + save_hands(&mut conn, scenario, &BTreeMap::from([("AKo".to_string(), iso)])).unwrap(); + let positions = [("Btn", "BTN", None), ("Sb", "SB", None), ("Hero", "BB", None::<&str>)]; + for (id, cards, acts) in [("dev", "Ah Kc", "Hero: Checks"), ("ok", "7h 2c", "Hero: Checks")] { + conn.execute( + "INSERT INTO hands (id, room, date_time, blinds, player_count, preflop_action) VALUES (?1, 'Winamax', '2026-11-10 20:00:00', '10/20', 3, ?2)", + params![id, format!("Btn: Folds\nSb: Calls 10\n{acts}")], + ) + .unwrap(); + for (name, position, _) in positions { + let held = (name == "Hero").then_some(cards); + conn.execute("INSERT INTO player_hands (hand_id, player_name, position, cards, stack, net_profit) VALUES (?1, ?2, ?3, ?4, 220, 0)", params![id, name, position, held]).unwrap(); + } + } + conn.execute("INSERT INTO players (name) VALUES ('Hero')", []).unwrap(); + ensure_computed(&mut conn, "Hero").unwrap(); + // 72o is planned as Fold (the default): checking it is a deviation as well. + let request = QuestionRequest { source: "deviation".into(), hero_name: Some("Hero".into()), ..Default::default() }; + let mut seen = std::collections::HashSet::new(); + for seed in 1..40 { + let question = next_question(&conn, &QuestionRequest { seed, ..request.clone() }).unwrap().unwrap(); + seen.insert(question["handId"].as_str().unwrap().to_string()); + assert_eq!(question["source"], "deviation"); + } + assert_eq!(seen.len(), 2, "both hands deviate from the plan"); + let question = next_question(&conn, &QuestionRequest { seed: 3, ..request.clone() }).unwrap().unwrap(); + let hero = question["table"]["seats"].as_array().unwrap().iter().find(|s| s["isHero"] == true).unwrap().clone(); + assert_eq!(hero["stackBb"], 10.0, "220 chips at 10/20 is 11 bb, minus the big blind posted"); + assert_eq!(question["table"]["potBb"], 2.0); + } +} diff --git a/crates/core/src/services/user_ranges.rs b/crates/core/src/services/user_ranges.rs new file mode 100644 index 00000000..e7d4ae48 --- /dev/null +++ b/crates/core/src/services/user_ranges.rs @@ -0,0 +1,872 @@ +//! The player's own preflop ranges: palette of actions, situations ("spots"), one range per stack +//! depth, programs and settings. SpinTracker ships no range: everything here is the player's data. +//! +//! The database does not enforce foreign keys, so every deletion cascades by hand inside one +//! transaction. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use rusqlite::{params, Connection, OptionalExtension, Transaction}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::engines::range_scenarios::{default_name, hand_classes, is_hand_class, parse_hex}; +use crate::Error; + +const FORMATS: [&str; 2] = ["3max", "hu"]; +const POSITIONS_3MAX: [&str; 3] = ["BTN", "SB", "BB"]; +const POSITIONS_HU: [&str; 2] = ["SB", "BB"]; +const LINE_VERBS: [&str; 4] = ["fold", "call", "raise", "all-in"]; +const IMMEDIATES: [&str; 8] = ["fold", "check", "call", "limp", "raise", "iso", "threebet", "allin"]; +const SIZE_UNITS: [&str; 3] = ["bb", "x", "pct_stack"]; +const RESPONSES: [&str; 4] = ["none", "fold", "call", "allin"]; +const OPPONENTS: [&str; 2] = ["any", "reg"]; +const MAX_LABEL_CHARS: usize = 40; +const MAX_NAME_CHARS: usize = 80; +const MAX_STACK_BB: f64 = 200.0; +const MAX_NEW_CARDS_PER_DAY: i64 = 500; +const MAX_DEFAULT_STACKS: usize = 20; + +/// A failure the caller can tell apart: a bad request, a clash with existing data, a missing row. +#[derive(Debug)] +pub enum RangeError { + Invalid(String), + /// The data clashes with a row that exists; `existing_id` is that row when it is a spot. + Conflict { message: String, existing_id: Option }, + NotFound, + Other(Error), +} + +impl From for RangeError { + fn from(e: Error) -> Self { + Self::Other(e) + } +} + +impl From for RangeError { + fn from(e: rusqlite::Error) -> Self { + Self::Other(e.into()) + } +} + +impl From for RangeError { + fn from(e: serde_json::Error) -> Self { + Self::Other(e.into()) + } +} + +pub type Res = std::result::Result; + +fn invalid(message: impl Into) -> Res { + Err(RangeError::Invalid(message.into())) +} + +pub(crate) fn now() -> String { + chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S").to_string() +} + +// --------------------------------------------------------------------------------------------- +// Actions (the palette) +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ActionInput { + #[serde(default)] + pub id: Option, + pub label: String, + pub color: String, + pub immediate: String, + #[serde(default)] + pub size_value: Option, + #[serde(default)] + pub size_unit: Option, + #[serde(default = "default_response")] + pub response: String, +} + +fn default_response() -> String { + "none".into() +} + +pub(crate) fn validate_action(a: &ActionInput) -> Res<()> { + let label = a.label.trim(); + if label.is_empty() || label.chars().count() > MAX_LABEL_CHARS { + return invalid(format!("an action label has 1 to {MAX_LABEL_CHARS} characters")); + } + if parse_hex(&a.color).is_none() { + return invalid("a colour is a hex value such as #5b8def"); + } + if !IMMEDIATES.contains(&a.immediate.as_str()) { + return invalid(format!("unknown immediate action: {}", a.immediate)); + } + if !RESPONSES.contains(&a.response.as_str()) { + return invalid(format!("unknown response: {}", a.response)); + } + match (&a.size_value, &a.size_unit) { + (None, None) => {} + (Some(v), Some(u)) if *v > 0.0 && v.is_finite() && SIZE_UNITS.contains(&u.as_str()) => {} + _ => return invalid("a size needs a positive value and a unit (bb, x or pct_stack)"), + } + Ok(()) +} + +pub fn list_actions(conn: &Connection) -> Res { + let mut stmt = conn.prepare( + "SELECT a.id, a.label, a.color, a.immediate, a.size_value, a.size_unit, a.response, a.sort_order, + (SELECT COUNT(*) FROM range_hands h WHERE h.action_id = a.id) + FROM range_actions a ORDER BY a.sort_order, a.id", + )?; + let rows = stmt + .query_map([], |r| { + Ok(json!({ + "id": r.get::<_, i64>(0)?, "label": r.get::<_, String>(1)?, "color": r.get::<_, String>(2)?, + "immediate": r.get::<_, String>(3)?, "sizeValue": r.get::<_, Option>(4)?, "sizeUnit": r.get::<_, Option>(5)?, + "response": r.get::<_, String>(6)?, "sortOrder": r.get::<_, i64>(7)?, "usedHands": r.get::<_, i64>(8)?, + })) + })? + .collect::, _>>()?; + Ok(Value::Array(rows)) +} + +/// Creates or updates the given actions; their order in the list becomes the palette order. +/// Actions left out of the list are kept (they are removed with `delete_action`). +pub fn save_actions(conn: &mut Connection, actions: &[ActionInput]) -> Res { + for a in actions { + validate_action(a)?; + } + let tx = conn.transaction()?; + for (order, a) in actions.iter().enumerate() { + let label = a.label.trim(); + let clash: Option = + tx.query_row("SELECT id FROM range_actions WHERE label = ?1 AND id IS NOT ?2", params![label, a.id], |r| r.get(0)).optional()?; + if clash.is_some() { + return Err(RangeError::Conflict { message: format!("an action named {label} already exists"), existing_id: None }); + } + let (size_value, size_unit) = (a.size_value, a.size_unit.as_deref()); + match a.id { + Some(id) => { + let changed = tx.execute( + "UPDATE range_actions SET label = ?1, color = ?2, immediate = ?3, size_value = ?4, size_unit = ?5, response = ?6, sort_order = ?7 WHERE id = ?8", + params![label, a.color, a.immediate, size_value, size_unit, a.response, order as i64, id], + )?; + if changed == 0 { + return Err(RangeError::NotFound); + } + } + None => { + tx.execute( + "INSERT INTO range_actions (label, color, immediate, size_value, size_unit, response, sort_order) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![label, a.color, a.immediate, size_value, size_unit, a.response, order as i64], + )?; + } + } + } + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + list_actions(conn) +} + +/// Removes an action. When ranges use it, `replace_with` must name another action that takes over +/// their hands. +pub fn delete_action(conn: &mut Connection, id: i64, replace_with: Option) -> Res<()> { + let tx = conn.transaction()?; + let exists: bool = tx.query_row("SELECT COUNT(*) FROM range_actions WHERE id = ?1", [id], |r| r.get::<_, i64>(0))? > 0; + if !exists { + return Err(RangeError::NotFound); + } + let used: i64 = tx.query_row("SELECT COUNT(*) FROM range_hands WHERE action_id = ?1", [id], |r| r.get(0))?; + if used > 0 { + let Some(target) = replace_with.filter(|t| *t != id) else { + return invalid(format!("{used} hands use this action: choose a replacement")); + }; + let target_exists: bool = tx.query_row("SELECT COUNT(*) FROM range_actions WHERE id = ?1", [target], |r| r.get::<_, i64>(0))? > 0; + if !target_exists { + return invalid("the replacement action does not exist"); + } + tx.execute("UPDATE range_hands SET action_id = ?1 WHERE action_id = ?2", params![target, id])?; + } + tx.execute("DELETE FROM range_actions WHERE id = ?1", [id])?; + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + Ok(()) +} + +pub(crate) fn first_action(tx: &Transaction) -> Res { + let id: Option = tx.query_row("SELECT id FROM range_actions ORDER BY sort_order, id LIMIT 1", [], |r| r.get(0)).optional()?; + id.ok_or_else(|| RangeError::Invalid("the action palette is empty".into())) +} + +// --------------------------------------------------------------------------------------------- +// Spots and scenarios +// --------------------------------------------------------------------------------------------- + +/// Where the hands of a new range come from. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct StartPoint { + /// "empty" (every hand in the first action), "spot" (another spot's range) or "depth" (another + /// depth of the same spot). + pub kind: String, + pub spot_id: Option, + pub stack_bb: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct SpotInput { + pub id: Option, + pub name: String, + pub format: String, + pub hero_position: String, + pub line: String, + pub line_sizes: Option, + pub opponent: String, + pub study_only: bool, + /// Depths to create (new spots only; later depths go through `add_depth`). + pub depths: Vec, + pub start: StartPoint, +} + +/// The line normalised to the form `engines::range_scenarios::canonical_line` produces +/// ("btn:fold,sb:call"), checked against the seats that speak before the hero. +pub(crate) fn normalize_line(format: &str, hero: &str, line: &str) -> Res { + let seats: &[&str] = if format == "hu" { &POSITIONS_HU } else { &POSITIONS_3MAX }; + let Some(hero_index) = seats.iter().position(|p| *p == hero) else { + return invalid(format!("{hero} does not play {format}")); + }; + let entries: Vec<&str> = line.split(',').map(str::trim).filter(|e| !e.is_empty()).collect(); + if entries.len() != hero_index { + return invalid(format!("the line must hold the {hero_index} actions before the hero")); + } + let mut out = Vec::new(); + for (entry, seat) in entries.iter().zip(seats) { + let Some((pos, verb)) = entry.split_once(':') else { return invalid(format!("bad line entry: {entry}")) }; + let (pos, verb) = (pos.trim().to_uppercase(), verb.trim().to_lowercase()); + if pos != *seat || !LINE_VERBS.contains(&verb.as_str()) { + return invalid(format!("bad line entry: {entry}")); + } + out.push(format!("{}:{verb}", pos.to_lowercase())); + } + Ok(out.join(",")) +} + +pub(crate) fn validate_depth(stack: f64) -> Res<()> { + if stack.is_finite() && stack > 0.0 && stack <= MAX_STACK_BB { + Ok(()) + } else { + invalid(format!("a depth is between 0 and {MAX_STACK_BB} bb")) + } +} + +fn spot_exists_with_situation(tx: &Transaction, format: &str, hero: &str, line: &str, opponent: &str, except: Option) -> Res> { + Ok(tx + .query_row( + "SELECT id FROM range_spots WHERE format = ?1 AND hero_position = ?2 AND line = ?3 AND opponent = ?4 AND id IS NOT ?5", + params![format, hero, line, opponent, except], + |r| r.get(0), + ) + .optional()?) +} + +fn insert_scenario(tx: &Transaction, spot_id: i64, stack: f64, start: &StartPoint, own_spot: i64) -> Res { + validate_depth(stack)?; + let taken: bool = tx.query_row("SELECT COUNT(*) FROM range_scenarios WHERE spot_id = ?1 AND stack_bb = ?2", params![spot_id, stack], |r| r.get::<_, i64>(0))? > 0; + if taken { + return Err(RangeError::Conflict { message: format!("{stack} bb already exists for this scenario"), existing_id: Some(spot_id) }); + } + tx.execute("INSERT INTO range_scenarios (spot_id, stack_bb, updated_at) VALUES (?1, ?2, ?3)", params![spot_id, stack, now()])?; + let scenario_id = tx.last_insert_rowid(); + + let source = match start.kind.as_str() { + "spot" => start.spot_id.map(|s| closest_depth(tx, s, stack)).transpose()?.flatten(), + "depth" => match start.stack_bb { + Some(from) => tx + .query_row("SELECT id FROM range_scenarios WHERE spot_id = ?1 AND stack_bb = ?2", params![own_spot, from], |r| r.get(0)) + .optional()?, + None => None, + }, + _ => None, + }; + let fallback = first_action(tx)?; + let mut hands: HashMap = HashMap::new(); + if let Some(source) = source { + let mut stmt = tx.prepare("SELECT hand, action_id FROM range_hands WHERE scenario_id = ?1")?; + for row in stmt.query_map([source], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + let (hand, action) = row?; + hands.insert(hand, action); + } + } else if matches!(start.kind.as_str(), "spot" | "depth") { + return invalid("the range to copy does not exist"); + } + let mut insert = tx.prepare("INSERT INTO range_hands (scenario_id, hand, action_id, weight) VALUES (?1, ?2, ?3, 1.0)")?; + for hand in hand_classes() { + insert.execute(params![scenario_id, hand, hands.get(&hand).copied().unwrap_or(fallback)])?; + } + Ok(scenario_id) +} + +/// The scenario of `spot_id` whose depth is the closest to `stack`. +fn closest_depth(tx: &Transaction, spot_id: i64, stack: f64) -> Res> { + Ok(tx + .query_row( + "SELECT id FROM range_scenarios WHERE spot_id = ?1 ORDER BY ABS(stack_bb - ?2), stack_bb LIMIT 1", + params![spot_id, stack], + |r| r.get(0), + ) + .optional()?) +} + +/// Creates a spot with one range per depth, or updates the situation of an existing spot. +/// Returns the spot id. +pub fn save_spot(conn: &mut Connection, input: &SpotInput) -> Res { + if !FORMATS.contains(&input.format.as_str()) { + return invalid(format!("unknown format: {}", input.format)); + } + let hero = input.hero_position.to_uppercase(); + let line = normalize_line(&input.format, &hero, &input.line)?; + let opponent = if input.opponent.is_empty() { "any" } else { input.opponent.as_str() }; + if !OPPONENTS.contains(&opponent) { + return invalid(format!("unknown opponent: {opponent}")); + } + let name = match input.name.trim() { + "" => default_name(&input.format, &hero, &line.to_lowercase(), opponent), + n if n.chars().count() <= MAX_NAME_CHARS => n.to_string(), + _ => return invalid(format!("a name has at most {MAX_NAME_CHARS} characters")), + }; + let sizes = input.line_sizes.as_ref().filter(|v| !v.is_null()).map(Value::to_string); + + let tx = conn.transaction()?; + if let Some(existing) = spot_exists_with_situation(&tx, &input.format, &hero, &line, opponent, input.id)? { + return Err(RangeError::Conflict { message: "this scenario already exists".into(), existing_id: Some(existing) }); + } + let name_clash: Option = tx.query_row("SELECT id FROM range_spots WHERE name = ?1 AND id IS NOT ?2", params![name, input.id], |r| r.get(0)).optional()?; + if name_clash.is_some() { + return Err(RangeError::Conflict { message: format!("a scenario named {name} already exists"), existing_id: name_clash }); + } + + let id = match input.id { + Some(id) => { + let changed = tx.execute( + "UPDATE range_spots SET name = ?1, format = ?2, hero_position = ?3, line = ?4, line_sizes = ?5, opponent = ?6, study_only = ?7, updated_at = ?8 WHERE id = ?9", + params![name, input.format, hero, line, sizes, opponent, input.study_only, now(), id], + )?; + if changed == 0 { + return Err(RangeError::NotFound); + } + id + } + None => { + if input.depths.is_empty() { + return invalid("at least one depth is required"); + } + let stamp = now(); + tx.execute( + "INSERT INTO range_spots (name, format, hero_position, line, line_sizes, opponent, study_only, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8)", + params![name, input.format, hero, line, sizes, opponent, input.study_only, stamp], + )?; + let id = tx.last_insert_rowid(); + for depth in &input.depths { + insert_scenario(&tx, id, *depth, &input.start, id)?; + } + id + } + }; + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + Ok(id) +} + +/// Removes ranges and everything that hangs off them. +pub(crate) fn purge_scenarios(tx: &Transaction, scenario_ids: &[i64]) -> Res<()> { + for id in scenario_ids { + tx.execute("DELETE FROM range_hands WHERE scenario_id = ?1", [id])?; + tx.execute("DELETE FROM training_attempts WHERE scenario_id = ?1", [id])?; + tx.execute("DELETE FROM training_cards WHERE scenario_id = ?1", [id])?; + tx.execute("DELETE FROM range_scenarios WHERE id = ?1", [id])?; + } + Ok(()) +} + +fn scenario_ids_of(tx: &Transaction, spot_id: i64) -> Res> { + let mut stmt = tx.prepare("SELECT id FROM range_scenarios WHERE spot_id = ?1")?; + let ids = stmt.query_map([spot_id], |r| r.get(0))?.collect::, _>>()?; + Ok(ids) +} + +pub fn delete_spot(conn: &mut Connection, id: i64) -> Res<()> { + let tx = conn.transaction()?; + let exists: bool = tx.query_row("SELECT COUNT(*) FROM range_spots WHERE id = ?1", [id], |r| r.get::<_, i64>(0))? > 0; + if !exists { + return Err(RangeError::NotFound); + } + let scenarios = scenario_ids_of(&tx, id)?; + purge_scenarios(&tx, &scenarios)?; + tx.execute("DELETE FROM range_program_spots WHERE spot_id = ?1", [id])?; + tx.execute("DELETE FROM range_spots WHERE id = ?1", [id])?; + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + Ok(()) +} + +/// Copies a spot with every depth to the other opponent kind (a situation exists once per +/// opponent kind), or to `opponent` when given. Returns the new spot id. +pub fn duplicate_spot(conn: &mut Connection, id: i64, opponent: Option<&str>) -> Res { + let spot = spot_row(conn, id)?.ok_or(RangeError::NotFound)?; + let target = match opponent { + Some(o) if OPPONENTS.contains(&o) => o.to_string(), + Some(o) => return invalid(format!("unknown opponent: {o}")), + None => if spot.opponent == "reg" { "any" } else { "reg" }.to_string(), + }; + let depths: Vec = { + let mut stmt = conn.prepare("SELECT stack_bb FROM range_scenarios WHERE spot_id = ?1 ORDER BY stack_bb DESC")?; + let rows = stmt.query_map([id], |r| r.get(0))?.collect::, _>>()?; + rows + }; + let input = SpotInput { + id: None, + name: default_name(&spot.format, &spot.hero_position, &spot.line.to_lowercase(), &target), + format: spot.format, + hero_position: spot.hero_position, + line: spot.line, + line_sizes: spot.line_sizes.and_then(|s| serde_json::from_str(&s).ok()), + opponent: target, + study_only: spot.study_only, + depths, + start: StartPoint { kind: "spot".into(), spot_id: Some(id), stack_bb: None }, + }; + save_spot(conn, &input) +} + +struct SpotRow { + format: String, + hero_position: String, + line: String, + line_sizes: Option, + opponent: String, + study_only: bool, +} + +fn spot_row(conn: &Connection, id: i64) -> Res> { + Ok(conn + .query_row("SELECT format, hero_position, line, line_sizes, opponent, study_only FROM range_spots WHERE id = ?1", [id], |r| { + Ok(SpotRow { + format: r.get(0)?, + hero_position: r.get(1)?, + line: r.get(2)?, + line_sizes: r.get(3)?, + opponent: r.get(4)?, + study_only: r.get::<_, i64>(5)? != 0, + }) + }) + .optional()?) +} + +/// Adds a depth to a spot. +pub fn add_depth(conn: &mut Connection, spot_id: i64, stack: f64, start: &StartPoint) -> Res { + let tx = conn.transaction()?; + if spot_row(&tx, spot_id)?.is_none() { + return Err(RangeError::NotFound); + } + let id = insert_scenario(&tx, spot_id, stack, start, spot_id)?; + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + Ok(id) +} + +/// Removes one depth; the last depth of a spot goes with the spot (`delete_spot`). +pub fn remove_depth(conn: &mut Connection, scenario_id: i64) -> Res<()> { + let tx = conn.transaction()?; + let spot: Option = tx.query_row("SELECT spot_id FROM range_scenarios WHERE id = ?1", [scenario_id], |r| r.get(0)).optional()?; + let Some(spot) = spot else { return Err(RangeError::NotFound) }; + let siblings: i64 = tx.query_row("SELECT COUNT(*) FROM range_scenarios WHERE spot_id = ?1", [spot], |r| r.get(0))?; + if siblings <= 1 { + return invalid("a scenario keeps at least one depth: delete the scenario instead"); + } + purge_scenarios(&tx, &[scenario_id])?; + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + Ok(()) +} + +/// One range with its stored hands (hand -> action id). +pub fn scenario(conn: &Connection, id: i64) -> Res { + let head: Option<(i64, f64)> = conn.query_row("SELECT spot_id, stack_bb FROM range_scenarios WHERE id = ?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).optional()?; + let Some((spot_id, stack)) = head else { return Err(RangeError::NotFound) }; + let mut hands = BTreeMap::new(); + let mut stmt = conn.prepare("SELECT hand, action_id FROM range_hands WHERE scenario_id = ?1")?; + for row in stmt.query_map([id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + let (hand, action) = row?; + hands.insert(hand, action); + } + Ok(json!({ "id": id, "spotId": spot_id, "stackBb": stack, "hands": hands })) +} + +/// Stores painted hands (hand -> action id); the other hands keep their action. +pub fn save_hands(conn: &mut Connection, scenario_id: i64, hands: &BTreeMap) -> Res<()> { + for hand in hands.keys() { + if !is_hand_class(hand) { + return invalid(format!("unknown hand: {hand}")); + } + } + let tx = conn.transaction()?; + let exists: bool = tx.query_row("SELECT COUNT(*) FROM range_scenarios WHERE id = ?1", [scenario_id], |r| r.get::<_, i64>(0))? > 0; + if !exists { + return Err(RangeError::NotFound); + } + let known: HashSet = { + let mut stmt = tx.prepare("SELECT id FROM range_actions")?; + let ids = stmt.query_map([], |r| r.get(0))?.collect::, _>>()?; + ids + }; + for (hand, action) in hands { + if !known.contains(action) { + return invalid(format!("unknown action for {hand}")); + } + tx.execute( + "INSERT INTO range_hands (scenario_id, hand, action_id, weight) VALUES (?1, ?2, ?3, 1.0) + ON CONFLICT(scenario_id, hand) DO UPDATE SET action_id = excluded.action_id", + params![scenario_id, hand, action], + )?; + } + tx.execute("UPDATE range_scenarios SET updated_at = ?1 WHERE id = ?2", params![now(), scenario_id])?; + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + Ok(()) +} + +/// Every spot with its depths, and the programs. +pub fn tree(conn: &Connection) -> Res { + let mut depths: HashMap> = HashMap::new(); + { + let mut stmt = conn.prepare("SELECT id, spot_id, stack_bb FROM range_scenarios ORDER BY stack_bb DESC")?; + for row in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?, r.get::<_, f64>(2)?)))? { + let (id, spot, stack) = row?; + depths.entry(spot).or_default().push(json!({ "id": id, "stackBb": stack })); + } + } + let mut stmt = conn.prepare("SELECT id, name, format, hero_position, line, line_sizes, opponent, study_only FROM range_spots ORDER BY id")?; + let spots = stmt + .query_map([], |r| { + let id: i64 = r.get(0)?; + let sizes: Option = r.get(5)?; + Ok((id, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?, r.get::<_, String>(4)?, sizes, r.get::<_, String>(6)?, r.get::<_, i64>(7)? != 0)) + })? + .collect::, _>>()?; + let spots: Vec = spots + .into_iter() + .map(|(id, name, format, hero, line, sizes, opponent, study)| { + json!({ + "id": id, "name": name, "format": format, "heroPosition": hero, "line": line, + "lineSizes": sizes.and_then(|s| serde_json::from_str::(&s).ok()), "opponent": opponent, "studyOnly": study, + "scenarios": depths.remove(&id).unwrap_or_default(), + }) + }) + .collect(); + Ok(json!({ "spots": spots, "programs": programs(conn)? })) +} + +// --------------------------------------------------------------------------------------------- +// Programs +// --------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ProgramInput { + pub id: Option, + pub name: String, + pub spot_ids: Vec, +} + +pub fn programs(conn: &Connection) -> Res { + let mut members: HashMap> = HashMap::new(); + { + let mut stmt = conn.prepare("SELECT program_id, spot_id FROM range_program_spots ORDER BY sort_order, spot_id")?; + for row in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)))? { + let (program, spot) = row?; + members.entry(program).or_default().push(spot); + } + } + let mut stmt = conn.prepare("SELECT id, name, sort_order FROM range_programs ORDER BY sort_order, id")?; + let rows = stmt + .query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))? + .collect::, _>>()?; + Ok(Value::Array( + rows.into_iter().map(|(id, name, order)| json!({ "id": id, "name": name, "sortOrder": order, "spotIds": members.remove(&id).unwrap_or_default() })).collect(), + )) +} + +/// Creates or renames a program and sets its scenarios, in the given order. Returns its id. +pub fn save_program(conn: &mut Connection, input: &ProgramInput) -> Res { + let name = input.name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME_CHARS { + return invalid(format!("a program name has 1 to {MAX_NAME_CHARS} characters")); + } + let tx = conn.transaction()?; + let clash: Option = tx.query_row("SELECT id FROM range_programs WHERE name = ?1 AND id IS NOT ?2", params![name, input.id], |r| r.get(0)).optional()?; + if clash.is_some() { + return Err(RangeError::Conflict { message: format!("a program named {name} already exists"), existing_id: None }); + } + let id = match input.id { + Some(id) => { + if tx.execute("UPDATE range_programs SET name = ?1 WHERE id = ?2", params![name, id])? == 0 { + return Err(RangeError::NotFound); + } + id + } + None => { + let next: i64 = tx.query_row("SELECT COALESCE(MAX(sort_order), -1) + 1 FROM range_programs", [], |r| r.get(0))?; + tx.execute("INSERT INTO range_programs (name, sort_order) VALUES (?1, ?2)", params![name, next])?; + tx.last_insert_rowid() + } + }; + tx.execute("DELETE FROM range_program_spots WHERE program_id = ?1", [id])?; + let mut seen = HashSet::new(); + for (order, spot) in input.spot_ids.iter().filter(|s| seen.insert(**s)).enumerate() { + let exists: bool = tx.query_row("SELECT COUNT(*) FROM range_spots WHERE id = ?1", [spot], |r| r.get::<_, i64>(0))? > 0; + if !exists { + return invalid(format!("unknown scenario: {spot}")); + } + tx.execute("INSERT INTO range_program_spots (program_id, spot_id, sort_order) VALUES (?1, ?2, ?3)", params![id, spot, order as i64])?; + } + tx.commit()?; + Ok(id) +} + +pub fn delete_program(conn: &mut Connection, id: i64) -> Res<()> { + let tx = conn.transaction()?; + tx.execute("DELETE FROM range_program_spots WHERE program_id = ?1", [id])?; + if tx.execute("DELETE FROM range_programs WHERE id = ?1", [id])? == 0 { + return Err(RangeError::NotFound); + } + tx.commit()?; + Ok(()) +} + +// --------------------------------------------------------------------------------------------- +// Settings +// --------------------------------------------------------------------------------------------- + +/// A raw setting, or its default when the row is missing. +pub fn setting(conn: &Connection, key: &str) -> Res> { + Ok(conn.query_row("SELECT value FROM range_settings WHERE key = ?1", [key], |r| r.get(0)).optional()?) +} + +pub fn settings(conn: &Connection) -> Res { + let stacks: Value = setting(conn, "default_stacks")?.and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_else(|| json!([25, 20, 15, 10, 7])); + let rule = setting(conn, "depth_rule")?.unwrap_or_else(|| "nearest".into()); + let cards: i64 = setting(conn, "new_cards_per_day")?.and_then(|s| s.parse().ok()).unwrap_or(20); + let borderline = setting(conn, "prioritize_borderline")?.map_or(true, |s| s == "1"); + Ok(json!({ "defaultStacks": stacks, "depthRule": rule, "newCardsPerDay": cards, "prioritizeBorderline": borderline })) +} + +fn put_setting(tx: &Transaction, key: &str, value: &str) -> Res<()> { + tx.execute("INSERT INTO range_settings (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", params![key, value])?; + Ok(()) +} + +/// Updates the settings present in `patch` (camelCase keys) and returns all of them. +pub fn update_settings(conn: &mut Connection, patch: &Value) -> Res { + let tx = conn.transaction()?; + if let Some(stacks) = patch.get("defaultStacks") { + let mut list: Vec = match stacks.as_array() { + Some(items) => items.iter().filter_map(Value::as_f64).collect(), + None => return invalid("defaultStacks must be a list of numbers"), + }; + if list.len() > MAX_DEFAULT_STACKS { + return invalid(format!("at most {MAX_DEFAULT_STACKS} default depths")); + } + for stack in &list { + validate_depth(*stack)?; + } + list.sort_by(|a, b| b.total_cmp(a)); + list.dedup(); + put_setting(&tx, "default_stacks", &serde_json::to_string(&list)?)?; + } + if let Some(rule) = patch.get("depthRule") { + match rule.as_str() { + Some(r @ ("nearest" | "below")) => put_setting(&tx, "depth_rule", r)?, + _ => return invalid("depthRule is nearest or below"), + } + } + if let Some(cards) = patch.get("newCardsPerDay") { + match cards.as_i64() { + Some(n) if (0..=MAX_NEW_CARDS_PER_DAY).contains(&n) => put_setting(&tx, "new_cards_per_day", &n.to_string())?, + _ => return invalid(format!("newCardsPerDay is between 0 and {MAX_NEW_CARDS_PER_DAY}")), + } + } + if let Some(flag) = patch.get("prioritizeBorderline") { + match flag.as_bool() { + Some(b) => put_setting(&tx, "prioritize_borderline", if b { "1" } else { "0" })?, + None => return invalid("prioritizeBorderline is a boolean"), + } + } + crate::services::range_adherence::invalidate(&tx)?; + tx.commit()?; + settings(conn) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::migrations; + + fn db() -> Connection { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn + } + + fn spot(line: &str, hero: &str, opponent: &str, depths: &[f64]) -> SpotInput { + SpotInput { + format: "3max".into(), + hero_position: hero.into(), + line: line.into(), + opponent: opponent.into(), + depths: depths.to_vec(), + start: StartPoint { kind: "empty".into(), ..Default::default() }, + ..Default::default() + } + } + + fn count(conn: &Connection, table: &str) -> i64 { + conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0)).unwrap() + } + + #[test] + fn a_new_database_holds_the_base_actions_and_no_scenario() { + let conn = db(); + assert_eq!(count(&conn, "range_actions"), 6); + assert_eq!(count(&conn, "range_spots"), 0); + assert_eq!(settings(&conn).unwrap()["defaultStacks"], json!([25, 20, 15, 10, 7])); + } + + #[test] + fn creating_a_spot_fills_every_depth_with_the_first_action() { + let mut conn = db(); + let id = save_spot(&mut conn, &spot("BTN:fold,SB:call", "BB", "reg", &[20.0, 10.0])).unwrap(); + assert_eq!(count(&conn, "range_scenarios"), 2); + assert_eq!(count(&conn, "range_hands"), 2 * 169); + let name: String = conn.query_row("SELECT name FROM range_spots WHERE id = ?1", [id], |r| r.get(0)).unwrap(); + assert_eq!(name, "BB vs SB limp · Reg"); + let fold: i64 = conn.query_row("SELECT id FROM range_actions WHERE label = 'Fold'", [], |r| r.get(0)).unwrap(); + assert_eq!(conn.query_row("SELECT COUNT(*) FROM range_hands WHERE action_id = ?1", [fold], |r| r.get::<_, i64>(0)).unwrap(), 2 * 169); + } + + #[test] + fn a_situation_exists_once_per_opponent_kind() { + let mut conn = db(); + let first = save_spot(&mut conn, &spot("", "BTN", "any", &[15.0])).unwrap(); + match save_spot(&mut conn, &spot("", "BTN", "any", &[10.0])) { + Err(RangeError::Conflict { existing_id, .. }) => assert_eq!(existing_id, Some(first)), + other => panic!("expected a conflict, got {other:?}"), + } + save_spot(&mut conn, &spot("", "BTN", "reg", &[15.0])).expect("the reg variant coexists"); + } + + #[test] + fn the_line_must_match_the_seats_before_the_hero() { + let mut conn = db(); + assert!(matches!(save_spot(&mut conn, &spot("BTN:fold", "BB", "any", &[10.0])), Err(RangeError::Invalid(_)))); + assert!(matches!(save_spot(&mut conn, &spot("SB:fold,BTN:fold", "BB", "any", &[10.0])), Err(RangeError::Invalid(_)))); + assert!(matches!(save_spot(&mut conn, &spot("", "BTN", "any", &[])), Err(RangeError::Invalid(_)))); + let mut hu = spot("SB:call", "BB", "any", &[10.0]); + hu.format = "hu".into(); + save_spot(&mut conn, &hu).expect("heads-up line"); + } + + #[test] + fn deleting_a_spot_removes_its_ranges_hands_and_program_links() { + let mut conn = db(); + let id = save_spot(&mut conn, &spot("", "BTN", "any", &[15.0, 10.0])).unwrap(); + let other = save_spot(&mut conn, &spot("", "BTN", "reg", &[15.0])).unwrap(); + save_program(&mut conn, &ProgramInput { name: "Week 1".into(), spot_ids: vec![id, other], ..Default::default() }).unwrap(); + delete_spot(&mut conn, id).unwrap(); + assert_eq!(count(&conn, "range_spots"), 1); + assert_eq!(count(&conn, "range_scenarios"), 1); + assert_eq!(count(&conn, "range_hands"), 169); + assert_eq!(count(&conn, "range_program_spots"), 1); + assert!(matches!(delete_spot(&mut conn, id), Err(RangeError::NotFound))); + } + + #[test] + fn an_action_in_use_needs_a_replacement() { + let mut conn = db(); + save_spot(&mut conn, &spot("", "BTN", "any", &[15.0])).unwrap(); + let ids: Vec = conn.prepare("SELECT id FROM range_actions ORDER BY sort_order").unwrap().query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect(); + let (fold, call) = (ids[0], ids[2]); + assert!(matches!(delete_action(&mut conn, fold, None), Err(RangeError::Invalid(_)))); + assert!(matches!(delete_action(&mut conn, fold, Some(fold)), Err(RangeError::Invalid(_)))); + delete_action(&mut conn, fold, Some(call)).unwrap(); + assert_eq!(conn.query_row("SELECT COUNT(*) FROM range_hands WHERE action_id = ?1", [call], |r| r.get::<_, i64>(0)).unwrap(), 169); + delete_action(&mut conn, ids[5], None).expect("an unused action goes without a replacement"); + } + + #[test] + fn painting_a_range_keeps_the_other_hands() { + let mut conn = db(); + save_spot(&mut conn, &spot("", "BTN", "any", &[15.0])).unwrap(); + let scenario_id: i64 = conn.query_row("SELECT id FROM range_scenarios", [], |r| r.get(0)).unwrap(); + let raise: i64 = conn.query_row("SELECT id FROM range_actions WHERE label = 'Raise'", [], |r| r.get(0)).unwrap(); + save_hands(&mut conn, scenario_id, &BTreeMap::from([("AKs".to_string(), raise)])).unwrap(); + let range = scenario(&conn, scenario_id).unwrap(); + assert_eq!(range["hands"]["AKs"], raise); + assert_eq!(range["hands"].as_object().unwrap().len(), 169); + assert!(matches!(save_hands(&mut conn, scenario_id, &BTreeMap::from([("KAs".to_string(), raise)])), Err(RangeError::Invalid(_)))); + assert!(matches!(save_hands(&mut conn, scenario_id, &BTreeMap::from([("AKs".to_string(), 999)])), Err(RangeError::Invalid(_)))); + } + + #[test] + fn a_new_depth_can_copy_another_depth_of_the_spot() { + let mut conn = db(); + let spot_id = save_spot(&mut conn, &spot("", "BTN", "any", &[15.0])).unwrap(); + let first: i64 = conn.query_row("SELECT id FROM range_scenarios", [], |r| r.get(0)).unwrap(); + let raise: i64 = conn.query_row("SELECT id FROM range_actions WHERE label = 'Raise'", [], |r| r.get(0)).unwrap(); + save_hands(&mut conn, first, &BTreeMap::from([("72o".to_string(), raise)])).unwrap(); + let second = add_depth(&mut conn, spot_id, 12.5, &StartPoint { kind: "depth".into(), stack_bb: Some(15.0), ..Default::default() }).unwrap(); + assert_eq!(scenario(&conn, second).unwrap()["hands"]["72o"], raise); + assert!(matches!(add_depth(&mut conn, spot_id, 15.0, &StartPoint::default()), Err(RangeError::Conflict { .. }))); + remove_depth(&mut conn, second).unwrap(); + assert!(matches!(remove_depth(&mut conn, first), Err(RangeError::Invalid(_))), "the last depth stays"); + } + + #[test] + fn duplicating_a_spot_creates_the_other_opponent_variant() { + let mut conn = db(); + let id = save_spot(&mut conn, &spot("BTN:fold,SB:call", "BB", "any", &[20.0, 10.0])).unwrap(); + let copy = duplicate_spot(&mut conn, id, None).unwrap(); + let (opponent, name): (String, String) = conn.query_row("SELECT opponent, name FROM range_spots WHERE id = ?1", [copy], |r| Ok((r.get(0)?, r.get(1)?))).unwrap(); + assert_eq!((opponent.as_str(), name.as_str()), ("reg", "BB vs SB limp · Reg")); + assert_eq!(count(&conn, "range_scenarios"), 4); + assert!(matches!(duplicate_spot(&mut conn, id, None), Err(RangeError::Conflict { .. }))); + } + + #[test] + fn settings_are_validated_and_stored() { + let mut conn = db(); + let updated = update_settings(&mut conn, &json!({ "defaultStacks": [10, 25, 15, 25], "depthRule": "below", "newCardsPerDay": 30, "prioritizeBorderline": false })).unwrap(); + assert_eq!(updated["defaultStacks"], json!([25.0, 15.0, 10.0])); + assert_eq!(updated["depthRule"], "below"); + assert!(matches!(update_settings(&mut conn, &json!({ "depthRule": "closest" })), Err(RangeError::Invalid(_)))); + assert!(matches!(update_settings(&mut conn, &json!({ "newCardsPerDay": -1 })), Err(RangeError::Invalid(_)))); + } + + #[test] + fn actions_are_validated_and_labels_stay_unique() { + let mut conn = db(); + let action = |label: &str| ActionInput { + id: None, + label: label.into(), + color: "#a07cf0".into(), + immediate: "iso".into(), + size_value: Some(3.0), + size_unit: Some("x".into()), + response: "fold".into(), + }; + save_actions(&mut conn, &[action("Iso 3x")]).unwrap(); + assert!(matches!(save_actions(&mut conn, &[action("Iso 3x")]), Err(RangeError::Conflict { .. }))); + assert!(matches!(save_actions(&mut conn, &[ActionInput { color: "purple".into(), ..action("Bad") }]), Err(RangeError::Invalid(_)))); + assert!(matches!(save_actions(&mut conn, &[ActionInput { size_unit: None, ..action("Bad size") }]), Err(RangeError::Invalid(_)))); + assert_eq!(count(&conn, "range_actions"), 7); + } +} diff --git a/crates/core/tests/fixtures/ranges_v1.json b/crates/core/tests/fixtures/ranges_v1.json new file mode 100644 index 00000000..7728a422 --- /dev/null +++ b/crates/core/tests/fixtures/ranges_v1.json @@ -0,0 +1,780 @@ +{ + "format": "spintracker-ranges", + "version": 1, + "actions": [ + { + "label": "Fold", + "color": "#2a2f39", + "immediate": "fold", + "sizeValue": null, + "sizeUnit": null, + "response": "none" + }, + { + "label": "Call", + "color": "#4caf50", + "immediate": "call", + "sizeValue": null, + "sizeUnit": null, + "response": "none" + }, + { + "label": "OPEN/FOLD", + "color": "#5b8def", + "immediate": "raise", + "sizeValue": 2, + "sizeUnit": "bb", + "response": "fold" + }, + { + "label": "Shove", + "color": "#ff6b5b", + "immediate": "allin", + "sizeValue": null, + "sizeUnit": null, + "response": "none" + } + ], + "spots": [ + { + "name": "BTN first in", + "format": "3max", + "heroPosition": "BTN", + "line": "", + "lineSizes": null, + "opponent": "any", + "studyOnly": false, + "scenarios": [ + { + "stackBb": 15, + "hands": { + "22": "Fold", + "33": "Fold", + "44": "Fold", + "55": "Fold", + "66": "Fold", + "77": "OPEN/FOLD", + "88": "OPEN/FOLD", + "99": "OPEN/FOLD", + "AA": "OPEN/FOLD", + "AKs": "OPEN/FOLD", + "AQs": "OPEN/FOLD", + "AJs": "OPEN/FOLD", + "ATs": "OPEN/FOLD", + "A9s": "OPEN/FOLD", + "A8s": "OPEN/FOLD", + "A7s": "OPEN/FOLD", + "A6s": "OPEN/FOLD", + "A5s": "OPEN/FOLD", + "A4s": "OPEN/FOLD", + "A3s": "OPEN/FOLD", + "A2s": "OPEN/FOLD", + "AKo": "OPEN/FOLD", + "KK": "OPEN/FOLD", + "KQs": "OPEN/FOLD", + "KJs": "OPEN/FOLD", + "KTs": "OPEN/FOLD", + "K9s": "OPEN/FOLD", + "K8s": "OPEN/FOLD", + "K7s": "OPEN/FOLD", + "K6s": "OPEN/FOLD", + "K5s": "OPEN/FOLD", + "K4s": "OPEN/FOLD", + "K3s": "OPEN/FOLD", + "K2s": "OPEN/FOLD", + "AQo": "OPEN/FOLD", + "KQo": "Fold", + "QQ": "OPEN/FOLD", + "QJs": "OPEN/FOLD", + "QTs": "OPEN/FOLD", + "Q9s": "OPEN/FOLD", + "Q8s": "OPEN/FOLD", + "Q7s": "OPEN/FOLD", + "Q6s": "OPEN/FOLD", + "Q5s": "OPEN/FOLD", + "Q4s": "OPEN/FOLD", + "Q3s": "OPEN/FOLD", + "Q2s": "OPEN/FOLD", + "AJo": "OPEN/FOLD", + "KJo": "Fold", + "QJo": "Fold", + "JJ": "OPEN/FOLD", + "JTs": "OPEN/FOLD", + "J9s": "OPEN/FOLD", + "J8s": "OPEN/FOLD", + "J7s": "OPEN/FOLD", + "J6s": "OPEN/FOLD", + "J5s": "OPEN/FOLD", + "J4s": "OPEN/FOLD", + "J3s": "OPEN/FOLD", + "J2s": "OPEN/FOLD", + "ATo": "OPEN/FOLD", + "KTo": "Fold", + "QTo": "Fold", + "JTo": "Fold", + "TT": "OPEN/FOLD", + "T9s": "OPEN/FOLD", + "T8s": "OPEN/FOLD", + "T7s": "OPEN/FOLD", + "T6s": "OPEN/FOLD", + "T5s": "OPEN/FOLD", + "T4s": "OPEN/FOLD", + "T3s": "OPEN/FOLD", + "T2s": "OPEN/FOLD", + "A9o": "OPEN/FOLD", + "K9o": "Fold", + "Q9o": "Fold", + "J9o": "Fold", + "T9o": "Fold", + "98s": "OPEN/FOLD", + "97s": "OPEN/FOLD", + "96s": "OPEN/FOLD", + "95s": "OPEN/FOLD", + "94s": "OPEN/FOLD", + "93s": "OPEN/FOLD", + "92s": "OPEN/FOLD", + "A8o": "OPEN/FOLD", + "K8o": "Fold", + "Q8o": "Fold", + "J8o": "Fold", + "T8o": "Fold", + "98o": "Fold", + "87s": "Fold", + "86s": "Fold", + "85s": "Fold", + "84s": "Fold", + "83s": "Fold", + "82s": "Fold", + "A7o": "OPEN/FOLD", + "K7o": "Fold", + "Q7o": "Fold", + "J7o": "Fold", + "T7o": "Fold", + "97o": "Fold", + "87o": "Fold", + "76s": "Fold", + "75s": "Fold", + "74s": "Fold", + "73s": "Fold", + "72s": "Fold", + "A6o": "OPEN/FOLD", + "K6o": "Fold", + "Q6o": "Fold", + "J6o": "Fold", + "T6o": "Fold", + "96o": "Fold", + "86o": "Fold", + "76o": "Fold", + "65s": "Fold", + "64s": "Fold", + "63s": "Fold", + "62s": "Fold", + "A5o": "OPEN/FOLD", + "K5o": "Fold", + "Q5o": "Fold", + "J5o": "Fold", + "T5o": "Fold", + "95o": "Fold", + "85o": "Fold", + "75o": "Fold", + "65o": "Fold", + "54s": "Fold", + "53s": "Fold", + "52s": "Fold", + "A4o": "OPEN/FOLD", + "K4o": "Fold", + "Q4o": "Fold", + "J4o": "Fold", + "T4o": "Fold", + "94o": "Fold", + "84o": "Fold", + "74o": "Fold", + "64o": "Fold", + "54o": "Fold", + "43s": "Fold", + "42s": "Fold", + "A3o": "OPEN/FOLD", + "K3o": "Fold", + "Q3o": "Fold", + "J3o": "Fold", + "T3o": "Fold", + "93o": "Fold", + "83o": "Fold", + "73o": "Fold", + "63o": "Fold", + "53o": "Fold", + "43o": "Fold", + "32s": "Fold", + "A2o": "OPEN/FOLD", + "K2o": "Fold", + "Q2o": "Fold", + "J2o": "Fold", + "T2o": "Fold", + "92o": "Fold", + "82o": "Fold", + "72o": "Fold", + "62o": "Fold", + "52o": "Fold", + "42o": "Fold", + "32o": "Fold" + } + }, + { + "stackBb": 10, + "hands": { + "22": "Shove", + "33": "Shove", + "44": "Shove", + "55": "Shove", + "66": "Shove", + "77": "OPEN/FOLD", + "88": "OPEN/FOLD", + "99": "OPEN/FOLD", + "AA": "OPEN/FOLD", + "AKs": "OPEN/FOLD", + "AQs": "OPEN/FOLD", + "AJs": "OPEN/FOLD", + "ATs": "OPEN/FOLD", + "A9s": "OPEN/FOLD", + "A8s": "OPEN/FOLD", + "A7s": "OPEN/FOLD", + "A6s": "OPEN/FOLD", + "A5s": "OPEN/FOLD", + "A4s": "OPEN/FOLD", + "A3s": "OPEN/FOLD", + "A2s": "OPEN/FOLD", + "AKo": "OPEN/FOLD", + "KK": "OPEN/FOLD", + "KQs": "OPEN/FOLD", + "KJs": "OPEN/FOLD", + "KTs": "OPEN/FOLD", + "K9s": "OPEN/FOLD", + "K8s": "OPEN/FOLD", + "K7s": "OPEN/FOLD", + "K6s": "OPEN/FOLD", + "K5s": "OPEN/FOLD", + "K4s": "OPEN/FOLD", + "K3s": "OPEN/FOLD", + "K2s": "OPEN/FOLD", + "AQo": "OPEN/FOLD", + "KQo": "Fold", + "QQ": "OPEN/FOLD", + "QJs": "OPEN/FOLD", + "QTs": "OPEN/FOLD", + "Q9s": "OPEN/FOLD", + "Q8s": "OPEN/FOLD", + "Q7s": "OPEN/FOLD", + "Q6s": "OPEN/FOLD", + "Q5s": "OPEN/FOLD", + "Q4s": "OPEN/FOLD", + "Q3s": "OPEN/FOLD", + "Q2s": "OPEN/FOLD", + "AJo": "OPEN/FOLD", + "KJo": "Fold", + "QJo": "Fold", + "JJ": "OPEN/FOLD", + "JTs": "OPEN/FOLD", + "J9s": "OPEN/FOLD", + "J8s": "OPEN/FOLD", + "J7s": "OPEN/FOLD", + "J6s": "OPEN/FOLD", + "J5s": "OPEN/FOLD", + "J4s": "OPEN/FOLD", + "J3s": "OPEN/FOLD", + "J2s": "OPEN/FOLD", + "ATo": "OPEN/FOLD", + "KTo": "Fold", + "QTo": "Fold", + "JTo": "Fold", + "TT": "OPEN/FOLD", + "T9s": "OPEN/FOLD", + "T8s": "OPEN/FOLD", + "T7s": "OPEN/FOLD", + "T6s": "OPEN/FOLD", + "T5s": "OPEN/FOLD", + "T4s": "OPEN/FOLD", + "T3s": "OPEN/FOLD", + "T2s": "OPEN/FOLD", + "A9o": "OPEN/FOLD", + "K9o": "Fold", + "Q9o": "Fold", + "J9o": "Fold", + "T9o": "Fold", + "98s": "OPEN/FOLD", + "97s": "OPEN/FOLD", + "96s": "OPEN/FOLD", + "95s": "OPEN/FOLD", + "94s": "OPEN/FOLD", + "93s": "OPEN/FOLD", + "92s": "OPEN/FOLD", + "A8o": "OPEN/FOLD", + "K8o": "Fold", + "Q8o": "Fold", + "J8o": "Fold", + "T8o": "Fold", + "98o": "Fold", + "87s": "Fold", + "86s": "Fold", + "85s": "Fold", + "84s": "Fold", + "83s": "Fold", + "82s": "Fold", + "A7o": "OPEN/FOLD", + "K7o": "Fold", + "Q7o": "Fold", + "J7o": "Fold", + "T7o": "Fold", + "97o": "Fold", + "87o": "Fold", + "76s": "Fold", + "75s": "Fold", + "74s": "Fold", + "73s": "Fold", + "72s": "Fold", + "A6o": "OPEN/FOLD", + "K6o": "Fold", + "Q6o": "Fold", + "J6o": "Fold", + "T6o": "Fold", + "96o": "Fold", + "86o": "Fold", + "76o": "Fold", + "65s": "Fold", + "64s": "Fold", + "63s": "Fold", + "62s": "Fold", + "A5o": "OPEN/FOLD", + "K5o": "Fold", + "Q5o": "Fold", + "J5o": "Fold", + "T5o": "Fold", + "95o": "Fold", + "85o": "Fold", + "75o": "Fold", + "65o": "Fold", + "54s": "Fold", + "53s": "Fold", + "52s": "Fold", + "A4o": "OPEN/FOLD", + "K4o": "Fold", + "Q4o": "Fold", + "J4o": "Fold", + "T4o": "Fold", + "94o": "Fold", + "84o": "Fold", + "74o": "Fold", + "64o": "Fold", + "54o": "Fold", + "43s": "Fold", + "42s": "Fold", + "A3o": "OPEN/FOLD", + "K3o": "Fold", + "Q3o": "Fold", + "J3o": "Fold", + "T3o": "Fold", + "93o": "Fold", + "83o": "Fold", + "73o": "Fold", + "63o": "Fold", + "53o": "Fold", + "43o": "Fold", + "32s": "Fold", + "A2o": "OPEN/FOLD", + "K2o": "Fold", + "Q2o": "Fold", + "J2o": "Fold", + "T2o": "Fold", + "92o": "Fold", + "82o": "Fold", + "72o": "Fold", + "62o": "Fold", + "52o": "Fold", + "42o": "Fold", + "32o": "Fold" + } + } + ] + }, + { + "name": "BB vs SB limp · Reg", + "format": "3max", + "heroPosition": "BB", + "line": "btn:fold,sb:call", + "lineSizes": null, + "opponent": "reg", + "studyOnly": false, + "scenarios": [ + { + "stackBb": 20, + "hands": { + "22": "Shove", + "33": "Shove", + "44": "Shove", + "55": "Shove", + "66": "Shove", + "77": "Shove", + "88": "Shove", + "99": "Shove", + "AA": "Shove", + "AKs": "Call", + "AQs": "Call", + "AJs": "Call", + "ATs": "Call", + "A9s": "Call", + "A8s": "Call", + "A7s": "Call", + "A6s": "Call", + "A5s": "Call", + "A4s": "Call", + "A3s": "Call", + "A2s": "Call", + "AKo": "Fold", + "KK": "Shove", + "KQs": "Call", + "KJs": "Call", + "KTs": "Call", + "K9s": "Call", + "K8s": "Call", + "K7s": "Call", + "K6s": "Call", + "K5s": "Call", + "K4s": "Call", + "K3s": "Call", + "K2s": "Call", + "AQo": "Fold", + "KQo": "Fold", + "QQ": "Shove", + "QJs": "Call", + "QTs": "Call", + "Q9s": "Call", + "Q8s": "Call", + "Q7s": "Call", + "Q6s": "Call", + "Q5s": "Call", + "Q4s": "Call", + "Q3s": "Call", + "Q2s": "Call", + "AJo": "Fold", + "KJo": "Fold", + "QJo": "Fold", + "JJ": "Shove", + "JTs": "Call", + "J9s": "Call", + "J8s": "Call", + "J7s": "Call", + "J6s": "Call", + "J5s": "Call", + "J4s": "Call", + "J3s": "Call", + "J2s": "Call", + "ATo": "Fold", + "KTo": "Fold", + "QTo": "Fold", + "JTo": "Fold", + "TT": "Shove", + "T9s": "Call", + "T8s": "Call", + "T7s": "Call", + "T6s": "Call", + "T5s": "Call", + "T4s": "Call", + "T3s": "Call", + "T2s": "Call", + "A9o": "Fold", + "K9o": "Fold", + "Q9o": "Fold", + "J9o": "Fold", + "T9o": "Fold", + "98s": "Call", + "97s": "Call", + "96s": "Call", + "95s": "Call", + "94s": "Call", + "93s": "Call", + "92s": "Call", + "A8o": "Fold", + "K8o": "Fold", + "Q8o": "Fold", + "J8o": "Fold", + "T8o": "Fold", + "98o": "Fold", + "87s": "Call", + "86s": "Call", + "85s": "Call", + "84s": "Call", + "83s": "Call", + "82s": "Call", + "A7o": "Fold", + "K7o": "Fold", + "Q7o": "Fold", + "J7o": "Fold", + "T7o": "Fold", + "97o": "Fold", + "87o": "Fold", + "76s": "Call", + "75s": "Call", + "74s": "Call", + "73s": "Call", + "72s": "Call", + "A6o": "Fold", + "K6o": "Fold", + "Q6o": "Fold", + "J6o": "Fold", + "T6o": "Fold", + "96o": "Fold", + "86o": "Fold", + "76o": "Fold", + "65s": "Call", + "64s": "Call", + "63s": "Call", + "62s": "Call", + "A5o": "Fold", + "K5o": "Fold", + "Q5o": "Fold", + "J5o": "Fold", + "T5o": "Fold", + "95o": "Fold", + "85o": "Fold", + "75o": "Fold", + "65o": "Fold", + "54s": "Call", + "53s": "Call", + "52s": "Call", + "A4o": "Fold", + "K4o": "Fold", + "Q4o": "Fold", + "J4o": "Fold", + "T4o": "Fold", + "94o": "Fold", + "84o": "Fold", + "74o": "Fold", + "64o": "Fold", + "54o": "Fold", + "43s": "Call", + "42s": "Call", + "A3o": "Fold", + "K3o": "Fold", + "Q3o": "Fold", + "J3o": "Fold", + "T3o": "Fold", + "93o": "Fold", + "83o": "Fold", + "73o": "Fold", + "63o": "Fold", + "53o": "Fold", + "43o": "Fold", + "32s": "Call", + "A2o": "Fold", + "K2o": "Fold", + "Q2o": "Fold", + "J2o": "Fold", + "T2o": "Fold", + "92o": "Fold", + "82o": "Fold", + "72o": "Fold", + "62o": "Fold", + "52o": "Fold", + "42o": "Fold", + "32o": "Fold" + } + } + ] + }, + { + "name": "BB (HU) vs SB open", + "format": "hu", + "heroPosition": "BB", + "line": "sb:raise", + "lineSizes": { + "SB": 2 + }, + "opponent": "any", + "studyOnly": true, + "scenarios": [ + { + "stackBb": 10, + "hands": { + "22": "Call", + "33": "Call", + "44": "Call", + "55": "Call", + "66": "Call", + "77": "Call", + "88": "Call", + "99": "Call", + "AA": "Call", + "AKs": "Call", + "AQs": "Call", + "AJs": "Call", + "ATs": "Call", + "A9s": "Call", + "A8s": "Call", + "A7s": "Call", + "A6s": "Call", + "A5s": "Call", + "A4s": "Call", + "A3s": "Call", + "A2s": "Call", + "AKo": "Call", + "KK": "Call", + "KQs": "Fold", + "KJs": "Fold", + "KTs": "Fold", + "K9s": "Fold", + "K8s": "Fold", + "K7s": "Fold", + "K6s": "Fold", + "K5s": "Fold", + "K4s": "Fold", + "K3s": "Fold", + "K2s": "Fold", + "AQo": "Call", + "KQo": "Fold", + "QQ": "Call", + "QJs": "Fold", + "QTs": "Fold", + "Q9s": "Fold", + "Q8s": "Fold", + "Q7s": "Fold", + "Q6s": "Fold", + "Q5s": "Fold", + "Q4s": "Fold", + "Q3s": "Fold", + "Q2s": "Fold", + "AJo": "Call", + "KJo": "Fold", + "QJo": "Fold", + "JJ": "Call", + "JTs": "Fold", + "J9s": "Fold", + "J8s": "Fold", + "J7s": "Fold", + "J6s": "Fold", + "J5s": "Fold", + "J4s": "Fold", + "J3s": "Fold", + "J2s": "Fold", + "ATo": "Call", + "KTo": "Fold", + "QTo": "Fold", + "JTo": "Fold", + "TT": "Call", + "T9s": "Fold", + "T8s": "Fold", + "T7s": "Fold", + "T6s": "Fold", + "T5s": "Fold", + "T4s": "Fold", + "T3s": "Fold", + "T2s": "Fold", + "A9o": "Call", + "K9o": "Fold", + "Q9o": "Fold", + "J9o": "Fold", + "T9o": "Fold", + "98s": "Fold", + "97s": "Fold", + "96s": "Fold", + "95s": "Fold", + "94s": "Fold", + "93s": "Fold", + "92s": "Fold", + "A8o": "Call", + "K8o": "Fold", + "Q8o": "Fold", + "J8o": "Fold", + "T8o": "Fold", + "98o": "Fold", + "87s": "Fold", + "86s": "Fold", + "85s": "Fold", + "84s": "Fold", + "83s": "Fold", + "82s": "Fold", + "A7o": "Call", + "K7o": "Fold", + "Q7o": "Fold", + "J7o": "Fold", + "T7o": "Fold", + "97o": "Fold", + "87o": "Fold", + "76s": "Fold", + "75s": "Fold", + "74s": "Fold", + "73s": "Fold", + "72s": "Fold", + "A6o": "Call", + "K6o": "Fold", + "Q6o": "Fold", + "J6o": "Fold", + "T6o": "Fold", + "96o": "Fold", + "86o": "Fold", + "76o": "Fold", + "65s": "Fold", + "64s": "Fold", + "63s": "Fold", + "62s": "Fold", + "A5o": "Call", + "K5o": "Fold", + "Q5o": "Fold", + "J5o": "Fold", + "T5o": "Fold", + "95o": "Fold", + "85o": "Fold", + "75o": "Fold", + "65o": "Fold", + "54s": "Fold", + "53s": "Fold", + "52s": "Fold", + "A4o": "Call", + "K4o": "Fold", + "Q4o": "Fold", + "J4o": "Fold", + "T4o": "Fold", + "94o": "Fold", + "84o": "Fold", + "74o": "Fold", + "64o": "Fold", + "54o": "Fold", + "43s": "Fold", + "42s": "Fold", + "A3o": "Call", + "K3o": "Fold", + "Q3o": "Fold", + "J3o": "Fold", + "T3o": "Fold", + "93o": "Fold", + "83o": "Fold", + "73o": "Fold", + "63o": "Fold", + "53o": "Fold", + "43o": "Fold", + "32s": "Fold", + "A2o": "Call", + "K2o": "Fold", + "Q2o": "Fold", + "J2o": "Fold", + "T2o": "Fold", + "92o": "Fold", + "82o": "Fold", + "72o": "Fold", + "62o": "Fold", + "52o": "Fold", + "42o": "Fold", + "32o": "Fold" + } + } + ] + } + ], + "programs": [ + { + "name": "Week 1", + "spots": [ + "BTN first in", + "BB vs SB limp · Reg" + ] + } + ] +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3b6793a6..014d5d0e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -18,6 +18,7 @@ const HandHistory = lazy(() => import('@/views/HandHistory')) const Analysis = lazy(() => import('@/views/Analysis')) const Players = lazy(() => import('@/views/Players')) const LiveHud = lazy(() => import('@/views/LiveHud')) +const Ranges = lazy(() => import('@/views/Ranges')) const Settings = lazy(() => import('@/views/Settings')) export default function App() { @@ -60,6 +61,7 @@ export default function App() { } /> } /> } /> + } /> } /> diff --git a/frontend/src/components/layout/TopNav.tsx b/frontend/src/components/layout/TopNav.tsx index f84548fd..67436c37 100644 --- a/frontend/src/components/layout/TopNav.tsx +++ b/frontend/src/components/layout/TopNav.tsx @@ -16,6 +16,7 @@ export default function TopNav({ children }: { children?: ReactNode }) { { name: t('navigation.analysis'), href: '/analysis' }, { name: t('navigation.players'), href: '/players' }, { name: t('navigation.hud'), href: '/hud' }, + { name: t('navigation.ranges'), href: '/ranges' }, ] return ( diff --git a/frontend/src/components/ranges/ActionChip.tsx b/frontend/src/components/ranges/ActionChip.tsx new file mode 100644 index 00000000..5d85b437 --- /dev/null +++ b/frontend/src/components/ranges/ActionChip.tsx @@ -0,0 +1,19 @@ +import clsx from 'clsx' +import { textColor, type RangeAction } from '@/utils/ranges' + +interface ActionChipProps { + action: Pick + /** Outline variant: the action that was played rather than the one in the range. */ + outline?: boolean + className?: string +} + +/** A pill in the colours of one of the player's actions. */ +export default function ActionChip({ action, outline, className }: ActionChipProps) { + const style = outline ? { borderColor: action.color, color: action.color } : { backgroundColor: action.color, borderColor: action.color, color: textColor(action.color) } + return ( + + {action.label} + + ) +} diff --git a/frontend/src/components/ranges/ActionFields.tsx b/frontend/src/components/ranges/ActionFields.tsx new file mode 100644 index 00000000..06fce091 --- /dev/null +++ b/frontend/src/components/ranges/ActionFields.tsx @@ -0,0 +1,106 @@ +import { useTranslation } from 'react-i18next' +import { IMMEDIATES, RESPONSES, SIZE_UNITS, type Immediate, type RangeAction, type Response, type SizeUnit } from '@/utils/ranges' +import ActionChip from './ActionChip' +import ColorPicker from './ColorPicker' + +/** An action being edited: the size stays text until it is saved. */ +export interface ActionDraft { + id?: number + label: string + color: string + immediate: Immediate + sizeValue: string + sizeUnit: SizeUnit + response: Response +} + +export const NEW_ACTION_COLOR = '#a07cf0' + +export function emptyDraft(): ActionDraft { + return { label: '', color: NEW_ACTION_COLOR, immediate: 'raise', sizeValue: '', sizeUnit: 'bb', response: 'none' } +} + +export function draftOf(action: RangeAction): ActionDraft { + return { + id: action.id, + label: action.label, + color: action.color, + immediate: action.immediate, + sizeValue: action.sizeValue === null ? '' : String(action.sizeValue), + sizeUnit: action.sizeUnit ?? 'bb', + response: action.response, + } +} + +/** The body the backend expects; `null` when the size is not a positive number. */ +export function draftToInput(draft: ActionDraft): Record | null { + const size = draft.sizeValue.trim() === '' ? null : Number(draft.sizeValue.replace(',', '.')) + if (size !== null && !(size > 0)) return null + return { + id: draft.id, + label: draft.label.trim(), + color: draft.color, + immediate: draft.immediate, + sizeValue: size, + sizeUnit: size === null ? null : draft.sizeUnit, + response: draft.response, + } +} + +export function isDraftValid(draft: ActionDraft): boolean { + return draft.label.trim() !== '' && draftToInput(draft) !== null +} + +interface ActionFieldsProps { + draft: ActionDraft + onChange: (draft: ActionDraft) => void +} + +/** The fields of one action: label, colour, immediate action, size and planned response. */ +export default function ActionFields({ draft, onChange }: ActionFieldsProps) { + const { t } = useTranslation() + const patch = (changes: Partial) => onChange({ ...draft, ...changes }) + return ( +
+ patch({ color })} label={t('ranges.actions.color')} /> + patch({ label: e.target.value })} + /> + + patch({ sizeValue: e.target.value })} + /> + + + +
+ ) +} diff --git a/frontend/src/components/ranges/ColorPicker.tsx b/frontend/src/components/ranges/ColorPicker.tsx new file mode 100644 index 00000000..11cd1340 --- /dev/null +++ b/frontend/src/components/ranges/ColorPicker.tsx @@ -0,0 +1,82 @@ +import { useEffect, useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' +import clsx from 'clsx' +import { COLOR_SHADES, HEX_COLOR } from '@/utils/ranges' + +interface ColorPickerProps { + value: string + onChange: (color: string) => void + /** Accessible name of the button that opens the picker. */ + label: string +} + +/** A colour swatch that opens the 16 proposed shades and a hex field. */ +export default function ColorPicker({ value, onChange, label }: ColorPickerProps) { + const { t } = useTranslation() + const [open, setOpen] = useState(false) + const [hex, setHex] = useState(value) + const root = useRef(null) + + useEffect(() => setHex(value), [value]) + + useEffect(() => { + if (!open) return undefined + const close = (e: MouseEvent) => { + if (!root.current?.contains(e.target as Node)) setOpen(false) + } + const escape = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false) + document.addEventListener('mousedown', close) + document.addEventListener('keydown', escape) + return () => { + document.removeEventListener('mousedown', close) + document.removeEventListener('keydown', escape) + } + }, [open]) + + const commit = (next: string) => { + if (HEX_COLOR.test(next)) onChange(next.toLowerCase()) + } + + return ( +
+
+ { + setHex(e.target.value) + commit(e.target.value) + }} + /> + + )} + + ) +} diff --git a/frontend/src/components/ranges/DeviationBadge.tsx b/frontend/src/components/ranges/DeviationBadge.tsx new file mode 100644 index 00000000..254e7c99 --- /dev/null +++ b/frontend/src/components/ranges/DeviationBadge.tsx @@ -0,0 +1,26 @@ +import { useTranslation } from 'react-i18next' +import ActionChip from './ActionChip' + +interface DeviationBadgeProps { + /** The action in the player's range. */ + expected: { label: string; color: string } | null + /** What was played, in the player's own actions when one fits. */ + played: { label: string; color: string } | null + /** The planned answer to a raise and the one given, when that is what differed. */ + response?: string | null +} + +/** "Your range: [action] · played: [action]": a deviation from the plan, never an error. */ +export default function DeviationBadge({ expected, played, response }: DeviationBadgeProps) { + const { t } = useTranslation() + return ( + + {t('ranges.deviation.yourRange')} + {expected && } + + {t('ranges.deviation.played')} + {played && } + {response && {t('ranges.deviation.response', { response })}} + + ) +} diff --git a/frontend/src/components/ranges/ExportRangesDialog.tsx b/frontend/src/components/ranges/ExportRangesDialog.tsx new file mode 100644 index 00000000..c645005e --- /dev/null +++ b/frontend/src/components/ranges/ExportRangesDialog.tsx @@ -0,0 +1,104 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' +import clsx from 'clsx' +import Modal from '@/components/ui/Modal' +import { allScenarioIds, checkState, formatDepth, groupSpots, shortName, toggleScenarios, type SpotSummary } from '@/utils/ranges' + +interface ExportRangesDialogProps { + open: boolean + spots: readonly SpotSummary[] + onClose: () => void + /** Called with the chosen depths (scenario ids). */ + onExport: (scenarioIds: number[]) => void +} + +/** A checkbox that shows a dash when only part of what it stands for is selected. */ +function Tick({ state, label, onChange }: { state: 'none' | 'some' | 'all'; label: string; onChange: () => void }) { + const ref = useRef(null) + useEffect(() => { + if (ref.current) ref.current.indeterminate = state === 'some' + }, [state]) + return +} + +/** Picks which situations and depths go into the exported file. */ +export default function ExportRangesDialog({ open, spots, onClose, onExport }: ExportRangesDialogProps) { + const { t } = useTranslation() + const [selected, setSelected] = useState>(new Set()) + const groups = useMemo(() => groupSpots(spots), [spots]) + const total = useMemo(() => allScenarioIds(spots).size, [spots]) + + // Every time the dialog opens, everything is selected again. + useEffect(() => { + if (open) setSelected(allScenarioIds(spots)) + }, [open, spots]) + + const toggle = (ids: readonly number[]) => setSelected((current) => toggleScenarios(current, ids)) + const idsOf = (list: readonly SpotSummary[]) => list.flatMap((s) => s.scenarios.map((sc) => sc.id)) + + return ( + + {t('ranges.exportDialog.count', { selected: selected.size, total })} + + + + } + > +

{t('ranges.exportDialog.help')}

+
+ + +
+
+ {groups.map((group) => ( +
+ +
    + {group.spots.map((spot) => { + const ids = spot.scenarios.map((sc) => sc.id) + return ( +
  • + toggle(ids)} /> + + {shortName(spot)} + + + {spot.scenarios.map((sc) => ( + + ))} + +
  • + ) + })} +
+
+ ))} +
+
+ ) +} diff --git a/frontend/src/components/ranges/QuizTable.tsx b/frontend/src/components/ranges/QuizTable.tsx new file mode 100644 index 00000000..08413d54 --- /dev/null +++ b/frontend/src/components/ranges/QuizTable.tsx @@ -0,0 +1,76 @@ +import { useTranslation } from 'react-i18next' +import clsx from 'clsx' +import { formatNumber } from '@/utils/ranges' +import { isLimp, seatLabel, type QuizQuestion, type QuizSeat } from '@/utils/training' + +const SUIT_SYMBOLS: Record = { s: '♠', h: '♥', d: '♦', c: '♣' } + +function CardFace({ card }: { card: string }) { + const suit = card.slice(-1).toLowerCase() + const red = suit === 'h' || suit === 'd' + return ( +
+ {card[0] === 'T' ? '10' : card[0]} + {SUIT_SYMBOLS[suit] ?? ''} +
+ ) +} + +function OpponentSeat({ seat, question, language }: { seat: QuizSeat; question: QuizQuestion; language: string }) { + const { t } = useTranslation() + const folded = seat.action === 'fold' + const pill = (() => { + if (!seat.action) return null + const size = `${formatNumber(seat.betBb, language, Number.isInteger(seat.betBb) ? 0 : 1)} bb` + if (seat.action === 'fold') return t('ranges.training.table.fold') + if (seat.action === 'call') return `${isLimp(question.table.seats, seat) ? t('ranges.training.table.limp') : t('ranges.training.table.call')} ${size}` + if (seat.action === 'raise') return `${t('ranges.training.table.raise')} ${size}` + return `${t('ranges.training.table.allin')} ${size}` + })() + return ( +
+
+ {seatLabel(seat.position, question.opponent, false)} + {formatNumber(seat.stackBb, language, 1)} bb +
+ {pill && {pill}} +
+ ) +} + +/** The table of a quiz question: the opponents' actions, the pot and the hero's cards. */ +export default function QuizTable({ question }: { question: QuizQuestion }) { + const { t, i18n } = useTranslation() + const opponents = question.table.seats.filter((s) => !s.isHero) + const hero = question.table.seats.find((s) => s.isHero) + return ( +
+
+ {t('ranges.training.table.pot')} + {formatNumber(question.table.potBb, i18n.language, Number.isInteger(question.table.potBb) ? 0 : 1)} bb +
+ {opponents[0] && ( +
+ +
+ )} + {opponents[1] && ( +
+ +
+ )} + {hero && ( +
+
+ {t('ranges.training.table.you')} · {hero.position} + {formatNumber(hero.stackBb, i18n.language, 1)} bb +
+
+ + +
+
+ )} +
+ ) +} diff --git a/frontend/src/components/ranges/RangeMatrix.tsx b/frontend/src/components/ranges/RangeMatrix.tsx new file mode 100644 index 00000000..d28c7432 --- /dev/null +++ b/frontend/src/components/ranges/RangeMatrix.tsx @@ -0,0 +1,157 @@ +import { useRef, useState, type KeyboardEvent, type MouseEvent, type PointerEvent, type ReactNode } from 'react' +import clsx from 'clsx' +import { cellOf, GRID_SIZE, handAt, HAND_CLASSES, rectBetween, rowOf, type PaintMode } from '@/utils/ranges' + +export interface MatrixCell { + color: string + textColor: string + dim?: boolean + outline?: 'edited' | 'deviation' | 'focus' + /** Small count in the top right corner (deviations of the hand). */ + badge?: number + /** Shown in a small card while the pointer is over the cell. */ + tip?: ReactNode +} + +interface RangeMatrixProps { + cells: Record + size?: 'sm' | 'md' + label: string + /** Makes the grid editable: called with the hands to paint; `start` is true on a new stroke. */ + onPaint?: (hands: string[], start: boolean) => void + /** The picker mode takes the action of a cell. */ + onPick?: (hand: string) => void + paintMode?: PaintMode +} + +/** Half the width of the hover card, used to keep it inside the grid. */ +const TIP_HALF_WIDTH = 115 +/** Cells this close to the top get their card below them instead of above. */ +const TIP_FLIP_BELOW_PX = 130 + +const OUTLINE_CLASS: Record, string> = { + edited: 'ring-2 ring-inset ring-white', + deviation: 'ring-2 ring-inset ring-deviation', + focus: 'ring-2 ring-inset ring-white font-bold', +} + +/** The 13 x 13 grid of hand classes, coloured by the player's actions. */ +export default function RangeMatrix({ cells, size = 'md', label, onPaint, onPick, paintMode = 'brush' }: RangeMatrixProps) { + const editable = Boolean(onPaint || onPick) + const [anchor, setAnchor] = useState(null) + const [cursor, setCursor] = useState('AA') + const container = useRef(null) + const [hover, setHover] = useState<{ hand: string; x: number; y: number; height: number } | null>(null) + + const act = (hand: string, shift: boolean, start: boolean) => { + if (paintMode === 'picker') return onPick?.(hand) + if (!onPaint) return + if (shift) return onPaint(rowOf(hand), true) + if (paintMode === 'rect') { + if (!start) return + if (anchor === null) return setAnchor(hand) + setAnchor(null) + return onPaint(rectBetween(anchor, hand), true) + } + onPaint([hand], start) + } + + const onPointerDown = (hand: string) => (e: PointerEvent) => { + if (e.button !== 0) return + e.preventDefault() + setCursor(hand) + act(hand, e.shiftKey, true) + } + + const onPointerEnter = (hand: string) => (e: PointerEvent) => { + if (paintMode === 'brush' && (e.buttons & 1) === 1 && !e.shiftKey) act(hand, false, false) + } + + const showTip = (hand: string) => (e: MouseEvent) => { + const box = container.current + const cell = e.currentTarget + if (!box || !cells[hand]?.tip) return setHover(null) + const centre = cell.offsetLeft + cell.offsetWidth / 2 + setHover({ hand, x: Math.min(Math.max(centre, TIP_HALF_WIDTH), box.clientWidth - TIP_HALF_WIDTH), y: cell.offsetTop, height: cell.offsetHeight }) + } + + const onKeyDown = (e: KeyboardEvent) => { + const { row, col } = cellOf(cursor) + const move: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] } + const delta = move[e.key] + if (delta) { + e.preventDefault() + const next = handAt(Math.min(GRID_SIZE - 1, Math.max(0, row + delta[0])), Math.min(GRID_SIZE - 1, Math.max(0, col + delta[1]))) + setCursor(next) + container.current?.querySelector(`[data-hand="${next}"]`)?.focus() + } else if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault() + act(cursor, e.shiftKey, true) + } + } + + const small = size === 'sm' + return ( +
setHover(null)} + className={clsx('relative grid grid-cols-[repeat(13,minmax(0,1fr))] select-none touch-none', small ? 'gap-[2px]' : 'gap-[3px]')} + > + {HAND_CLASSES.map((hand) => { + const cell = cells[hand] + const style = cell ? { backgroundColor: cell.color, color: cell.textColor } : undefined + const classes = clsx( + 'relative aspect-square flex items-center justify-center rounded-[3px] font-mono leading-none', + small ? 'text-[8.5px]' : 'text-[11px]', + !cell && 'bg-dark-300 text-gray-500', + cell?.dim && 'opacity-[0.55]', + cell?.outline && OUTLINE_CLASS[cell.outline], + anchor === hand && 'ring-2 ring-inset ring-white', + editable && 'cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-400', + ) + const content = ( + <> + {hand} + {cell?.badge ? {cell.badge} : null} + + ) + return editable ? ( + + ) : ( +
+ {content} +
+ ) + })} + {hover && cells[hover.hand]?.tip && ( +
+ {cells[hover.hand].tip} +
+ )} +
+ ) +} diff --git a/frontend/src/components/ranges/RangesTour.tsx b/frontend/src/components/ranges/RangesTour.tsx new file mode 100644 index 00000000..6cb61d70 --- /dev/null +++ b/frontend/src/components/ranges/RangesTour.tsx @@ -0,0 +1,110 @@ +import { useMemo, useState } from 'react' +import { useTranslation } from 'react-i18next' +import clsx from 'clsx' +import Modal from '@/components/ui/Modal' +import RangeMatrix from '@/components/ranges/RangeMatrix' +import { useNotificationStore } from '@/stores/notificationStore' +import { useUserRangesStore } from '@/stores/userRangesStore' +import { textColor } from '@/utils/ranges' +import { DEMO_COLORS, DEMO_START, DEMO_TARGET_COUNT, demoCells, EXAMPLE_SCENARIO_COUNT, EXAMPLE_SPOT_COUNT, exampleRangesFile, TOUR_STEPS, type DemoAction } from '@/utils/rangesTour' + +interface RangesTourProps { + open: boolean + onClose: () => void +} + +const startHands = (): Record => Object.fromEntries(DEMO_START.map((hand) => [hand, 'shove' as const])) + +/** A short guided tour of "My ranges", with a grid to try the painting on and the example ranges to start from. */ +export default function RangesTour({ open, onClose }: RangesTourProps) { + const { t } = useTranslation() + const notify = useNotificationStore() + const importRanges = useUserRangesStore((s) => s.importRanges) + const [index, setIndex] = useState(0) + const [demo, setDemo] = useState>(startHands) + const [brush, setBrush] = useState('shove') + const [busy, setBusy] = useState(false) + + const step = TOUR_STEPS[index] + const last = index === TOUR_STEPS.length - 1 + const painted = Object.values(demo).filter((a) => a === 'shove').length + const points = t(`ranges.tour.steps.${step}.points`, { returnObjects: true, defaultValue: [] }) as string[] + const cells = useMemo(() => demoCells(demo, textColor), [demo]) + + const close = () => { + setIndex(0) + setDemo(startHands()) + onClose() + } + + const paintHands = (hands: string[]) => setDemo((current) => ({ ...current, ...Object.fromEntries(hands.map((h) => [h, brush])) })) + + const loadExamples = async () => { + setBusy(true) + const result = await importRanges(exampleRangesFile(), 'merge') + setBusy(false) + if (result.error) return notify.error(result.error) + notify.success(t('ranges.tour.examplesLoaded')) + close() + } + + const footer = ( + <> + + {index > 0 && ( + + )} + {last ? ( + <> + + + + ) : ( + + )} + + ) + + return ( + {t('ranges.tour.progress', { current: index + 1, total: TOUR_STEPS.length })}}> +

{t(`ranges.tour.steps.${step}.title`)}

+

{t(`ranges.tour.steps.${step}.body`)}

+ {points.length > 0 && ( +
    + {points.map((point) => ( +
  • {point}
  • + ))} +
+ )} + + {step === 'paint' && ( +
+
+
+ {(['shove', 'fold'] as const).map((action) => ( + + ))} +
+ {t('ranges.tour.painted', { count: painted, target: DEMO_TARGET_COUNT })} +
+ +
+ )} + + {step === 'start' &&

{t('ranges.tour.examplesNote', { spots: EXAMPLE_SPOT_COUNT, scenarios: EXAMPLE_SCENARIO_COUNT })}

} +
+ ) +} diff --git a/frontend/src/components/replayer/RangeCheckCard.tsx b/frontend/src/components/replayer/RangeCheckCard.tsx new file mode 100644 index 00000000..7e9053bc --- /dev/null +++ b/frontend/src/components/replayer/RangeCheckCard.tsx @@ -0,0 +1,48 @@ +import { useTranslation } from 'react-i18next' +import DeviationBadge from '@/components/ranges/DeviationBadge' +import { COLOR_SHADES, formatDepth, formatNumber } from '@/utils/ranges' + +/** What the backend returns for a hand compared with the player's ranges. */ +export interface RangeCheck { + status: 'match' | 'deviation' | 'no_range' + scenarioName: string | null + expectedAction: { id: number; label: string; color: string } | null + playedAction: { id: number; label: string; color: string } | null + playedImmediate: string + playedResponse: string | null + deviationKind: 'immediate' | 'size' | 'response' | null + depthUsedBb: number | null + stackBb: number +} + +/** Colour of a played action the player has no action for. */ +const UNKNOWN_ACTION_COLOR = COLOR_SHADES[2] + +/** The replayer's card telling whether the hero followed their own range on this hand. */ +export default function RangeCheckCard({ check }: { check: RangeCheck }) { + const { t, i18n } = useTranslation() + + if (check.status === 'no_range') { + return

{t('ranges.replayer.noRange')}

+ } + if (check.status === 'match') { + return ( +

+ {t('ranges.replayer.match')} + {check.scenarioName} +

+ ) + } + const played = check.playedAction ?? { label: t(`ranges.immediate.${check.playedImmediate}`), color: UNKNOWN_ACTION_COLOR } + return ( +
+ {t('ranges.replayer.deviation')} + + {check.depthUsedBb !== null && ( +

+ {t('ranges.replayer.scenario', { name: check.scenarioName, depth: formatDepth(check.depthUsedBb), stack: formatNumber(check.stackBb, i18n.language, 1) })} +

+ )} +
+ ) +} diff --git a/frontend/src/components/replayer/Replayer.tsx b/frontend/src/components/replayer/Replayer.tsx index b437ed53..02cd7a57 100644 --- a/frontend/src/components/replayer/Replayer.tsx +++ b/frontend/src/components/replayer/Replayer.tsx @@ -5,6 +5,7 @@ import clsx from 'clsx' import type { Json } from '@/services/ipcService' import { isRealAction, selectCurrentAction, selectDoneActions, selectTotalActions, useReplayerStore } from '@/stores/replayerStore' import PokerTable from './PokerTable' +import RangeCheckCard from './RangeCheckCard' import './replayer.css' const SPEEDS = [ @@ -116,6 +117,11 @@ export default function Replayer() { {showLogs && (