Modern UI contract: camps read and the first command, camp.book

ModernSession::ui_command checks careerId, expectedRevision and owner, runs
the engine action and answers command_result or error. A refused command
restores the state and both generators; a repeated requestId gets the stored
answer, a different command under the same id duplicate_request. The camps
read lists maps and camps with a binding, draw-free quote per camp, focus and
the season's stays. Tests cover stale revision, foreign owner, unknown camp,
booking, repeat, conflict and a refused second booking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-27 08:25:54 +01:00
1 parent fec4c6c7e7
commit 99a48a463d
7 files changed
+252 -2

No files matched your search

+14 -1
View File
@@ -27,10 +27,23 @@ 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 |
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).
## 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` |
Test: `modern_ui_contract_tests` (Umschlag, IDs, Geld, Fehler, Reads ändern den Spielstand nicht; Commands: veraltete Revision, fremder Manager, Wiederholung, Konflikt, Ablehnung ohne Änderung; braucht Spieldaten).
Noch nicht gefüllt: `nationId`, `crestAssetId` der Teams, `employments` (Amtszeiten), `strengthChoice`, `allowedCommands`.
+108
View File
@@ -8734,4 +8734,112 @@ 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_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 auto restore = [&] { g_ = saved_state; rand_ = saved_rand; game_ = saved_game; revision = previous; };
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<uint8_t, 4> 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 {
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
+9
View File
@@ -848,6 +848,11 @@ public:
context.next_away = desk.next_match_away;
return modern::ui_read(g_, context, request);
}
// 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 +1001,10 @@ private:
uint64_t original_rand_calls = 0, original_game_calls = 0, context_revision = 0;
};
std::optional<ManagerJoinDraft> 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<std::string, std::pair<std::string, cli::Json>> ui_answers_;
std::vector<std::string> ui_answer_order_;
std::filesystem::path data_directory_;
LeImage exe_;
+70
View File
@@ -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,6 +320,24 @@ 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<std::string>& 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}};
}
@@ -286,6 +355,7 @@ cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& req
const std::string today = *std::get<O>(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))
+9
View File
@@ -17,6 +17,7 @@
#include <cstdint>
#include <string>
#include <vector>
#include "cli/json.hpp"
#include "modern/game/modern_state.hpp"
@@ -46,4 +47,12 @@ 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<std::string>& 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:<n>").
std::string ui_manager_id(const ModernState& g, int manager);
} // namespace bmh::modern
+1 -1
View File
@@ -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());
}
+41
View File
@@ -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<bool>(&j.value); return b && *b; }
} // namespace
int main(int argc, char** argv) {
@@ -105,6 +106,46 @@ 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");
} catch (const std::exception& ex) {
std::fprintf(stderr, "FAIL: %s\n", ex.what());
return 1;