Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down
161 changes: 159 additions & 2 deletions crates/core/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)?)?;
Expand Down Expand Up @@ -425,12 +437,22 @@ impl Backend {
("POST", ["analysis", "hands"]) => Response::data(analysis::analysis_hands(&*conn()?, &r.body_as_camel::<AnalysisHandsRequest>()?)?),
("POST", ["analysis", "range-breakdown"]) => Response::data(analysis::range_breakdown(&*conn()?, &r.body_as_camel::<AnalysisFilters>()?)?),
("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),

Expand Down Expand Up @@ -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<Option<Response>> {
use std::collections::BTreeMap;
let result: ranges::Res<Option<Response>> = (|| {
let mut conn = self.db.conn()?;
let id = |s: &str| s.parse::<i64>().map_err(|_| RangeError::Invalid(format!("bad id: {s}")));
let body = |name: &str| -> ranges::Res<Value> { 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<String, i64> = 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<ranges::ActionInput> = 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::<i64>("scenarioId")?, r.body_str("handClass").unwrap_or_default(), r.body_field::<bool>("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<std::collections::HashSet<i64>> = 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<Option<Response>> {
let response = match (r.method, rest) {
("GET", []) => Response::data(Value::Array(self.registry.get_all().iter().map(database_json).collect())),
Expand Down
19 changes: 17 additions & 2 deletions crates/core/src/db/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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;
Expand All @@ -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<String> = conn
.query_row("SELECT room FROM players WHERE name = 'hero'", [], |r| r.get(0))
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/db/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
75 changes: 75 additions & 0 deletions crates/core/src/db/sql/202611200001_user_ranges.sql
Original file line number Diff line number Diff line change
@@ -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');
Loading
Loading