From 015fa65f56faff3a9b566068c03551bab2d5ee05 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:00:22 +0100 Subject: [PATCH 1/3] Modern UI: the statistics screen reads the almanac ModernSession::read_statistics_screen answers the statistics screen's filters with real data: eternal table, national tournaments (winners, scorers, history), series and records, winners by season and the own club per five minutes. Views the engine does not record yet (title chances, transfers, weekly curves, season finances) answer available false, reason not_recorded. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 3 +- src/modern/app/modern_session.hpp | 4 + src/modern/content/statistics.cpp | 349 +++++++++++++++++++++++++++++ src/modern/content/statistics.hpp | 7 + tests/modern_season_sim.cpp | 8 + tests/modern_ui_contract_tests.cpp | 8 + 6 files changed, 378 insertions(+), 1 deletion(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 98d44f3..5fdbfb5 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -40,7 +40,8 @@ Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt auf; Antwort `{ok, ...}` wie in ihrer Demo. - `ModernSession::read_almanac`: `index` (Jahre, Anzahl, erstes/letztes Datum), `calendar {year}` (Spieltage mit Anzahl und Höhepunkten), `day {date}` (alle Spiele des Tages), `match {id}` (`match:-`). Ein Spiel trägt Datum, Saison, Wettbewerb (`league`/`cup`/`friendly`), Runde, beide Seiten (mit Manager, wenn menschlich), Ergebnis getrennt nach regulärer Zeit, Verlängerung (über die Torminuten) und Elfmeterschießen, Schiedsrichter, Zuschauer, Wetter, Aufstellungen (unter elf Spielern `null`) und Ereignisse (`goal`, `miss`, `yellow`, `second_yellow`, `red`, `injury`, `substitution`, `shootout`). -- `ModernSession::read_statistics`: `competitions`, `winners`, `player_stats` ([Statistik](statistik.md)). **Offen:** Der Statistikbildschirm der UI fragt andere Arten ab (Kategorie, Bereich, Verlaufskurven); der Abgleich folgt. +- `ModernSession::read_statistics_screen`: der Statistikbildschirm mit den Filtern seiner Demo (`section` 0–8, `category`, `country`, `winner_country`, `absolute`, `curves`), `fictional: false`. Aus dem Almanach: 3 Ewige Tabelle (je Land die erste Liga, 5 die eigene), 4 WM-Statistiken (Sieger mit Finale, Torschützen, Länder-Historie), 6 Serien und Rekorde (eigene Liga), 7 Sieger (national, Europapokale, Hallen-Masters), 8 Minuten-Statistik (eigener Verein). Noch ohne Aufzeichnung (`available: false`, `reason: not_recorded`): 0 Möglichkeiten, 1 Transferhistorie, 2 Analytics-Kurven, 5 Saisonfinanzen, bei 4 Gruppen und Finalrunde. +- `ModernSession::read_statistics`: `competitions`, `winners`, `player_stats` ([Statistik](statistik.md)) für eine eigene Spieler- und Siegerstatistik. ## Commands diff --git a/src/modern/app/modern_session.hpp b/src/modern/app/modern_session.hpp index 6c27181..c4d24ad 100644 --- a/src/modern/app/modern_session.hpp +++ b/src/modern/app/modern_session.hpp @@ -833,6 +833,10 @@ public: cli::Json read_statistics(const cli::Json& request) const { return query_statistics(g_, request); } // The almanac screen (index, calendar, day, match; docs/new_engine/ui-anbindung.md). Read-only. cli::Json read_almanac(const cli::Json& request) const { return query_almanac(g_, request); } + // The statistics screen for the manager at the desk (docs/new_engine/ui-anbindung.md). Read-only. + cli::Json read_statistics_screen(const cli::Json& request) const { + return query_statistics_screen(g_, int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0), request); + } // The read queries of the new interface (docs/new_engine/ui-abfragen.md): status, leagues, // table, fixtures, squad and the statistics, for the manager at the desk. Read-only. cli::Json read(const cli::Json& request) const { diff --git a/src/modern/content/statistics.cpp b/src/modern/content/statistics.cpp index 3acb242..d0ca9f4 100644 --- a/src/modern/content/statistics.cpp +++ b/src/modern/content/statistics.cpp @@ -2,6 +2,7 @@ #include "modern/content/statistics.hpp" #include +#include #include #include #include @@ -11,6 +12,8 @@ #include "formats/executable_layout.hpp" #include "game/messages.hpp" +#include "game/schedule.hpp" +#include "modern/content/world_package.hpp" #include "modern/game/almanac.hpp" namespace bmh::modern { @@ -398,4 +401,350 @@ cli::Json query_almanac(const ModernState& g, const cli::Json& request) { } } + +// --- the statistics screen of the Modern UI (DataSource::read_statistics; the demo's filters) --- + +namespace { + +constexpr const char* kSections[9] = {"Möglichkeiten", "Transferhistorie", "Analytics", "Ewige Tabelle", "WM-Statistiken", + "Saisonfinanzen", "Serien u. Rekorde", "Sieger", "Minuten-Statistik"}; +constexpr const char* kWorldViews[6] = {"Sieger", "Gruppen", "Torschützen", "Finalrunde", "Tabelle", "Historie"}; +// The first league of the countries with leagues, in the screen's order (de, es, it, fr, en); +// kEternal maps the eternal table's values (de, es, en, fr, it) to it. +struct Country { const char* code; const char* name; int league; }; +constexpr Country kCountries[5] = {{"de", "Deutschland", 0}, {"es", "Spanien", 5}, {"it", "Italien", 8}, + {"fr", "Frankreich", 7}, {"en", "England", 6}}; +constexpr int kEternal[5] = {0, 1, 4, 3, 2}; + +J cell(const std::string& text) { return O{{"text", text}}; } +J numeric(int64_t v) { return O{{"text", std::to_string(v)}, {"value", v}}; } +J club_cell(const AlmanacClub& c) { return O{{"text", c.name}, {"club", c.id}}; } +J nation_cell(const AlmanacClub& c) { return O{{"text", c.name}, {"nation", c.id}}; } + +// The world's nation of the league's clubs; without a world "nation:". +std::string country_nation(const Country& c) { + if (const World* w = current_world()) + for (const auto& l : w->leagues) + if (l.index == c.league && !l.members.empty()) + if (const WorldClub* club = w->club(l.members.front()); club && !club->nation.empty()) return club->nation; + return std::string("nation:") + c.code; +} + +void headings(O& out, std::initializer_list names) { + A& cols = std::get(out["columns"].value); + for (const char* n : names) cols.push_back(cell(n)); +} +void row(O& out, A cells) { std::get(out["rows"].value).push_back(O{{"cells", std::move(cells)}}); } + +// The ids of a league's clubs as the running game has them. +std::set league_club_ids(const ModernState& g, int league) { + std::set ids; + if (league < 0) return ids; + const int first = league_first_team(league); + for (int t = first; t < first + int(kLeagueSizes[league]); ++t) { + const std::string id = t < int(g.world_club_id.size()) ? g.world_club_id[size_t(t)] : std::string{}; + ids.insert(id.empty() ? "team:" + std::to_string(t) : id); + } + return ids; +} + +void eternal_table(O& out, const std::vector& seasons, int league) { + headings(out, {"Verein", "Sp.", "S", "U", "N", "Punkte", "Tore"}); + struct Sum { AlmanacClub club; int played = 0, won = 0, drawn = 0, lost = 0, points = 0, gf = 0, ga = 0; }; + std::map sums; + for (const auto& s : seasons) + for (const auto& t : s.tables) { + if (t.league != league) continue; + for (const auto& r : t.rows) { + Sum& x = sums[s.clubs[r.club].id]; + x.club = s.clubs[r.club]; + x.played += r.played, x.won += r.won, x.drawn += r.drawn, x.lost += r.lost, x.points += r.points; + x.gf += r.goals_for, x.ga += r.goals_against; + } + } + std::vector list; + for (auto& [id, x] : sums) list.push_back(x); + std::stable_sort(list.begin(), list.end(), [](const Sum& a, const Sum& b) { + return a.points != b.points ? a.points > b.points : a.gf - a.ga > b.gf - b.ga; + }); + for (const auto& x : list) + row(out, A{club_cell(x.club), numeric(x.played), numeric(x.won), numeric(x.drawn), numeric(x.lost), numeric(x.points), + cell(std::to_string(x.gf) + ":" + std::to_string(x.ga))}); +} + +// The national tournaments: cup 6 is the final round (a final), cup 7 the qualification. +bool national_match(const AlmanacMatch& m) { return m.type == 7 || m.type == 8; } + +bool world_tournaments(O& out, const ModernState& g, const std::vector& seasons, int view) { + if (view == 0) { + headings(out, {"WM / EM", "Sieger", "Finalist", "Finale"}); + for (auto s = seasons.rbegin(); s != seasons.rend(); ++s) + for (const auto& w : s->winners) { + if (w.type != 7) continue; + std::string final_score = "—"; + for (const auto& m : s->matches) + if (m.type == 7 && ((m.home == w.winner && m.away == w.runner_up) || (m.away == w.winner && m.home == w.runner_up))) + final_score = std::to_string(m.home_goals) + ":" + std::to_string(m.away_goals); + const std::string when = std::to_string(s->start_year + 1); + row(out, A{J(O{{"text", cup_name(g, 6) + " " + when}, {"season", when}, {"winner", s->clubs[w.winner].id}}), + nation_cell(s->clubs[w.winner]), w.runner_up == 0xffff ? cell("—") : nation_cell(s->clubs[w.runner_up]), + cell(final_score)}); + } + return true; + } + if (view == 2) { + headings(out, {"Spieler", "Land", "Tore"}); + struct Scorer { int goals = 0; J player, nation; }; + std::map scorers; + for (const auto& s : seasons) + for (const auto& m : s.matches) { + if (!national_match(m)) continue; + for (const auto& e : m.events) { + if (e.kind != AlmanacEventKind::Goal || e.player == kAlmanacNone || e.player >= s.players.size()) continue; + const AlmanacPlayer& p = s.players[e.player]; + Scorer& x = scorers[p.id]; + ++x.goals; + x.player = O{{"text", player_name(p)}, {"player", p.id}}; + x.nation = nation_cell(s.clubs[e.side ? m.away : m.home]); + } + } + std::vector list; + for (auto& [id, x] : scorers) list.push_back(x); + std::stable_sort(list.begin(), list.end(), [](const Scorer& a, const Scorer& b) { return a.goals > b.goals; }); + for (size_t i = 0; i < list.size() && i < 20; ++i) row(out, A{list[i].player, list[i].nation, numeric(list[i].goals)}); + return true; + } + if (view == 4 || view == 5) { + headings(out, {"Land", "Spiele", "Siege", "Punkte"}); + struct Rec { AlmanacClub club; int games = 0, wins = 0, points = 0; }; + std::map recs; + for (const auto& s : seasons) + for (const auto& m : s.matches) { + if (!national_match(m)) continue; + for (int side = 0; side < 2; ++side) { + Rec& r = recs[s.clubs[side ? m.away : m.home].id]; + r.club = s.clubs[side ? m.away : m.home]; + const int own = side ? m.away_goals : m.home_goals, other = side ? m.home_goals : m.away_goals; + ++r.games; + if (own > other) ++r.wins, r.points += 3; + else if (own == other) r.points += 1; + } + } + std::vector list; + for (auto& [id, r] : recs) list.push_back(r); + std::stable_sort(list.begin(), list.end(), [](const Rec& a, const Rec& b) { return a.points > b.points; }); + for (const auto& r : list) row(out, A{nation_cell(r.club), numeric(r.games), numeric(r.wins), numeric(r.points)}); + return true; + } + return false; // groups, final round: not yet +} + +void series_and_records(O& out, const ModernState& g, const std::vector& seasons, int league) { + headings(out, {"Serie / Rekord", "Verein", "Wert"}); + const auto ids = league_club_ids(g, league); + struct Run { int unbeaten = 0, wins = 0, scoring = 0, best_unbeaten = 0, best_wins = 0, best_scoring = 0; AlmanacClub club; }; + std::map runs; + struct Best { AlmanacClub club; std::array value{}; }; // home wins, away wins, goals in one season + std::map season_best; + int biggest = -1, crowd = -1; + J biggest_club = cell("—"), crowd_club = cell("—"); + std::string big_score; + for (const auto& s : seasons) { + std::map this_season; + for (const auto& m : s.matches) { + if (m.type != 0 || m.league != league) continue; + for (int side = 0; side < 2; ++side) { + const AlmanacClub& c = s.clubs[side ? m.away : m.home]; + if (!ids.count(c.id)) continue; + const int own = side ? m.away_goals : m.home_goals, other = side ? m.home_goals : m.away_goals; + Run& r = runs[c.id]; + r.club = c; + r.unbeaten = own >= other ? r.unbeaten + 1 : 0; + r.wins = own > other ? r.wins + 1 : 0; + r.scoring = own > 0 ? r.scoring + 1 : 0; + r.best_unbeaten = std::max(r.best_unbeaten, r.unbeaten); + r.best_wins = std::max(r.best_wins, r.wins); + r.best_scoring = std::max(r.best_scoring, r.scoring); + Best& x = this_season[c.id]; + x.club = c; + if (own > other) ++x.value[size_t(side)]; + x.value[2] += own; + if (own - other > biggest) biggest = own - other, biggest_club = club_cell(c), big_score = std::to_string(own) + " : " + std::to_string(other); + if (side == 0 && int(m.attendance) > crowd) crowd = int(m.attendance), crowd_club = club_cell(c); + } + } + for (auto& [id, x] : this_season) { + Best& b = season_best[id]; + b.club = x.club; + for (size_t k = 0; k < 3; ++k) b.value[k] = std::max(b.value[k], x.value[k]); + } + } + const auto best_run = [&](int Run::*value, const char* name) { + int best = 0; + J who = cell("—"); + for (const auto& [id, r] : runs) if (r.*value > best) best = r.*value, who = club_cell(r.club); + if (best > 0) row(out, A{cell(name), who, numeric(best)}); + }; + const auto best_season = [&](size_t k, const char* name) { + int best = 0; + J who = cell("—"); + for (const auto& [id, b] : season_best) if (b.value[k] > best) best = b.value[k], who = club_cell(b.club); + if (best > 0) row(out, A{cell(name), who, numeric(best)}); + }; + best_run(&Run::best_unbeaten, "Ungeschlagen"); + best_run(&Run::best_wins, "Siege in Folge"); + best_season(0, "Heimsiege"); + best_season(1, "Auswärtssiege"); + best_season(2, "Tore in einer Saison"); + if (biggest > 0) row(out, A{cell("Höchster Sieg"), biggest_club, cell(big_score)}); + best_run(&Run::best_scoring, "Längste Torserie"); + if (crowd > 0) row(out, A{cell("Meiste Zuschauer"), crowd_club, numeric(crowd)}); +} + +void winners_by_season(O& out, const std::vector& seasons, int category, int country) { + struct Title { const char* text; const char* trophy; int type; int league; int detail; }; + std::vector titles; + if (category == 0) { + const Country& c = kCountries[country]; + titles.push_back({"Meisterschaft", c.league == 0 ? "championship" : "", 0, c.league, 0}); + if (c.league == 0) titles.push_back({"DFB-Pokal", "dfb-cup", 1, -1, 0}); + out["note"] = std::string(c.name) + " · Titelträger im Saisonvergleich"; + } else if (category == 1) { + titles = {{"Champions League", "champions-league", 2, -1, 0}, {"Pokalsieger", "cup-winners", 3, -1, 0}, {"UEFA-Cup", "uefa-cup", 4, -1, 0}}; + out["note"] = "Europäische Titelträger im Saisonvergleich"; + } else { + titles = {{"Sieger", "indoor-masters", 12, -1, 1}, {"Finalist", "", 12, -1, 2}}; + out["note"] = "Hallenmasters · Sieger und Finalisten"; + } + headings(out, {"Saison"}); + for (const auto& t : titles) std::get<A>(out["columns"].value).push_back(O{{"text", t.text}, {"trophy", t.trophy}}); + for (auto s = seasons.rbegin(); s != seasons.rend(); ++s) { + A cells{cell(season_label(s->start_year))}; + bool any = false; + for (const auto& t : titles) { + J value = cell("—"); + for (const auto& w : s->winners) { + if (w.type != t.type || (t.type == 0 && w.league != t.league)) continue; + if (t.detail >= 1 && w.detail != 1) continue; + const uint16_t c = t.detail == 2 ? w.runner_up : w.winner; + if (c != 0xffff) value = club_cell(s->clubs[c]), any = true; + } + cells.push_back(std::move(value)); + } + if (any) row(out, std::move(cells)); + } +} + +void minute_buckets(O& out, const std::vector<AlmanacSeason>& seasons, const std::string& own) { + headings(out, {"Ereignis"}); + for (int i = 0; i < 18; ++i) std::get<A>(out["columns"].value).push_back(cell(std::to_string(i * 5) + ".")); + std::array<std::array<int, 18>, 4> counts{}; + for (const auto& s : seasons) + for (const auto& m : s.matches) { + const int side = s.clubs[m.home].id == own ? 0 : s.clubs[m.away].id == own ? 1 : -1; + if (side < 0) continue; + for (const auto& e : m.events) { + if (e.side != side || e.minute < 1 || e.minute > 90) continue; + const size_t b = size_t(std::min(17, (e.minute - 1) / 5)); + if (e.kind == AlmanacEventKind::Goal) ++counts[0][b], ++counts[1][b]; + if (e.kind == AlmanacEventKind::Miss) ++counts[1][b]; + if (e.kind == AlmanacEventKind::YellowCard) ++counts[2][b]; + if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++counts[3][b]; + } + } + const char* names[4] = {"Tore", "Chancen", "Gelb", "Rot"}; + for (size_t k = 0; k < 4; ++k) { + A cells{cell(names[k])}; + for (size_t b = 0; b < 18; ++b) cells.push_back(numeric(counts[k][b])); + row(out, std::move(cells)); + } +} + +} // namespace + +cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::Json& request) { + const auto reject = [](const char* e) { return J(O{{"ok", false}, {"fictional", false}, {"error", e}}); }; + const auto* o = request.object(); + if (!o) return reject("invalid_statistics_request"); + for (const auto& [key, value] : *o) + if (key != "section" && key != "category" && key != "country" && key != "winner_country" && key != "absolute" && key != "curves") + return reject("unknown_statistics_filter"); + const auto integer = [&](const char* key, int fallback, int maximum) -> int { + const J* v = field(request, key); + if (!v) return fallback; + return v->integer() && *v->integer() >= 0 && *v->integer() <= maximum ? int(*v->integer()) : -1; + }; + const int section = integer("section", 7, 8), category = integer("category", 0, 5), country = integer("country", 0, 5); + if (section < 0 || category < 0 || country < 0 || (category != 0 && category != 1 && category != 5)) + return reject("invalid_statistics_filter"); + std::string winner_country = country_nation(kCountries[0]); + if (const J* w = field(request, "winner_country")) { + if (!w->string()) return reject("invalid_statistics_country"); + winner_country = *w->string(); + } + int winner_index = -1; + for (int i = 0; i < 5; ++i) + if (country_nation(kCountries[i]) == winner_country) winner_index = i; + if (winner_index < 0) return reject("invalid_statistics_country"); + const J* abs = field(request, "absolute"); + const bool absolute = abs && std::holds_alternative<bool>(abs->value) && std::get<bool>(abs->value); + A curves; + for (int i = 0; i < 6; ++i) curves.push_back(true); + if (const J* c = field(request, "curves")) { + if (!c->array() || c->array()->size() != 6) return reject("invalid_statistics_curves"); + curves = *c->array(); + } + try { + const auto seasons = seasons_of(g); + const int team = manager >= 0 && size_t(manager) < g.manager_teams.size() ? g.manager_teams[size_t(manager)] : -1; + const bool club = team >= 0 && team < league_clubs(); + std::string own_id; + if (club) { + own_id = team < int(g.world_club_id.size()) ? g.world_club_id[size_t(team)] : std::string{}; + if (own_id.empty()) own_id = "team:" + std::to_string(team); + } + const int own_league = club ? team_league(team) : -1; + const int year = g.display_start_year + g.season; + std::string manager_name; + const size_t at = size_t(std::max(0, manager)) * 0xb0c + 0xa8; + for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i) + manager_name.push_back(char(g.manager_records[at + i])); + A sections, views, countries, eternal; + for (const char* s : kSections) sections.push_back(s); + for (const char* v : kWorldViews) views.push_back(v); + for (const auto& c : kCountries) countries.push_back(O{{"id", country_nation(c)}, {"name", c.name}}); + for (int v = 0; v < 5; ++v) + eternal.push_back(O{{"value", v}, {"nation", country_nation(kCountries[kEternal[v]])}, {"name", kCountries[kEternal[v]].name}}); + eternal.push_back(O{{"value", 5}, {"name", "Absolut"}}); + O out{{"ok", true}, {"fictional", false}, {"available", true}, {"section", section}, {"category", category}, + {"country", country}, {"winner_country", winner_country}, {"absolute", absolute}, {"curves", curves}, + {"title", kSections[section]}, {"season", season_label(year)}, {"previous_season", season_label(year - 1)}, + {"year", year}, {"manager", manager_name.empty() ? "—" : almanac_utf8(manager_name)}, + {"club", club ? J(own_id) : J(nullptr)}, {"columns", A{}}, {"rows", A{}}, {"countries", std::move(countries)}, + {"sections", std::move(sections)}, {"world_views", std::move(views)}, {"series", A{}}, + {"eternal_countries", std::move(eternal)}}; + // the views without a record of their own yet: title chances, transfers, weekly curves, + // season finances; the groups and final round of the national tournaments + bool known = true; + if (section == 3) { + eternal_table(out, seasons, country == 5 ? own_league : kCountries[kEternal[country]].league); + } else if (section == 4) { + known = world_tournaments(out, g, seasons, country); + } else if (section == 6) { + if (club) series_and_records(out, g, seasons, own_league); + } else if (section == 7) { + winners_by_season(out, seasons, category, winner_index); + } else if (section == 8) { + if (club) minute_buckets(out, seasons, own_id); + } else { + known = false; + } + if (!known) out["reason"] = "not_recorded"; + out["available"] = known && !std::get<A>(out["rows"].value).empty(); + return J(std::move(out)); + } catch (const std::exception&) { + return reject("statistics_unavailable"); + } +} + } // namespace bmh::modern diff --git a/src/modern/content/statistics.hpp b/src/modern/content/statistics.hpp index b3d5dd3..5485fda 100644 --- a/src/modern/content/statistics.hpp +++ b/src/modern/content/statistics.hpp @@ -28,4 +28,11 @@ cli::Json query_statistics(const ModernState& g, const cli::Json& request); // regulation / extra time / penalties, referee, attendance, weather, line-ups, events. cli::Json query_almanac(const ModernState& g, const cli::Json& request); +// The statistics screen of the Modern UI (DataSource::read_statistics) with the filters of its demo +// (section 0-8, category, country, winner_country, absolute, curves), from the almanac: eternal +// table, national tournaments (winners, scorers, history), series and records, winners by season, +// the own club per five minutes. Views without a record yet answer available: false, reason +// not_recorded (title chances, transfers, weekly curves, season finances). +cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::Json& request); + } // namespace bmh::modern diff --git a/tests/modern_season_sim.cpp b/tests/modern_season_sim.cpp index 7d99fb0..23c59ca 100644 --- a/tests/modern_season_sim.cpp +++ b/tests/modern_season_sim.cpp @@ -747,6 +747,14 @@ int main(int argc, char** argv) { const auto request = cli::Json::Object{{"kind", kind}, {"requestId", std::string("request:sim-") + kind}}; std::printf("ui_read %s\n -> %s\n", kind, cli::dump_json(session.ui_read(request, revision)).c_str()); } + for (const auto& filter : {cli::Json::Object{{"section", 3}}, cli::Json::Object{{"section", 4}, {"country", 0}}, + cli::Json::Object{{"section", 4}, {"country", 2}}, cli::Json::Object{{"section", 6}}, + cli::Json::Object{{"section", 7}}, cli::Json::Object{{"section", 7}, {"category", 1}}, + cli::Json::Object{{"section", 8}}, cli::Json::Object{{"section", 1}}}) { + std::string answer = cli::dump_json(session.read_statistics_screen(filter)); + if (answer.size() > 1500) answer = answer.substr(0, 1500) + " ..."; + std::printf("statistics screen %s\n -> %s\n", cli::dump_json(filter).c_str(), answer.c_str()); + } std::printf("ui_read wrong manager\n -> %s\n", cli::dump_json(session.ui_read(cli::Json::Object{{"kind", "desktop"}, {"managerId", "manager:99"}}, revision)).c_str()); } diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 4930c19..d92f6b4 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -269,6 +269,14 @@ int main(int argc, char** argv) { } check(s(at(session.read_almanac(O{{"kind", "match"}, {"id", "match:0-0"}}), "error")) == "almanac_match_not_found", "unknown match"); + // the statistics screen: real data (fictional false), unrecorded views say so + const J minutes = session.read_statistics_screen(O{{"section", 8}}); + check(truth(at(minutes, "ok")) && !truth(at(minutes, "fictional")) && at(minutes, "rows").array() && + at(minutes, "rows").array()->size() == 4, "minute statistics"); + const J transfers = session.read_statistics_screen(O{{"section", 1}}); + check(truth(at(transfers, "ok")) && !truth(at(transfers, "available")) && s(at(transfers, "reason")) == "not_recorded", + "transfer history not recorded"); + check(s(at(session.read_statistics_screen(O{{"section", 9}}), "error")) == "invalid_statistics_filter", "bad section"); } } catch (const std::exception& ex) { std::fprintf(stderr, "FAIL: %s\n", ex.what()); From 6054a44acff3e10719e05da4bc87d432d9fb415b Mon Sep 17 00:00:00 2001 From: Claude <claude@openbmh.invalid> Date: Tue, 27 Oct 2026 09:05:57 +0100 Subject: [PATCH 2/3] Modern UI statistics screen: transfer history and the six curves Section 1 lists the manager's transfers from the original's own records, section 2 the six curves of the original (its labels, weekly values and the absolute scale); the interface scales them itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/new_engine/ui-anbindung.md | 2 +- src/modern/app/modern_session.cpp | 58 ++++++++++++++++++++++++++++++ src/modern/app/modern_session.hpp | 5 ++- tests/modern_season_sim.cpp | 2 +- tests/modern_ui_contract_tests.cpp | 2 ++ 5 files changed, 64 insertions(+), 5 deletions(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 5fdbfb5..212a5dd 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -40,7 +40,7 @@ Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt auf; Antwort `{ok, ...}` wie in ihrer Demo. - `ModernSession::read_almanac`: `index` (Jahre, Anzahl, erstes/letztes Datum), `calendar {year}` (Spieltage mit Anzahl und Höhepunkten), `day {date}` (alle Spiele des Tages), `match {id}` (`match:<Saisonstartjahr>-<Nr.>`). Ein Spiel trägt Datum, Saison, Wettbewerb (`league`/`cup`/`friendly`), Runde, beide Seiten (mit Manager, wenn menschlich), Ergebnis getrennt nach regulärer Zeit, Verlängerung (über die Torminuten) und Elfmeterschießen, Schiedsrichter, Zuschauer, Wetter, Aufstellungen (unter elf Spielern `null`) und Ereignisse (`goal`, `miss`, `yellow`, `second_yellow`, `red`, `injury`, `substitution`, `shootout`). -- `ModernSession::read_statistics_screen`: der Statistikbildschirm mit den Filtern seiner Demo (`section` 0–8, `category`, `country`, `winner_country`, `absolute`, `curves`), `fictional: false`. Aus dem Almanach: 3 Ewige Tabelle (je Land die erste Liga, 5 die eigene), 4 WM-Statistiken (Sieger mit Finale, Torschützen, Länder-Historie), 6 Serien und Rekorde (eigene Liga), 7 Sieger (national, Europapokale, Hallen-Masters), 8 Minuten-Statistik (eigener Verein). Noch ohne Aufzeichnung (`available: false`, `reason: not_recorded`): 0 Möglichkeiten, 1 Transferhistorie, 2 Analytics-Kurven, 5 Saisonfinanzen, bei 4 Gruppen und Finalrunde. +- `ModernSession::read_statistics_screen`: der Statistikbildschirm mit den Filtern seiner Demo (`section` 0–8, `category`, `country`, `winner_country`, `absolute`, `curves`), `fictional: false`. Aus dem Almanach: 3 Ewige Tabelle (je Land die erste Liga, 5 die eigene), 4 WM-Statistiken (Sieger mit Finale, Torschützen, Länder-Historie), 6 Serien und Rekorde (eigene Liga), 7 Sieger (national, Europapokale, Hallen-Masters), 8 Minuten-Statistik (eigener Verein). Aus den Aufzeichnungen des Originals: 1 Transferhistorie (Käufe, Verkäufe, Leihen des Managers mit Ablöse) und 2 Analytics: die sechs Kurven des Originals mit ihren Namen, `values` je erfasster Woche und `absoluteMin`/`absoluteMax`; **die UI skaliert selbst** (`points` bleibt leer, die Demo lieferte Bildschirmkoordinaten). Noch ohne Aufzeichnung (`available: false`, `reason: not_recorded`): 0 Möglichkeiten, 5 Saisonfinanzen (das Original speichert nur die laufende Saison), bei 4 Gruppen und Finalrunde. - `ModernSession::read_statistics`: `competitions`, `winners`, `player_stats` ([Statistik](statistik.md)) für eine eigene Spieler- und Siegerstatistik. ## Commands diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 4baf485..be544bd 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8752,6 +8752,64 @@ std::string ui_text(const cli::Json& j, const char* key) { } // namespace +cli::Json ModernSession::read_statistics_screen(const cli::Json& request) const { + using O = cli::Json::Object; + using A = cli::Json::Array; + const int manager = int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0); + cli::Json answer = modern::query_statistics_screen(g_, manager, request); + auto* out = std::get_if<O>(&answer.value); + if (!out || !out->count("section") || !(*out)["section"].integer()) return answer; + const int64_t section = *(*out)["section"].integer(); + if (section != 1 && section != 2) return answer; + const bool club = manager >= 0 && size_t(manager) < g_.manager_teams.size() && + g_.manager_teams[size_t(manager)] >= 0 && g_.manager_teams[size_t(manager)] < league_clubs(); + try { + if (section == 1 && club) { + // the manager's transfer list of the original (+0x760/+0x7d8): date, kind, player, other club, fee + const ui::TransferHistoryProjection h = ui::transfer_history_from_game(g_, manager); + auto& cols = std::get<A>((*out)["columns"].value); + for (const char* c : {"Saison / Spieler", "Von", "Nach", "Ablöse"}) cols.push_back(O{{"text", c}}); + const size_t team = size_t(g_.manager_teams[size_t(manager)]); + const std::string own = team < g_.world_club_name.size() && !g_.world_club_name[team].empty() + ? g_.world_club_name[team] : ui::original_to_utf8(g_.club_name(int(team))); + static constexpr const char* kKinds[4] = {"Verkauf", "Kauf", "Verleih", "Leihe"}; + for (const auto& r : h.rows) { + const AlmanacDate d = almanac_date(r.source_date_counter, g_.display_start_year); + const std::string other = r.special_counterparty ? "Ausland" : ui::original_to_utf8(r.counterparty_club_name); + const bool outgoing = (r.source_kind & 3) == 0 || (r.source_kind & 3) == 2; + std::get<A>((*out)["rows"].value).push_back(O{{"cells", A{ + O{{"text", std::to_string(d.year) + " · " + ui::original_to_utf8(r.saved_player_name)}, {"kind", kKinds[r.source_kind & 3]}}, + O{{"text", outgoing ? own : other}}, O{{"text", outgoing ? other : own}}, + O{{"text", std::to_string(r.source_fee) + " €"}, {"value", int64_t(r.source_fee)}, {"money", modern::ui_money(r.source_fee)}}}}}); + } + } + if (section == 2 && club) { + // the six curves of the original (labels from the executable), values per recorded week; + // the interface scales them (absolute: min/max of the original's absolute scale) + const ui::AnalyticsState a = ui::analytics_from_game(g_, exe_, manager, Image(320, 240)); // (the underlay only draws) + const A* active = (*out)["curves"].array(); + auto& series = std::get<A>((*out)["series"].value); + for (size_t i = 0; i < a.series.size(); ++i) { + A values; + for (int32_t v : a.series[i].values) values.push_back(int64_t(v)); + series.push_back(O{{"name", ui::original_to_utf8(a.series[i].label)}, {"color", int(a.series[i].color)}, + {"active", active && i < active->size() ? (*active)[i] : cli::Json(true)}, + {"values", std::move(values)}, {"absoluteMin", int64_t(a.series[i].absolute_min)}, + {"absoluteMax", int64_t(a.series[i].absolute_max)}, {"points", A{}}}); + } + } + } catch (const std::exception& e) { + (*out)["reasonDetail"] = std::string(e.what()); // stays "not recorded" + return answer; + } + const bool filled = section == 1 ? !std::get<A>((*out)["rows"].value).empty() : !std::get<A>((*out)["series"].value).empty(); + if (filled) { + (*out)["available"] = true; + out->erase("reason"); + } + return answer; +} + cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) const { using O = cli::Json::Object; using A = cli::Json::Array; diff --git a/src/modern/app/modern_session.hpp b/src/modern/app/modern_session.hpp index c4d24ad..c645b18 100644 --- a/src/modern/app/modern_session.hpp +++ b/src/modern/app/modern_session.hpp @@ -834,9 +834,8 @@ public: // The almanac screen (index, calendar, day, match; docs/new_engine/ui-anbindung.md). Read-only. cli::Json read_almanac(const cli::Json& request) const { return query_almanac(g_, request); } // The statistics screen for the manager at the desk (docs/new_engine/ui-anbindung.md). Read-only. - cli::Json read_statistics_screen(const cli::Json& request) const { - return query_statistics_screen(g_, int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0), request); - } + // Sections 1 (transfer history) and 2 (the six curves) come from the original's own records. + cli::Json read_statistics_screen(const cli::Json& request) const; // The read queries of the new interface (docs/new_engine/ui-abfragen.md): status, leagues, // table, fixtures, squad and the statistics, for the manager at the desk. Read-only. cli::Json read(const cli::Json& request) const { diff --git a/tests/modern_season_sim.cpp b/tests/modern_season_sim.cpp index 23c59ca..dbee00c 100644 --- a/tests/modern_season_sim.cpp +++ b/tests/modern_season_sim.cpp @@ -750,7 +750,7 @@ int main(int argc, char** argv) { for (const auto& filter : {cli::Json::Object{{"section", 3}}, cli::Json::Object{{"section", 4}, {"country", 0}}, cli::Json::Object{{"section", 4}, {"country", 2}}, cli::Json::Object{{"section", 6}}, cli::Json::Object{{"section", 7}}, cli::Json::Object{{"section", 7}, {"category", 1}}, - cli::Json::Object{{"section", 8}}, cli::Json::Object{{"section", 1}}}) { + cli::Json::Object{{"section", 8}}, cli::Json::Object{{"section", 1}}, cli::Json::Object{{"section", 2}}}) { std::string answer = cli::dump_json(session.read_statistics_screen(filter)); if (answer.size() > 1500) answer = answer.substr(0, 1500) + " ..."; std::printf("statistics screen %s\n -> %s\n", cli::dump_json(filter).c_str(), answer.c_str()); diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index d92f6b4..5d345f4 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -277,6 +277,8 @@ int main(int argc, char** argv) { check(truth(at(transfers, "ok")) && !truth(at(transfers, "available")) && s(at(transfers, "reason")) == "not_recorded", "transfer history not recorded"); check(s(at(session.read_statistics_screen(O{{"section", 9}}), "error")) == "invalid_statistics_filter", "bad section"); + const J curves = session.read_statistics_screen(O{{"section", 2}}); + check(at(curves, "series").array() && at(curves, "series").array()->size() == 6, "the six curves of the original"); } } catch (const std::exception& ex) { std::fprintf(stderr, "FAIL: %s\n", ex.what()); From 2ca6b21a947762e38c88bdbd196e5af36e19da62 Mon Sep 17 00:00:00 2001 From: Claude <claude@openbmh.invalid> Date: Tue, 27 Oct 2026 09:12:34 +0100 Subject: [PATCH 3/3] Modern UI contract: contracts read, quote.request and contract.offer The contracts read lists remaining months, salary, insurance and bonuses per player and the open quote. quote.request asks a player's demands for one to four years (a draw, as at the desk); contract.offer answers applied or offer_rejected. A refused command also restores the open quote. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/new_engine/ui-anbindung.md | 3 + src/modern/app/modern_session.cpp | 92 +++++++++++++++++++++++++++++- tests/modern_ui_contract_tests.cpp | 25 ++++++++ 3 files changed, 119 insertions(+), 1 deletion(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 212a5dd..7337b0d 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -31,6 +31,7 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `lineup` | die Kaderzeilen in Reihenfolge (die ersten elf spielen) mit Rolle, die Plätze der Startelf auf der Taktiktafel (`depth` 0–19, `lane` 0–8; das JSON hat keine Kommazahlen), `manual` (Aufstellung von Hand) | | `tactics` | die acht Einstellungen (`tactic:0` Grundausrichtung bis `tactic:7` Einsatz) mit Wert und Maximum aus der EXE; die Bedeutung der Diagramm-Einstellungen 1–3, 5, 6 ist nicht belegt, daher neutrale Namen | | `training` | Bälle je Spielertyp und Trainingsbereich (1–3) mit den Grenzen, je Spieler Intensität und Schwerpunkt, ob das Training eingerichtet ist, Automatik-Bits | +| `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | | `bank` | Konto, Festgeld, Kreditrahmen, Anlagen (alles `Money`), die 12 Aktien (Kurs, Vorkurs, Bestand, bezahlt, Höchstkauf, 30 Kurse Verlauf) und die angebotenen Fonds; Kredite noch `unavailable` (folgen), der Aktientipp zieht Zufall und kommt als `quote.request` | Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team`. @@ -55,6 +56,8 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt |---|---|---| | `camp.book` | `campId`, optional `focus {condition, technique, play}` (0–15; Erholung folgt) | setzt die Schwerpunkte und bucht das Lager wie der Schreibtisch; Fehler `unknown_camp`, `invalid_focus`, `booked_this_week`, `visit_limit`, `insufficient_funds` | | `session.advance` | `{}` | der Anstoß am Schreibtisch: der Kalender läuft bis zum nächsten Schreibtisch eines Menschen, zum Saisonende oder zum Karriereende (Spiele noch ohne Live-Ansicht); `outcome` `career_ended` am Ende; Fehler `decision_pending` (eine Entscheidung am Schreibtisch fehlt, z. B. ein auslaufender Vertrag), `advance_failed` | +| `quote.request` | `kind: contract`, `playerId` | fragt die Forderungen des Spielers ab (zieht Zufall wie am Schreibtisch); `outcome: offer_pending`, die Forderungen stehen danach im `contracts`-Read | +| `contract.offer` | `quoteId`, `years` 1–4, `monthlySalary` (`Money`) | das Angebot gegen die Forderung; `outcome` `applied` (verlängert) oder `offer_rejected`; das Angebot ist danach verbraucht (`stale_quote`). Versicherung und Prämien folgen | | `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:<n>`, `fund:<n>`) und `count` | wie die Bank am Schreibtisch; Fehler `invalid_amount`, `amount_unavailable`, `invalid_share_count`, `insufficient_funds`, `investment_limit`, `invalid_fund_count` u. a. | | `lineup.commit` | `order`: Spieler-IDs in der gewünschten Reihenfolge | öffnet die Aufstellung wie am Schreibtisch und tauscht die Zeilen; Fehler `unknown_player`, `lineup_refused` (z. B. Verletzte, Ausländerregel) | | `tactics.commit` | `values`: die acht Werte | jede geänderte Einstellung über die Prüfung der Taktiktafel (eine gesetzte Grundausrichtung beendet die Steuerung durch den Assistenten); Fehler `invalid_tactic` | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index be544bd..20b2c7d 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8823,7 +8823,7 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co const std::string kind = ui_text(request, "kind"), request_id = ui_text(request, "requestId"); const int manager = context.manager; if (manager < 0 || size_t(manager) >= g_.manager_teams.size() || - (kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank")) + (kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts")) return modern::ui_read(g_, context, request); if (const std::string wanted = ui_text(request, "managerId"); !wanted.empty() && wanted != modern::ui_manager_id(g_, manager)) return modern::ui_error(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", revision, false); @@ -8853,6 +8853,38 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co {"rows", std::move(rows)}, {"positions", std::move(positions)}, {"depthMax", 19}, {"laneMax", 8}, {"manual", g_.manager_options.size() > size_t(manager) * 5 && g_.manager_options[size_t(manager) * 5] == 0}}); } + if (kind == "contracts") { + // per player: remaining months, monthly salary, insurance, the team bonuses; the open quote + // (quote.request) with the monthly demand for one to four years + ui::ContractsState c; + try { c = ui::contracts_from_game(g_, manager, revision); } catch (const std::exception&) { + return modern::ui_error(request_id, "contracts_unavailable", "Die Verträge sind hier nicht verfügbar.", revision, false); + } + static constexpr const char* kPositions[4] = {"gk", "def", "mid", "fwd"}; + A players; + for (const auto& p : c.players) { + A premiums; + for (uint8_t b : p.team_premiums) premiums.push_back(int(b)); + players.push_back(O{{"playerId", modern::ui_player_id(g_, p.player_id)}, {"name", p.name}, + {"age", p.age}, {"position", kPositions[p.position & 3]}, + {"contractRemaining", O{{"value", int(p.remaining_months)}, {"unit", "months"}}}, + {"salaryMonthly", modern::ui_money(p.current_monthly_salary)}, + {"insuranceMonths", int(p.insurance)}, {"insuranceAvailable", p.insurance_available}, + {"insuranceFee", modern::ui_money(p.insurance_fee)}, {"offerBlocked", p.offer_blocked}, + {"bonuses", std::move(premiums)}}); + } + cli::Json quote = nullptr; + if (contract_quote_ && contract_quote_->manager_slot == manager) { + A demands; + for (size_t y = 0; y < 4; ++y) + demands.push_back(O{{"years", int(y + 1)}, {"monthlyDemand", modern::ui_money(contract_quote_->demands[y])}}); + quote = O{{"id", "quote:contract-" + std::to_string(contract_quote_->quote_id)}, + {"playerId", modern::ui_player_id(g_, contract_quote_->player_id)}, {"demands", std::move(demands)}, + {"maxMonthlySalary", modern::ui_money(200000)}}; + } + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "contracts"}, {"teamId", modern::ui_team_id(g_, team)}, {"players", std::move(players)}, {"quote", std::move(quote)}}); + } if (kind == "bank") { // account, fixed deposit, credit line, the 12 stocks and 6 funds (prices in whole euros, // converted to Money); the stock tip draws a random number and is no read @@ -8951,9 +8983,12 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision const GameRandom saved_game = game_; const uint64_t previous = revision; const int saved_entry_manager = lineup_entry_manager_, saved_entry_club = lineup_entry_club_; + const auto saved_quote = contract_quote_; + const uint64_t saved_quote_id = next_contract_quote_id_, saved_contract_request = last_contract_request_id_; const auto restore = [&] { g_ = saved_state; rand_ = saved_rand; game_ = saved_game; revision = previous; lineup_entry_manager_ = saved_entry_manager, lineup_entry_club_ = saved_entry_club; // the board stays as it was + contract_quote_ = saved_quote, next_contract_quote_id_ = saved_quote_id, last_contract_request_id_ = saved_contract_request; }; cli::Json answer; std::string error; @@ -9126,6 +9161,61 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision "statistics", "almanac"}, what); if (r.kind == TurnDeskKind::CareerComplete) std::get<cli::Json::Object>(answer.value)["outcome"] = "career_ended"; + } else if (kind == "quote.request" || kind == "contract.offer") { + // quote.request {kind: "contract", playerId}: the player's demands for one to four years + // (draws a random number, as at the desk); contract.offer {quoteId, years 1-4, + // monthlySalary: Money}: the offer against that quote, accepted or rejected by the player + const int team = g_.manager_teams[size_t(manager)]; + if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es keine Verträge."); + const SquadRange range = squad_range(team); + ui::ContractRequest r; + r.request_id = last_contract_request_id_ + 1; + r.revision = revision; + r.manager_slot = manager; + r.runtime_club = team; + if (kind == "quote.request") { + if (ui_text(*payload, "kind") != "contract") return refuse("unknown_quote", "quote.request kennt bisher kind contract."); + const std::string id = ui_text(*payload, "playerId"); + for (size_t row = 0; row < range.count; ++row) { + const int p = g_.squad_slots[range.first + row] & 0x0fff; + if (p != 0x0fff && modern::ui_player_id(g_, p) == id) r.row = int(row), r.player_id = p; + } + if (r.row < 0) return refuse("unknown_player", "Spieler nicht im Kader: " + id); + r.kind = ui::ContractActionKind::request_demands; + ui::ContractActionResult result; + if (!dispatch_contract(r, revision, result, error)) { restore(); return refuse("quote_refused", error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"contracts"}, "Forderungen liegen vor."); + std::get<cli::Json::Object>(answer.value)["outcome"] = "offer_pending"; + } else { + const std::string quote = ui_text(*payload, "quoteId"); + const cli::Json* years = ui_field(*payload, "years"); + const cli::Json* salary = ui_field(*payload, "monthlySalary"); + if (!contract_quote_ || quote != "quote:contract-" + std::to_string(contract_quote_->quote_id)) + return refuse("stale_quote", "Dieses Angebot gilt nicht mehr; bitte die Forderungen neu abfragen."); + if (!years || !years->integer() || *years->integer() < 1 || *years->integer() > 4 || !salary) + return refuse("invalid_payload", "years (1 bis 4) und monthlySalary (Money) nötig."); + int64_t cents = -1; + try { cents = std::stoll(ui_text(*salary, "minor")); } catch (const std::exception&) { cents = -1; } + if (cents < 0 || cents % 100 != 0) return refuse("invalid_amount", "monthlySalary in ganzen Euro."); + r.kind = ui::ContractActionKind::submit_offer; + r.quote_id = contract_quote_->quote_id; + r.row = contract_quote_->row; + r.player_id = contract_quote_->player_id; + r.term_column = uint8_t(*years->integer() - 1); + r.demand = contract_quote_->demands[r.term_column]; + r.monthly_salary = uint32_t(cents / 100); + const size_t board = size_t(manager) * 0x840 + size_t(r.row) * 0x58; + for (size_t i = 0; i < r.proposed_bonuses.size() && board + 0x12 + i < g_.tactics.size(); ++i) + r.proposed_bonuses[i] = g_.tactics[board + 0x12 + i]; // the bonuses stay as they are + ui::ContractActionResult result; + if (!dispatch_contract(r, revision, result, error)) { restore(); return refuse("offer_refused", error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"contracts", "squad", "desktop"}, + result.feedback.empty() ? (result.accepted ? "Vertrag verlängert." : "Angebot abgelehnt.") + : result.feedback); + if (!result.accepted) std::get<cli::Json::Object>(answer.value)["outcome"] = "offer_rejected"; + } } else if (kind == "bank.commit") { // payload {action: deposit|withdraw, amount: Money} or {action: buy|sell, assetId: stock:<n>|fund:<n>, count} const std::string action = ui_text(*payload, "action"); diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 5d345f4..9dab75b 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -235,6 +235,31 @@ int main(int argc, char** argv) { check(s(at(refused, "messageType")) == "error" && modern::save_stream(session.state()) == kept && rev == before_bank + 2, "withdrawal above the deposit refused without change"); } + // contracts: demands as a quote, an offer against it, a stale quote refused + { + const J contracts = session.ui_read(O{{"kind", "contracts"}}, rev); + const auto* players = at(at(contracts, "data"), "players").array(); + check(players && !players->empty(), "contracts read"); + const std::string player = players && !players->empty() ? s(at((*players)[0], "playerId")) : ""; + const uint64_t before = rev; + const J quoted = session.ui_command(cmd("request:k1", "quote.request", O{{"kind", "contract"}, {"playerId", player}}), rev); + check(s(at(quoted, "outcome")) == "offer_pending" && rev == before + 1, "demands quoted"); + const J with_quote = session.ui_read(O{{"kind", "contracts"}}, rev); + const J& quote = at(at(with_quote, "data"), "quote"); + const auto* demands = at(quote, "demands").array(); + check(s(at(quote, "playerId")) == player && demands && demands->size() == 4, "quote with four terms"); + if (demands && demands->size() == 4) { + const std::string id = s(at(quote, "id")); + const J offer = session.ui_command(cmd("request:k2", "contract.offer", + O{{"quoteId", id}, {"years", 2}, {"monthlySalary", O{{"minor", "100"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev); + const std::string outcome = s(at(offer, "outcome")); + check(s(at(offer, "messageType")) == "command_result" && (outcome == "applied" || outcome == "offer_rejected") && + rev == before + 2, "offer answered"); + check(s(at(session.ui_command(cmd("request:k3", "contract.offer", + O{{"quoteId", id}, {"years", 2}, {"monthlySalary", O{{"minor", "100"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev), + "code")) == "stale_quote" && rev == before + 2, "a used quote is gone"); + } + } // session.advance: three kickoffs, each one revision, the date moves on { const std::string date_before = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date"));