diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 340b2c1..98d44f3 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -27,10 +27,39 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `session` | `sessionState`, `activeManagerId`, alle menschlichen Manager (ID, Platz, Name, Team, Porträt, `active`/`waiting`) | | `desktop` | Manager, Team (`TeamRef`), Kontostand (`accounts.cash`; Sparguthaben und Kredit folgen mit dem Bank-Read), nächstes Spiel, `menuAvailability` | | `squad` | ein Kader (`teamId`, sonst der eigene Verein; auch Nationalteams mit Kader): Spieler-ID, Name, Nation, Position, Rolle (`starter`/`bench`/`reserve`), Verfügbarkeit, Verletzung und Sperre in Wochen, Alter, Werte (Stärke, Kondition, Technik, Form), Fähigkeiten; für den eigenen Verein Monatsgehalt und Restlaufzeit in Monaten (fremde Vereine: `null`) | +| `camps` | Karten und Lager (Qualität 0–6, Ort, Nation, Exklusiv-Sponsor-Chance), je Lager ein bindendes Angebot für den eigenen Kader (Grundpreis + Kaderzuschlag, ohne Zufall; `allowed`, `reasonCode` `booked_this_week`/`visit_limit`/`no_club`, `exceedsCash`), Schwerpunkte, Aufenthalte der Saison, Buchung dieser Woche | +| `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 | +| `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`. -Test: `modern_ui_contract_tests` (Umschlag, IDs, Geld, Fehler, Reads ändern den Spielstand nicht; braucht Spieldaten). +## Almanach und Statistik (ohne Umschlag) + +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. + +## Commands + +`ModernSession::ui_command(request, revision)`. Ein Command (`messageType: command`) braucht `requestId`, `expectedRevision` (gleich der aktuellen Revision), `owner.managerId` (der Manager am Schreibtisch), `kind` und `payload`; `careerId` wird geprüft, wenn angegeben. Antwort: `command_result` mit `previousRevision`, `newRevision` (ein Schritt je Command), `outcome`, `changedReadKinds`, oder `error`. + +- Ein abgelehnter Command (Prüfung oder Engine) lässt Spielstand und beide Zufallsgeneratoren unverändert (`stateChanged: false`). +- Dieselbe `requestId` mit demselben Command liefert die gespeicherte Antwort (keine zweite Buchung); mit anderem Command `duplicate_request`. Gespeichert sind die letzten 64 Antworten dieses Prozesses; nach einem Neustart schützt `expectedRevision`. +- Fehler: `invalid_command`, `invalid_payload`, `wrong_career`, `stale_revision` (`retryable: true`), `no_active_manager`, `manager_not_active`, `unknown_command` und die Gründe der Engine-Aktion. + +| Command | payload | Wirkung | +|---|---|---| +| `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` | +| `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:`, `fund:`) 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` | +| `training.commit` | optional `types` (4), `areas` (9), `players [{playerId, intensity}]` | richtet das Training bei Bedarf ein, setzt erst die Senkungen, dann die Erhöhungen (jeder Zwischenstand bleibt in den Grenzen); Fehler `training_unavailable`, `unknown_player` und die Gründe der Engine | + +Test: `modern_ui_contract_tests` (Umschlag, IDs, Geld, Fehler, Reads ändern den Spielstand nicht; Commands: veraltete Revision, fremder Manager, Wiederholung, Konflikt, Ablehnung ohne Änderung, je ein angenommener und ein abgelehnter Befehl für Lager, Aufstellung, Taktik und Training; braucht Spieldaten). Noch nicht gefüllt: `nationId`, `crestAssetId` der Teams, `employments` (Amtszeiten), `strengthChoice`, `allowedCommands`. diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 1b01bbc..4baf485 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8734,4 +8734,412 @@ void ModernSession::set_loan_return_offer_presenter(LoanReturnOfferPresenter pre }; } +// --- the interface contract: commands (docs/new_engine/ui-anbindung.md) ---------------------- + +namespace { + +const cli::Json* ui_field(const cli::Json& j, const char* key) { + const auto* o = j.object(); + if (!o) return nullptr; + const auto it = o->find(key); + return it == o->end() ? nullptr : &it->second; +} + +std::string ui_text(const cli::Json& j, const char* key) { + const cli::Json* v = ui_field(j, key); + return v && v->string() ? *v->string() : std::string{}; +} + +} // namespace + +cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) const { + using O = cli::Json::Object; + using A = cli::Json::Array; + UiContext context; + context.state_revision = revision; + context.manager = int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0); + const ui::DeskState desk = desktop_projection(revision); + context.next_opponent = desk.next_opponent; + context.next_competition = desk.next_competition_label; + context.next_away = desk.next_match_away; + 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")) + 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); + const int team = g_.manager_teams[size_t(manager)]; + if (team < 0 || team >= league_clubs()) + return modern::ui_error(request_id, "no_club", "Am Schreibtisch des Bundestrainers gibt es das nicht.", revision, false); + if (kind == "lineup") { + // the squad rows in order: the first eleven start (+0x8000), the bench (+0x4000) follows; + // the starters' places on the manager's tactics board: depth 0-19, lane 0-8 + const SquadRange range = squad_range(team); + A order, rows, positions; + for (size_t row = 0; row < range.count; ++row) { + const uint16_t e = g_.squad_slots[range.first + row]; + const int p = e & 0x0fff; + if (p == 0x0fff) continue; + const std::string id = modern::ui_player_id(g_, p); + order.push_back(id); + rows.push_back(O{{"row", int(row)}, {"playerId", id}, + {"role", (e & 0x8000) ? "starter" : (e & 0x4000) ? "bench" : "reserve"}}); + const size_t at = size_t(manager) * 0x840 + row * 0x58; + if (row < 11 && at + 0x43 <= g_.tactics.size()) + positions.push_back(O{{"playerId", id}, {"depth", int(int8_t(g_.tactics[at + 0x41]))}, + {"lane", int(int8_t(g_.tactics[at + 0x42]))}}); + } + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "lineup"}, {"teamId", modern::ui_team_id(g_, team)}, {"formationId", nullptr}, {"order", std::move(order)}, + {"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 == "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 + ui::BankState b; + try { b = ui::bank_from_game(g_, exe_, revision); } catch (const std::exception&) { + return modern::ui_error(request_id, "bank_unavailable", "Die Bank ist hier nicht verfügbar.", revision, false); + } + A stocks, funds; + for (size_t i = 0; i < b.stocks.size(); ++i) { + const auto& s = b.stocks[i]; + A history; + for (uint16_t h : s.history) history.push_back(modern::ui_money(h)); + stocks.push_back(O{{"id", "stock:" + std::to_string(i)}, {"name", b.finance_stock_labels[i]}, + {"price", modern::ui_money(s.price)}, {"previousPrice", modern::ui_money(s.previous_price)}, + {"owned", int(s.owned)}, {"paid", modern::ui_money(s.paid)}, {"maxToBuy", s.max_to_buy}, + {"history", std::move(history)}}); + } + for (size_t i = 0; i < b.funds.size(); ++i) { + const auto& f = b.funds[i]; + if (f.price == 0) continue; // a fund the game does not offer + funds.push_back(O{{"id", "fund:" + std::to_string(i)}, {"name", f.name}, {"price", modern::ui_money(f.price)}, + {"owned", int(f.owned)}, {"paid", modern::ui_money(f.paid)}, {"maxToBuy", f.max_to_buy}}); + } + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "bank"}, {"teamId", modern::ui_team_id(g_, team)}, + {"accounts", O{{"cash", modern::ui_money(b.balance)}, {"deposit", modern::ui_money(b.deposit)}, + {"creditLine", modern::ui_money(b.credit_line)}, {"investments", modern::ui_money(b.investment_balance)}}}, + {"stocks", std::move(stocks)}, {"funds", std::move(funds)}, + {"credit", O{{"status", "unavailable"}, {"reasonCode", "not_yet_in_contract"}, {"missingFields", A{}}}}}); + } + if (kind == "tactics") { + // the eight settings (record +0xd2..+0xd9) with the executable's maxima; the meaning of + // settings 1-3, 5 and 6 (diagrams on the original board) is not proven, hence neutral labels + static constexpr const char* kLabels[8] = {"Grundausrichtung", "Spielzug 1", "Spielzug 2", "Spielzug 3", + "Flache oder hohe Bälle", "Aufbau links", "Aufbau rechts", "Einsatz"}; + const ui::TacticsState t = ui::tactics_from_game(g_, exe_, revision); + A controls; + for (int i = 0; i < 8; ++i) + controls.push_back(O{{"id", "tactic:" + std::to_string(i)}, + {"label", O{{"key", nullptr}, {"text", kLabels[i]}, {"locale", "de"}, {"args", O{}}}}, + {"value", int(t.values[size_t(i)])}, {"choices", A{}}, + {"range", O{{"min", 0}, {"max", int(exe_.u8(::bmh::layout::CareerSession_DispatchLiveTactic_RuntimeField + uint32_t(i)))}, {"step", 1}}}}); + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "tactics"}, {"teamId", modern::ui_team_id(g_, team)}, {"controls", std::move(controls)}, + {"assistantAttitude", int(t.assistant_attitude)}, {"liveScopeToken", nullptr}}); + } + // training: ball counts of the player types and areas (1-3; types <= 8, fitness + skill <= 4, + // the rest <= 18), per player the intensity 1-3 and the focus symbol, the automation bits + static constexpr const char* kTypes[4] = {"goalkeepers", "defence", "midfield", "attack"}; + static constexpr const char* kAreas[9] = {"fitness", "skill", "corner", "free_kick", "tackling", "pass", "shot", "speed", "game"}; + ui::TrainingState t; + try { t = ui::training_from_game(g_, exe_, revision); } catch (const std::exception&) { + return modern::ui_error(request_id, "training_unavailable", "Training gibt es in diesem Spielmodus nicht.", revision, false); + } + A types, areas, players; + for (size_t i = 0; i < 4; ++i) types.push_back(O{{"id", std::string("training:type/") + kTypes[i]}, {"allocation", int(t.types[i])}, {"min", 1}, {"max", 3}, {"unit", "balls"}}); + for (size_t i = 0; i < 9; ++i) areas.push_back(O{{"id", std::string("training:area/") + kAreas[i]}, {"allocation", int(t.areas[i])}, {"min", 1}, {"max", 3}, {"unit", "balls"}}); + for (const auto& p : t.players) + players.push_back(O{{"playerId", modern::ui_player_id(g_, p.player_id)}, {"row", p.row}, {"intensity", int(p.intensity)}, + {"focus", int(p.focus)}}); + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "training"}, {"teamId", modern::ui_team_id(g_, team)}, {"types", std::move(types)}, {"areas", std::move(areas)}, + {"limits", O{{"types", 8}, {"fitnessAndSkill", 4}, {"otherAreas", 18}}}, {"players", std::move(players)}, + {"initialized", !t.needs_initialization()}, {"automation", int(t.automation)}}); +} + +cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision) { + const std::string request_id = ui_text(request, "requestId"); + const std::string kind = ui_text(request, "kind"); + const auto refuse = [&](const std::string& code, const std::string& message, bool retryable = false) { + return modern::ui_error(request_id, code, message, revision, retryable); + }; + if (ui_text(request, "messageType") != "command" || request_id.empty()) + return refuse("invalid_command", "Kein gültiger Befehl (messageType command und requestId nötig)."); + // a repeated requestId: the stored answer for the same command, otherwise a conflict + const std::string body = cli::dump_json(request); + if (const auto it = ui_answers_.find(request_id); it != ui_answers_.end()) + return it->second.first == body ? it->second.second + : refuse("duplicate_request", "Diese requestId gehört zu einem anderen Befehl."); + if (const std::string career = ui_text(request, "careerId"); !career.empty() && career != g_.career_id) + return refuse("wrong_career", "Der Befehl gehört zu einer anderen Karriere."); + if (ui_text(request, "expectedRevision") != std::to_string(revision)) + return refuse("stale_revision", "Die Ansicht ist veraltet. Bitte neu laden.", true); + const int manager = int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0); + if (manager < 0 || size_t(manager) >= g_.manager_teams.size()) + return refuse("no_active_manager", "Kein Manager am Schreibtisch."); + const cli::Json* owner = ui_field(request, "owner"); + if (!owner || ui_text(*owner, "managerId") != modern::ui_manager_id(g_, manager)) + return refuse("manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch."); + const cli::Json* payload = ui_field(request, "payload"); + if (!payload || !payload->object()) return refuse("invalid_payload", "Der Befehl braucht ein payload-Objekt."); + + // a refused engine action leaves the state and both generators as they were + const ModernState saved_state = g_; + const WatcomRandom saved_rand = rand_; + 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 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 + }; + cli::Json answer; + std::string error; + if (kind == "camp.book") { + // payload {campId, focus?: {condition, technique, play}}: focus first (recovery follows), then the booking + const std::string camp = ui_text(*payload, "campId"); + int resort = -1; + for (size_t i = 0; i < g_.training_camps.size(); ++i) + if (g_.training_camps[i].id == camp) resort = int(i); + if (resort < 0) return refuse("unknown_camp", "Unbekanntes Trainingslager: " + camp); + ui::TrainingCampRequest r; + r.manager_slot = manager; + r.runtime_club = g_.manager_teams[size_t(manager)]; + const size_t rec = size_t(manager) * 0xb0c; + r.focus = {g_.manager_records.at(rec + 0xc1), g_.manager_records.at(rec + 0xc2), g_.manager_records.at(rec + 0xc3), + g_.manager_records.at(rec + 0xc4)}; + bool ok = true; + if (const cli::Json* focus = ui_field(*payload, "focus"); focus && focus->object()) { + std::array f = r.focus; + const char* keys[3] = {"condition", "technique", "play"}; + for (int k = 0; k < 3; ++k) { + const cli::Json* v = ui_field(*focus, keys[k]); + if (!v || !v->integer() || *v->integer() < 0 || *v->integer() > 15) return refuse("invalid_focus", "Schwerpunkte 0 bis 15."); + f[size_t(k)] = uint8_t(*v->integer()); + } + f[3] = uint8_t(15 - (unsigned(f[0]) + f[1] + f[2]) / 3); + if (f != r.focus) { + r.kind = ui::TrainingCampRequestKind::set_focus; + r.focus = f; + r.revision = revision; + ok = dispatch_training_camp(r, revision, error); + } + } + if (ok) { + r.kind = ui::TrainingCampRequestKind::book; + r.resort = resort; + r.revision = revision; + ok = dispatch_training_camp(r, revision, error); + } + if (!ok) { + restore(); + return refuse(error, "Buchung nicht möglich: " + error); + } + // an engine step after the booking: one revision for the whole command + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"desktop", "camps", "squad"}, + "Trainingslager gebucht: " + g_.training_camps[size_t(resort)].name); + } else if (kind == "tactics.commit") { + // payload {values: [8 numbers]}: every changed setting through the tactics board's own check + const cli::Json* values = ui_field(*payload, "values"); + const auto* list = values ? values->array() : nullptr; + if (!list || list->size() != 8) return refuse("invalid_payload", "values braucht acht Taktikwerte."); + const ui::TacticsState current = ui::tactics_from_game(g_, exe_, revision); + bool ok = true; + for (int i = 0; i < 8 && ok; ++i) { + const cli::Json& v = (*list)[size_t(i)]; + if (!v.integer()) { restore(); return refuse("invalid_payload", "Taktikwerte sind ganze Zahlen."); } + if (*v.integer() == current.values[size_t(i)]) continue; + ui::TacticsRequest r; + r.kind = ui::TacticsRequestKind::set_tactic; + r.manager_slot = manager; + r.runtime_club = g_.manager_teams[size_t(manager)]; + r.revision = revision; + r.index = i; + r.desired_value = int(*v.integer()); + if (i == 0) r.desired_assistant_attitude = 0; // a set attitude ends the assistant's control + ok = dispatch_tactics(r, revision, error); + } + if (!ok) { restore(); return refuse("invalid_tactic", error); } + if (revision != previous) revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"tactics"}, "Taktik übernommen."); + } else if (kind == "training.commit") { + // payload {types?: [4 x 1-3], areas?: [9 x 1-3], players?: [{playerId, intensity 1-3}]} + ui::TrainingState current; + try { current = ui::training_from_game(g_, exe_, revision); } catch (const std::exception&) { + return refuse("training_unavailable", "Training gibt es in diesem Spielmodus nicht."); + } + auto send = [&](ui::TrainingRequest r) { + r.manager_slot = manager; + r.runtime_club = g_.manager_teams[size_t(manager)]; + r.revision = revision; + if (!dispatch_training(r, revision, error)) return false; + current = ui::training_from_game(g_, exe_, revision); + return true; + }; + bool ok = true; + if (current.needs_initialization()) { // the screen initializes itself on first use + ui::TrainingRequest r; + r.kind = ui::TrainingRequestKind::initialize; + r.desired_types = current.types, r.desired_areas = current.areas, r.desired_automation = 0x9f; + ok = send(r); + } + // targets: lower values first, then higher, so every step keeps the limits + // (types sum <= 8, fitness + skill <= 4, the other areas <= 18) + const auto targets = [&](const char* key, size_t n, std::vector& out) { + out.clear(); + const cli::Json* v = ui_field(*payload, key); + if (!v) return true; + const auto* a = v->array(); + if (!a || a->size() != n) return false; + for (const auto& x : *a) { + if (!x.integer() || *x.integer() < 1 || *x.integer() > 3) return false; + out.push_back(int(*x.integer())); + } + return true; + }; + std::vector types, areas; + if (!targets("types", 4, types) || !targets("areas", 9, areas)) { + restore(); + return refuse("invalid_payload", "types (4) und areas (9) mit Werten 1 bis 3."); + } + for (int pass = 0; pass < 2 && ok; ++pass) + for (int group = 0; group < 2 && ok; ++group) { + const std::vector& want = group == 0 ? types : areas; + for (size_t i = 0; i < want.size() && ok; ++i) { + const int now = group == 0 ? current.types[i] : current.areas[i]; + if (want[i] == now || (pass == 0) != (want[i] < now)) continue; + ui::TrainingRequest r; + r.kind = group == 0 ? ui::TrainingRequestKind::set_type : ui::TrainingRequestKind::set_area; + r.index = int(i), r.value = want[i]; + r.desired_types = current.types, r.desired_areas = current.areas; + (group == 0 ? r.desired_types[i] : r.desired_areas[i]) = uint8_t(want[i]); + r.desired_automation = uint8_t(current.automation & ~uint8_t(1u << (group == 0 ? 1 : 2))); + ok = send(r); + } + } + if (const cli::Json* players = ui_field(*payload, "players"); ok && players) { + const auto* list = players->array(); + if (!list) { restore(); return refuse("invalid_payload", "players ist eine Liste."); } + for (const auto& p : *list) { + const std::string id = ui_text(p, "playerId"); + const cli::Json* intensity = ui_field(p, "intensity"); + if (!intensity || !intensity->integer()) { restore(); return refuse("invalid_payload", "intensity fehlt."); } + const auto row = std::find_if(current.players.begin(), current.players.end(), [&](const auto& t) { + return modern::ui_player_id(g_, t.player_id) == id; + }); + if (row == current.players.end()) { restore(); return refuse("unknown_player", "Spieler nicht im Kader: " + id); } + if (row->intensity == *intensity->integer()) continue; + ui::TrainingRequest r; + r.kind = ui::TrainingRequestKind::set_player_intensity; + r.index = row->row, r.player_id = row->player_id, r.value = int(*intensity->integer()); + r.desired_types = current.types, r.desired_areas = current.areas; + r.desired_automation = uint8_t(current.automation & ~uint8_t(1u << 3)); + if (!(ok = send(r))) break; + } + } + if (!ok) { restore(); return refuse(error.empty() ? "invalid_training" : error, "Training nicht übernommen: " + error); } + if (revision != previous) revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"training"}, "Training übernommen."); + } else if (kind == "session.advance") { + // payload {}: the kickoff of the desk - the calendar runs (matches without live view) to the + // next desk of a human manager, the season end desk or the end of the career + ui::DeskRequest kickoff; + kickoff.kind = ui::DeskRequestKind::advance_turn; + kickoff.manager_slot = manager; + kickoff.revision = revision; + const TurnAdvanceResult r = dispatch_kickoff(kickoff, revision, error); + if (r.kind == TurnDeskKind::Failed || r.kind == TurnDeskKind::WaitingAtDesk) { + restore(); + const std::string reason = r.reason.empty() ? error : r.reason; + return refuse(r.kind == TurnDeskKind::WaitingAtDesk ? "decision_pending" : "advance_failed", + "Weiter nicht möglich: " + reason); + } + modern::ensure_ui_identities(g_); + revision = previous + 1; + const char* what = r.kind == TurnDeskKind::SeasonEndDesk ? "Saisonende." : r.kind == TurnDeskKind::CareerComplete + ? "Die Karriere ist zu Ende." : "Weiter zum nächsten Termin."; + answer = modern::ui_command_result(request_id, previous, revision, + {"session", "desktop", "squad", "lineup", "tactics", "training", "camps", "bank", + "statistics", "almanac"}, what); + if (r.kind == TurnDeskKind::CareerComplete) + std::get(answer.value)["outcome"] = "career_ended"; + } else if (kind == "bank.commit") { + // payload {action: deposit|withdraw, amount: Money} or {action: buy|sell, assetId: stock:|fund:, count} + const std::string action = ui_text(*payload, "action"); + ui::BankRequest r; + r.manager_slot = manager, r.runtime_club = g_.manager_teams[size_t(manager)], r.revision = revision; + if (action == "deposit" || action == "withdraw") { + const cli::Json* amount = ui_field(*payload, "amount"); + const std::string minor = amount ? ui_text(*amount, "minor") : std::string{}; + int64_t cents = 0; + try { cents = minor.empty() ? 0 : std::stoll(minor); } catch (const std::exception&) { cents = 0; } + if (cents <= 0 || cents % 100 != 0 || cents / 100 > INT32_MAX) + return refuse("invalid_amount", "amount ist ein positiver Betrag in ganzen Euro (Money)."); + r.kind = ui::BankRequestKind::move_to_deposit; + r.amount = int32_t(cents / 100) * (action == "deposit" ? 1 : -1); + } else if (action == "buy" || action == "sell") { + const std::string asset = ui_text(*payload, "assetId"); + const cli::Json* count = ui_field(*payload, "count"); + const bool stock = asset.starts_with("stock:"), fund = asset.starts_with("fund:"); + if ((!stock && !fund) || !count || !count->integer()) return refuse("invalid_payload", "assetId und count nötig."); + try { r.asset_index = std::stoi(asset.substr(stock ? 6 : 5)); } catch (const std::exception&) { return refuse("unknown_asset", asset); } + r.count = int(*count->integer()); + r.kind = stock ? (action == "buy" ? ui::BankRequestKind::buy_shares : ui::BankRequestKind::sell_shares) + : (action == "buy" ? ui::BankRequestKind::buy_fund : ui::BankRequestKind::sell_fund); + } else { + return refuse("invalid_payload", "action ist deposit, withdraw, buy oder sell."); + } + if (!dispatch_bank(r, revision, error)) { restore(); return refuse(error, "Bankauftrag abgelehnt: " + error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"bank", "desktop"}, "Bankauftrag ausgeführt."); + } else if (kind == "lineup.commit") { + // payload {order: [player ids]}: the squad in this order (the first eleven start); the + // board opens as on the desk (the human line-up path), then rows are swapped into place + const cli::Json* order = ui_field(*payload, "order"); + const auto* ids = order ? order->array() : nullptr; + if (!ids || ids->empty()) return refuse("invalid_payload", "order braucht die Spieler-IDs."); + const int team = g_.manager_teams[size_t(manager)]; + const SquadRange range = squad_range(team); + ui::LineupRequest prepare; + prepare.kind = ui::LineupRequestKind::prepare_lineup; + prepare.manager_slot = manager, prepare.runtime_club = team, prepare.revision = revision; + bool ok = dispatch_lineup(prepare, revision, error); + for (size_t want = 0; ok && want < ids->size(); ++want) { + const std::string id = (*ids)[want].string() ? *(*ids)[want].string() : std::string{}; + size_t at = range.count; + 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) at = row; + } + if (at == range.count || want >= range.count) { error = "unknown_player"; ok = false; break; } + if (at == want) continue; + ui::LineupRequest swap; + swap.kind = ui::LineupRequestKind::swap_players; + swap.manager_slot = manager, swap.runtime_club = team, swap.revision = revision; + swap.first_row = int(want), swap.second_row = int(at); + swap.first_slot = g_.squad_slots[range.first + want], swap.second_slot = g_.squad_slots[range.first + at]; + swap.first_player = (swap.first_slot & 0x0fff) == 0x0fff ? -1 : swap.first_slot & 0x0fff; + swap.second_player = swap.second_slot & 0x0fff; + ok = dispatch_lineup(swap, revision, error); + } + if (!ok) { restore(); return refuse(error == "unknown_player" ? "unknown_player" : "lineup_refused", error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"lineup", "squad"}, "Aufstellung übernommen."); + } else { + return refuse("unknown_command", "Unbekannter Befehl: " + kind); + } + ui_answers_[request_id] = {body, answer}; + ui_answer_order_.push_back(request_id); + if (ui_answer_order_.size() > 64) { + ui_answers_.erase(ui_answer_order_.front()); + ui_answer_order_.erase(ui_answer_order_.begin()); + } + return answer; +} + } // namespace bmh::modern::app diff --git a/src/modern/app/modern_session.hpp b/src/modern/app/modern_session.hpp index 1eeaa59..6c27181 100644 --- a/src/modern/app/modern_session.hpp +++ b/src/modern/app/modern_session.hpp @@ -831,6 +831,8 @@ public: // The game statistics menu (docs/new_engine/statistik.md): winners by season, player // statistics per competition. Read-only; answers {ok, ...} or {ok: false, error}. 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 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 { @@ -838,16 +840,13 @@ public: } // The interface contract (docs/new_engine/ui-anbindung.md): a read in the contract's envelope // for the manager at the desk, at the revision the caller holds. Read-only. - cli::Json ui_read(const cli::Json& request, uint64_t revision) const { - UiContext context; - context.state_revision = revision; - context.manager = int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0); - const ui::DeskState desk = desktop_projection(revision); - context.next_opponent = desk.next_opponent; - context.next_competition = desk.next_competition_label; - context.next_away = desk.next_match_away; - return modern::ui_read(g_, context, request); - } + // Kinds of the session itself: lineup, tactics, training; the others in ui_contract.cpp. + cli::Json ui_read(const cli::Json& request, uint64_t revision) const; + // A command of the interface contract: checks career, expectedRevision and owner, runs the + // engine action and answers command_result or error. A refused command leaves the state and + // both generators untouched; a repeated requestId with the same command gets the stored + // answer, with another command duplicate_request. Kinds so far: camp.book. + cli::Json ui_command(const cli::Json& request, uint64_t& revision); ModernState& state() { return g_; } const TurnResultSnapshot& last_turn_results() const { return turn_driver_.last_results; } // Owned presentation for the event completed by the last accepted kickoff. @@ -996,6 +995,10 @@ private: uint64_t original_rand_calls = 0, original_game_calls = 0, context_revision = 0; }; std::optional manager_join_; + // ui_command: answers by requestId (the command as JSON, the answer) for repeated commands, + // the last 64 in this process; after a restart expectedRevision prevents a second booking. + std::map> ui_answers_; + std::vector ui_answer_order_; std::filesystem::path data_directory_; LeImage exe_; diff --git a/src/modern/content/statistics.cpp b/src/modern/content/statistics.cpp index 05cf2c4..3acb242 100644 --- a/src/modern/content/statistics.cpp +++ b/src/modern/content/statistics.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -268,4 +269,133 @@ cli::Json query_statistics(const ModernState& g, const cli::Json& request) { } } +// --- the almanac view of the Modern UI (DataSource::read_almanac; the demo's request kinds) ------ + +namespace { + +J almanac_person(const AlmanacSeason& s, uint16_t player) { + if (player == kAlmanacNone || player >= s.players.size()) return nullptr; + const AlmanacPlayer& p = s.players[player]; + return O{{"id", p.id}, {"name", player_name(p)}}; +} + +J almanac_side(const ModernState& g, const AlmanacSeason& s, uint16_t club, int8_t manager) { + J m = nullptr; + if (manager >= 0 && size_t(manager) < s.managers.size()) { + const AlmanacManager& a = s.managers[size_t(manager)]; + std::string id = a.index >= 0 && size_t(a.index) < g.manager_ids.size() ? g.manager_ids[size_t(a.index)] : std::string{}; + if (id.empty()) id = "manager:slot-" + std::to_string(a.index); + m = O{{"id", id}, {"name", a.name}}; + } + return O{{"id", s.clubs[club].id}, {"name", s.clubs[club].name}, {"crest", nullptr}, {"manager", std::move(m)}}; +} + +std::string match_id(const AlmanacSeason& s, size_t index) { + return "match:" + std::to_string(s.start_year) + "-" + std::to_string(index); +} + +// One recorded match in the form the almanac screen reads. The score after 90 minutes and the +// extra time are told apart by the goal minutes; a line-up shorter than eleven is not known (null). +J almanac_match(const ModernState& g, const AlmanacSeason& s, size_t index) { + static constexpr const char* kKinds[8] = {"goal", "yellow", "red", "second_yellow", "injury", "substitution", "shootout", "miss"}; + const AlmanacMatch& m = s.matches[index]; + const Competition c = competition_of(g, s, m); + const std::string type = m.type == 0 ? "league" : m.type - 1 == 10 ? "friendly" : "cup"; + int regulation[2] = {0, 0}; + for (const auto& e : m.events) + if (e.kind == AlmanacEventKind::Goal && e.minute <= 90 && e.side < 2) ++regulation[e.side]; + const bool extra = m.decided >= 1, shootout = m.decided == 2; + J lineups = O{}; + for (int side = 0; side < 2; ++side) { + const auto& l = m.lineup[size_t(side)]; + if (l.size() < 11) { + std::get(lineups.value)[side ? "away" : "home"] = nullptr; + continue; + } + A starters, bench; + for (size_t i = 0; i < l.size(); ++i) (i < 11 ? starters : bench).push_back(almanac_person(s, l[i])); + std::get(lineups.value)[side ? "away" : "home"] = O{{"starters", std::move(starters)}, {"bench", std::move(bench)}}; + } + A events; + for (const auto& e : m.events) + events.push_back(O{{"kind", kKinds[size_t(e.kind) & 7]}, {"minute", int(e.minute)}, {"side", e.side ? "away" : "home"}, + {"player", almanac_person(s, e.player)}, {"other", almanac_person(s, e.other)}, {"detail", int(e.detail)}}); + return O{{"id", match_id(s, index)}, {"date", iso_date(m.date, s.display_start_year)}, {"season", season_label(s.start_year)}, + {"competition", O{{"id", c.id}, {"name", c.name}, {"type", type}}}, {"round", int(m.round)}, + {"home", almanac_side(g, s, m.home, m.home_manager)}, {"away", almanac_side(g, s, m.away, m.away_manager)}, + {"result", O{{"regulation", extra ? J(A{J(regulation[0]), J(regulation[1])}) : J(A{J(int(m.home_goals)), J(int(m.away_goals))})}, + {"extra", extra ? J(A{J(int(m.home_goals) - regulation[0]), J(int(m.away_goals) - regulation[1])}) : J(nullptr)}, + {"penalties", shootout ? J(A{J(int(m.home_shootout)), J(int(m.away_shootout))}) : J(nullptr)}, + {"final", A{J(int(m.home_goals)), J(int(m.away_goals))}}, {"extra_played", extra}, {"penalties_played", shootout}}}, + {"referee", m.referee > 0 && m.referee < s.referees.size() ? J(s.referees[m.referee]) : J(nullptr)}, + {"attendance", int64_t(m.attendance)}, + {"weather", O{{"temperature", int(m.temperature)}, {"rain", int(m.rain)}}}, + {"lineups", std::move(lineups)}, {"events", std::move(events)}}; +} + +} // namespace + +cli::Json query_almanac(const ModernState& g, const cli::Json& request) { + const J* kind = field(request, "kind"); + if (!kind || !kind->string()) return error("invalid_almanac_request"); + try { + const auto seasons = seasons_of(g); + const std::string k = *kind->string(); + if (k == "index") { + std::set years; + std::string first, last; + size_t count = 0; + for (const auto& s : seasons) + for (const auto& m : s.matches) { + const std::string d = iso_date(m.date, s.display_start_year); + years.insert(std::stoi(d.substr(0, 4))); + if (first.empty() || d < first) first = d; + if (d > last) last = d; + ++count; + } + A listed; + for (int y : years) listed.push_back(y); + return O{{"ok", true}, {"years", std::move(listed)}, {"match_count", int64_t(count)}, + {"first_date", first.empty() ? J(nullptr) : J(first)}, {"last_date", last.empty() ? J(nullptr) : J(last)}}; + } + if (k == "calendar") { + const J* year = field(request, "year"); + if (!year || !year->integer()) return error("invalid_almanac_request"); + std::map> days; + for (const auto& s : seasons) + for (size_t i = 0; i < s.matches.size(); ++i) { + const AlmanacMatch& m = s.matches[i]; + const std::string d = iso_date(m.date, s.display_start_year); + if (std::stoi(d.substr(0, 4)) != *year->integer()) continue; + auto& day = days[d]; + ++day.first; + if (m.decided >= 1 || m.home_goals + m.away_goals >= 4) day.second.push_back(match_id(s, i)); + } + A listed; + for (auto& [d, day] : days) listed.push_back(O{{"date", d}, {"count", day.first}, {"highlights", std::move(day.second)}}); + return O{{"ok", true}, {"year", *year->integer()}, {"days", std::move(listed)}}; + } + if (k == "day") { + const J* date = field(request, "date"); + if (!date || !date->string()) return error("invalid_almanac_request"); + A matches; + for (const auto& s : seasons) + for (size_t i = 0; i < s.matches.size(); ++i) + if (iso_date(s.matches[i].date, s.display_start_year) == *date->string()) matches.push_back(almanac_match(g, s, i)); + return O{{"ok", true}, {"date", *date->string()}, {"matches", std::move(matches)}}; + } + if (k == "match") { + const J* id = field(request, "id"); + if (!id || !id->string()) return error("invalid_almanac_request"); + for (const auto& s : seasons) + for (size_t i = 0; i < s.matches.size(); ++i) + if (match_id(s, i) == *id->string()) return O{{"ok", true}, {"match", almanac_match(g, s, i)}}; + return error("almanac_match_not_found"); + } + return error("invalid_almanac_request"); + } catch (const std::exception&) { + return error("almanac_unavailable"); + } +} + } // namespace bmh::modern diff --git a/src/modern/content/statistics.hpp b/src/modern/content/statistics.hpp index ef17858..b3d5dd3 100644 --- a/src/modern/content/statistics.hpp +++ b/src/modern/content/statistics.hpp @@ -19,4 +19,13 @@ namespace bmh::modern { cli::Json query_statistics(const ModernState& g, const cli::Json& request); +// The almanac screen of the Modern UI (DataSource::read_almanac), the request kinds of its demo: +// {kind: "index"} years with matches, their number, first and last date +// {kind: "calendar", year} the match days of a year with counts and highlights +// {kind: "day", date} all matches of a day (ISO date) +// {kind: "match", id} one match ("match:-") +// A match: date, season, competition, round, both sides (manager if human), result split into +// regulation / extra time / penalties, referee, attendance, weather, line-ups, events. +cli::Json query_almanac(const ModernState& g, const cli::Json& request); + } // namespace bmh::modern diff --git a/src/modern/content/ui_contract.cpp b/src/modern/content/ui_contract.cpp index 90eb8ed..1ecefd5 100644 --- a/src/modern/content/ui_contract.cpp +++ b/src/modern/content/ui_contract.cpp @@ -12,6 +12,7 @@ #include "game/table.hpp" #include "modern/content/world_package.hpp" #include "modern/game/almanac.hpp" +#include "modern/game/desk_actions.hpp" namespace bmh::modern { @@ -253,6 +254,56 @@ J squad_data(const ModernState& g, const UiContext& c, int team, const std::stri return O{{"kind", "squad"}, {"team", team_ref(g, team, today)}, {"players", std::move(players)}}; } +// The training camps (docs/new_engine/trainingslager.md): catalogue, the price for the own +// squad (base price + 5000 per player, no random draw: a binding quote), focus and bookings. +J camps_data(const ModernState& g, const UiContext& c, const std::string& revision) { + const size_t rec = size_t(c.manager) * kRecord; + const TrainingCampBookingBlock block = training_camp_booking_block(g, c.manager); + const char* reason = block == TrainingCampBookingBlock::booked_this_week ? "booked_this_week" + : block == TrainingCampBookingBlock::visit_limit ? "visit_limit" + : block == TrainingCampBookingBlock::invalid_request ? "no_club" + : nullptr; + const int64_t cash = money_of(g, c.manager); + A maps; + for (const CampMap& m : g.camp_maps) + maps.push_back(O{{"id", m.id}, {"name", text(m.name)}, {"guiAssetKey", "gui:map/" + (m.id.starts_with("map:") ? m.id.substr(4) : m.id)}, + {"width", m.width ? J(*m.width) : J(nullptr)}, {"height", m.height ? J(*m.height) : J(nullptr)}}); + A camps; + for (size_t i = 0; i < g.training_camps.size(); ++i) { + const TrainingCamp& t = g.training_camps[i]; + J quote = nullptr; + if (block != TrainingCampBookingBlock::invalid_request) { + const int64_t price = training_camp_price(g, c.manager, int(i)); + const int64_t base = t.base_price; + const char* blocked = reason ? reason : nullptr; + // book_money allows the credit line too; the read names only the plain case + quote = O{{"id", "quote:camp-" + revision + "-" + std::to_string(i)}, {"ownerManagerId", manager_id(g, c.manager)}, + {"teamId", team_id(g, team_of(g, c.manager))}, {"expectedRevision", revision}, + {"scopeId", "scope:desk-" + revision + "-" + std::to_string(c.manager)}, {"expiresOn", nullptr}, + {"total", ui_money(price)}, {"totalBasis", "immediate"}, {"chargesNow", ui_money(price)}, + {"breakdown", A{O{{"code", "base"}, {"amount", ui_money(base)}}, + O{{"code", "squad"}, {"amount", ui_money(price - base)}}}}, + {"allowed", blocked == nullptr}, {"reasonCode", blocked ? J(blocked) : J(nullptr)}, + {"exceedsCash", price > cash}}; + } + camps.push_back(O{{"id", t.id}, {"mapId", t.map}, {"name", text(t.name)}, {"place", t.place}, + {"nationId", t.country.empty() ? J(nullptr) : J(t.country)}, + {"position", t.x && t.y ? J(O{{"x", *t.x}, {"y", *t.y}}) : J(nullptr)}, + {"quality", O{{"pitch", int(t.quality[0])}, {"fitness", int(t.quality[1])}, + {"catering", int(t.quality[2])}, {"lodging", int(t.quality[3])}}}, + {"guiImageKey", "gui:camp/" + std::to_string(i)}, {"worldImageAssetId", nullptr}, + {"sponsorChance", t.sponsor_chance}, {"quote", std::move(quote)}}); + } + const uint8_t stays = rec + 0x21f < g.manager_records.size() ? g.manager_records[rec + 0x21f] : 0; + O focus; + if (rec + 0xc4 < g.manager_records.size()) + focus = O{{"condition", int(g.manager_records[rec + 0xc1])}, {"technique", int(g.manager_records[rec + 0xc2])}, + {"play", int(g.manager_records[rec + 0xc3])}, {"recovery", int(g.manager_records[rec + 0xc4])}}; + return O{{"kind", "camps"}, {"maps", std::move(maps)}, {"camps", std::move(camps)}, {"focus", std::move(focus)}, + {"staysThisSeason", int(stays & 0x7f)}, {"staysLimit", 3}, {"bookedThisWeek", (stays & 0x80) != 0}, + {"availability", reason ? unavailable(reason) : available()}}; +} + } // namespace void ensure_ui_identities(ModernState& g) { @@ -269,10 +320,39 @@ void ensure_ui_identities(ModernState& g) { if (id.empty()) id = "manager:" + std::to_string(++g.manager_serial); } +cli::Json ui_command_result(const std::string& request_id, uint64_t previous, uint64_t next, + const std::vector& changed_reads, const std::string& feedback) { + A changed; + for (const auto& k : changed_reads) changed.push_back(k); + return O{{"messageType", "command_result"}, {"requestId", request_id}, {"accepted", true}, + {"previousRevision", std::to_string(previous)}, {"newRevision", std::to_string(next)}, + {"outcome", next == previous ? "no_change" : "applied"}, {"changedReadKinds", std::move(changed)}, + {"ownershipChange", nullptr}, {"feedback", text(feedback)}}; +} + +cli::Json ui_error(const std::string& request_id, const std::string& code, const std::string& message, + uint64_t revision, bool retryable) { + return O{{"messageType", "error"}, {"requestId", request_id}, {"code", code}, {"message", text(message)}, + {"currentRevision", std::to_string(revision)}, {"retryable", retryable}, {"stateChanged", false}}; +} + +std::string ui_manager_id(const ModernState& g, int manager) { return manager_id(g, manager); } + cli::Json ui_money(int64_t euros) { return O{{"minor", std::to_string(euros * 100)}, {"currency", "EUR"}, {"minorUnits", 2}}; } +cli::Json ui_snapshot(const ModernState& g, const UiContext& c, const std::string& request_id, cli::Json data) { + return snapshot(request_id, meta(g, c), std::move(data)); +} + +std::string ui_team_id(const ModernState& g, int team) { return team_id(g, team); } + +std::string ui_player_id(const ModernState& g, int player) { + std::string id = entry(g.world_player_id, size_t(player)); + return id.empty() ? "player:legacy-" + std::to_string(player) : id; +} + cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& request) { const std::string request_id = text_field(request, "requestId"); const std::string kind = text_field(request, "kind"); @@ -286,6 +366,7 @@ cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& req const std::string today = *std::get(m.value).at("date").string(); if (kind == "session") return snapshot(request_id, std::move(m), session_data(g, c)); if (kind == "desktop") return snapshot(request_id, std::move(m), desktop_data(g, c, today)); + if (kind == "camps") return snapshot(request_id, std::move(m), camps_data(g, c, std::to_string(c.state_revision))); if (kind == "squad") { const int team = requested_team(g, c, request); if (team < 0 || !fields_players(g, team)) diff --git a/src/modern/content/ui_contract.hpp b/src/modern/content/ui_contract.hpp index d6b23d9..5937f02 100644 --- a/src/modern/content/ui_contract.hpp +++ b/src/modern/content/ui_contract.hpp @@ -17,6 +17,7 @@ #include #include +#include #include "cli/json.hpp" #include "modern/game/modern_state.hpp" @@ -46,4 +47,16 @@ cli::Json ui_money(int64_t euros); cli::Json ui_read(const ModernState& g, const UiContext& context, const cli::Json& request); +// The parts of a command answer the session puts together (ModernSession::ui_command). +cli::Json ui_command_result(const std::string& request_id, uint64_t previous, uint64_t next, + const std::vector& changed_reads, const std::string& feedback); +cli::Json ui_error(const std::string& request_id, const std::string& code, const std::string& message, + uint64_t revision, bool retryable); +// The contract id of a manager slot ("manager:"). +std::string ui_manager_id(const ModernState& g, int manager); +// Reads the session answers itself (they need the executable's tables): data in the envelope. +cli::Json ui_snapshot(const ModernState& g, const UiContext& context, const std::string& request_id, cli::Json data); +std::string ui_team_id(const ModernState& g, int team); +std::string ui_player_id(const ModernState& g, int player); + } // namespace bmh::modern diff --git a/tests/modern_season_sim.cpp b/tests/modern_season_sim.cpp index 31c3718..7d99fb0 100644 --- a/tests/modern_season_sim.cpp +++ b/tests/modern_season_sim.cpp @@ -743,7 +743,7 @@ int main(int argc, char** argv) { read({{"kind", "squad"}}); read({{"kind", "table"}, {"league", 42}}); // the interface contract (docs/new_engine/ui-anbindung.md) - for (const char* kind : {"session", "desktop", "squad", "nonsense"}) { + for (const char* kind : {"session", "desktop", "squad", "camps", "nonsense"}) { 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()); } diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 659e4aa..4930c19 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -31,6 +31,7 @@ const J& at(const J& j, const char* key) { return it == o->end() ? none : it->second; } std::string s(const J& j) { return j.string() ? *j.string() : std::string{}; } +bool truth(const J& j) { const bool* b = std::get_if(&j.value); return b && *b; } } // namespace int main(int argc, char** argv) { @@ -105,6 +106,170 @@ int main(int argc, char** argv) { // money check(s(at(modern::ui_money(15), "minor")) == "1500" && s(at(modern::ui_money(-3), "minor")) == "-300", "money"); + + // camps: read with binding quotes, then camp.book as the first command + const J camps = session.ui_read(O{{"kind", "camps"}}, revision); + const auto* list = at(at(camps, "data"), "camps").array(); + check(list && list->size() == session.state().training_camps.size() && !list->empty(), "camp catalogue"); + const std::string camp_id = list && !list->empty() ? s(at((*list)[0], "id")) : ""; + const std::string price = list && !list->empty() ? s(at(at(at((*list)[0], "quote"), "total"), "minor")) : ""; + check(list && !list->empty() && truth(at(at((*list)[0], "quote"), "allowed")), "camp quote allowed"); + uint64_t rev = revision; + const auto command = [&](const std::string& id, const std::string& expected, const std::string& manager, + const std::string& camp) { + return J(O{{"messageType", "command"}, {"requestId", id}, {"expectedRevision", expected}, + {"owner", O{{"managerId", manager}}}, {"kind", "camp.book"}, {"payload", O{{"campId", camp}}}}); + }; + const auto unchanged = modern::save_stream(session.state()); + check(s(at(session.ui_command(command("request:c1", "999", "manager:1", camp_id), rev), "code")) == "stale_revision", + "stale revision refused"); + check(s(at(session.ui_command(command("request:c2", std::to_string(rev), "manager:9", camp_id), rev), "code")) == + "manager_not_active", "foreign owner refused"); + check(s(at(session.ui_command(command("request:c3", std::to_string(rev), "manager:1", "resort:none"), rev), "code")) == + "unknown_camp", "unknown camp refused"); + check(rev == revision && modern::save_stream(session.state()) == unchanged, "refused commands change nothing"); + const int64_t cash_before = *at(session.read(O{{"kind", "status"}}), "money").integer(); + const J booked = session.ui_command(command("request:c4", std::to_string(rev), "manager:1", camp_id), rev); + check(s(at(booked, "messageType")) == "command_result" && s(at(booked, "newRevision")) == std::to_string(revision + 1) && + rev == revision + 1, "camp booked, one revision"); + const int64_t cash_after = *at(session.read(O{{"kind", "status"}}), "money").integer(); + check(std::to_string((cash_before - cash_after) * 100) == price, "the quoted price was charged"); + const J again = session.ui_command(command("request:c4", std::to_string(revision), "manager:1", camp_id), rev); + check(cli::dump_json(again) == cli::dump_json(booked) && rev == revision + 1 && + *at(session.read(O{{"kind", "status"}}), "money").integer() == cash_after, "repeated request answered, not booked twice"); + check(s(at(session.ui_command(command("request:c4", std::to_string(rev), "manager:1", camp_id), rev), "code")) == + "duplicate_request", "same id, other command"); + const auto after_booking = modern::save_stream(session.state()); + check(s(at(session.ui_command(command("request:c5", std::to_string(rev), "manager:1", camp_id), rev), "code")) == + "booked_this_week" && modern::save_stream(session.state()) == after_booking && rev == revision + 1, + "second booking in a week refused without change"); + const J after = session.ui_read(O{{"kind", "camps"}}, rev); + check(at(at(after, "data"), "staysThisSeason").integer() && *at(at(after, "data"), "staysThisSeason").integer() == 1 && + truth(at(at(after, "data"), "bookedThisWeek")), "camp read shows the stay"); + // lineup, tactics, training: read, one accepted and one refused command each + const auto cmd = [&](const std::string& id, const char* kind, J payload) { + return J(O{{"messageType", "command"}, {"requestId", id}, {"expectedRevision", std::to_string(rev)}, + {"owner", O{{"managerId", "manager:1"}}}, {"kind", kind}, {"payload", std::move(payload)}}); + }; + const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev); + const auto* order = at(at(lineup, "data"), "order").array(); + check(order && order->size() >= 12 && at(at(lineup, "data"), "positions").array() && + at(at(lineup, "data"), "positions").array()->size() == 11, "lineup read"); + if (order && order->size() >= 12) { + J::Array wanted = *order; + std::swap(wanted[0], wanted[1]); + std::swap(wanted[10], wanted[11]); + const uint64_t before_lineup = rev; + const J done = session.ui_command(cmd("request:l1", "lineup.commit", O{{"order", wanted}}), rev); + if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "lineup: %s\n", cli::dump_json(done).c_str()); + const J reread = session.ui_read(O{{"kind", "lineup"}}, rev); + const auto* now = at(at(reread, "data"), "order").array(); + if (now && (s((*now)[0]) != s(wanted[0]) || s((*now)[10]) != s(wanted[10]) || rev != before_lineup + 1)) + std::fprintf(stderr, "lineup: rev %llu/%llu, now %s %s %s, wanted %s %s %s\n", (unsigned long long)rev, + (unsigned long long)before_lineup, s((*now)[0]).c_str(), s((*now)[1]).c_str(), s((*now)[10]).c_str(), + s(wanted[0]).c_str(), s(wanted[1]).c_str(), s(wanted[10]).c_str()); + check(s(at(done, "messageType")) == "command_result" && rev == before_lineup + 1 && now && + s((*now)[0]) == s(wanted[0]) && s((*now)[10]) == s(wanted[10]), + "lineup committed"); + const auto kept = modern::save_stream(session.state()); + check(s(at(session.ui_command(cmd("request:l2", "lineup.commit", O{{"order", J::Array{J("player:none")}}}), rev), + "code")) == "unknown_player" && modern::save_stream(session.state()) == kept && rev == before_lineup + 1, + "unknown player refused without change"); + } + const J tactics = session.ui_read(O{{"kind", "tactics"}}, rev); + const auto* controls = at(at(tactics, "data"), "controls").array(); + check(controls && controls->size() == 8, "tactics read"); + if (controls && controls->size() == 8) { + J::Array values; + for (const auto& c : *controls) values.push_back(at(c, "value")); + const int64_t max7 = *at(at((*controls)[7], "range"), "max").integer(); + const int64_t v7 = *values[7].integer(); + values[7] = J(v7 == max7 ? v7 - 1 : v7 + 1); + const uint64_t before_tactics = rev; + const J done = session.ui_command(cmd("request:t1", "tactics.commit", O{{"values", values}}), rev); + const J reread = session.ui_read(O{{"kind", "tactics"}}, rev); + const auto* now = at(at(reread, "data"), "controls").array(); + check(s(at(done, "messageType")) == "command_result" && rev == before_tactics + 1 && now && + *at((*now)[7], "value").integer() == *values[7].integer(), "tactics committed"); + values[7] = J(max7 + 1); + const auto kept = modern::save_stream(session.state()); + check(s(at(session.ui_command(cmd("request:t2", "tactics.commit", O{{"values", values}}), rev), "code")) == + "invalid_tactic" && modern::save_stream(session.state()) == kept, "tactic above its maximum refused"); + } + const J training = session.ui_read(O{{"kind", "training"}}, rev); + check(s(at(training, "messageType")) == "snapshot" && at(at(training, "data"), "areas").array() && + at(at(training, "data"), "areas").array()->size() == 9, "training read"); + { + const uint64_t before_training = rev; + const J done = session.ui_command(cmd("request:p1", "training.commit", + O{{"types", J::Array{J(2), J(2), J(2), J(2)}}, + {"areas", J::Array{J(2), J(2), J(2), J(2), J(2), J(2), J(2), J(2), J(2)}}}), rev); + const J now = session.ui_read(O{{"kind", "training"}}, rev); + const auto* areas = at(at(now, "data"), "areas").array(); + check(s(at(done, "messageType")) == "command_result" && rev == before_training + 1 && areas && + *at((*areas)[8], "allocation").integer() == 2, "training committed"); + const auto kept = modern::save_stream(session.state()); + check(s(at(session.ui_command(cmd("request:p2", "training.commit", O{{"types", J::Array{J(3), J(3), J(3), J(3)}}}), rev), + "messageType")) == "error" && modern::save_stream(session.state()) == kept && rev == before_training + 1, + "training over the limit refused without change"); + } + // bank: read, fixed deposit, a share, a refused withdrawal + { + const J bank = session.ui_read(O{{"kind", "bank"}}, rev); + const J& accounts = at(at(bank, "data"), "accounts"); + const auto* stocks = at(at(bank, "data"), "stocks").array(); + check(s(at(bank, "messageType")) == "snapshot" && stocks && stocks->size() == 12, "bank read"); + const std::string deposit_before = s(at(at(accounts, "deposit"), "minor")); + const uint64_t before_bank = rev; + const J done = session.ui_command(cmd("request:b1", "bank.commit", + O{{"action", "deposit"}, {"amount", O{{"minor", "10000000"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev); + const J after = session.ui_read(O{{"kind", "bank"}}, rev); + check(s(at(done, "messageType")) == "command_result" && rev == before_bank + 1 && + std::stoll(s(at(at(at(at(after, "data"), "accounts"), "deposit"), "minor"))) == + std::stoll(deposit_before) + 10000000, "100000 euros to the fixed deposit"); + const J share = session.ui_command(cmd("request:b2", "bank.commit", O{{"action", "buy"}, {"assetId", "stock:0"}, {"count", 1}}), rev); + check(s(at(share, "messageType")) == "command_result" && rev == before_bank + 2, "one share bought"); + const auto kept = modern::save_stream(session.state()); + const J refused = session.ui_command(cmd("request:b3", "bank.commit", + O{{"action", "withdraw"}, {"amount", O{{"minor", "99999999900"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev); + check(s(at(refused, "messageType")) == "error" && modern::save_stream(session.state()) == kept && rev == before_bank + 2, + "withdrawal above the deposit refused without change"); + } + // 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")); + for (int k = 0; k < 3; ++k) { + const uint64_t before = rev; + const J done = session.ui_command(cmd("request:a" + std::to_string(k), "session.advance", O{}), rev); + if (s(at(done, "messageType")) != "command_result") + std::fprintf(stderr, "advance: %s\n", cli::dump_json(done).c_str()); + check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "advance accepted"); + } + const std::string date_after = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")); + check(date_after > date_before, "the date moved on"); + } + // almanac view after the kickoffs: index, calendar, day, match + { + const J index = session.read_almanac(O{{"kind", "index"}}); + const auto* years = at(index, "years").array(); + check(truth(at(index, "ok")) && years && !years->empty() && *at(index, "match_count").integer() > 0, "almanac index"); + const J cal = years && !years->empty() ? session.read_almanac(O{{"kind", "calendar"}, {"year", (*years)[0]}}) : J{}; + const auto* days = at(cal, "days").array(); + check(days && !days->empty(), "almanac calendar"); + const J day = days && !days->empty() ? session.read_almanac(O{{"kind", "day"}, {"date", at((*days)[0], "date")}}) : J{}; + const auto* matches = at(day, "matches").array(); + check(matches && !matches->empty(), "almanac day"); + if (matches && !matches->empty()) { + const J& m = (*matches)[0]; + const auto* final_score = at(at(m, "result"), "final").array(); + check(final_score && final_score->size() == 2 && at(at(m, "home"), "id").string() && + at(m, "events").array(), "almanac match form"); + const J one = session.read_almanac(O{{"kind", "match"}, {"id", at(m, "id")}}); + check(truth(at(one, "ok")) && s(at(at(one, "match"), "id")) == s(at(m, "id")), "almanac match by id"); + } + check(s(at(session.read_almanac(O{{"kind", "match"}, {"id", "match:0-0"}}), "error")) == "almanac_match_not_found", + "unknown match"); + } } catch (const std::exception& ex) { std::fprintf(stderr, "FAIL: %s\n", ex.what()); return 1;