Files
Dreierpack-Manager/tests/modern_ui_contract_tests.cpp
T
MichaelandClaude Fable 5.2 2639f37def The stadium has a name of its own, and the name can be sold
A manager renames his stadium on the stadium page. On the advertising page
three sponsors offer to buy the name for one to five years; the sponsor
pays with every month change, the stadium is called after him, and until
the contract ends it can be neither renamed nor sold again. The match
sheet shows the name.

Engine: naming_rights.hpp; read stadium (name, nameEditable, namingRights,
namingOffers), commands stadium.rename and stadium.namingRights, live read
stadiumName; saved in state/modern.json.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 15:09:01 +01:00

1078 lines
81 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
// The engine side of the Modern interface contract (docs/new_engine/ui-anbindung.md): the
// envelope, identities, money, errors and that a read changes nothing. Needs game data
// (a Modern session on the Classic data).
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <variant>
#include "cli/json.hpp"
#include "modern/app/modern_session.hpp"
#include "modern/content/press_journal.hpp"
#include "modern/content/ui_contract.hpp"
#include "modern/game/save.hpp"
using namespace bmh;
using J = cli::Json;
using O = J::Object;
namespace {
int failures = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "FAIL: %s\n", what);
++failures;
}
}
const J& at(const J& j, const char* key) {
static const J none;
const auto* o = j.object();
if (!o) return none;
const auto it = o->find(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) {
if (argc < 2) {
std::fprintf(stderr, "usage: modern_ui_contract_tests <BMH data>\n");
return 2;
}
try {
modern::app::ModernSession session(argv[1], 1u);
ui::SetupOptions options;
ui::ManagerChoice choice;
choice.name = "TEST";
choice.master_club = 0;
std::string error;
if (!session.confirm_manager(options, choice, error)) throw std::runtime_error("manager: " + error);
ui::CareerInitializationResult init;
if (!session.finish(init, error)) throw std::runtime_error("career start: " + error);
const uint64_t revision = init.desktop.revision;
const auto before = modern::save_stream(session.state());
const std::string career = session.state().career_id;
// session: envelope and identities
const J sess = session.ui_read(O{{"kind", "session"}, {"requestId", "request:1"}}, revision);
check(s(at(sess, "messageType")) == "snapshot", "session is a snapshot");
check(s(at(sess, "requestId")) == "request:1", "request id echoed");
const J& meta = at(sess, "meta");
check(s(at(meta, "contractVersion")) == "bmh-modern-ui@draft1", "contract version");
check(s(at(meta, "careerId")).starts_with("career:") && s(at(meta, "careerId")).size() == 23, "career id");
check(s(at(meta, "stateRevision")) == std::to_string(revision), "state revision as decimal string");
check(s(at(at(meta, "scope"), "managerId")) == "manager:1", "first manager id");
check(s(at(at(meta, "currency"), "code")) == "EUR" && at(at(meta, "currency"), "minorUnits").integer() &&
*at(at(meta, "currency"), "minorUnits").integer() == 2, "currency");
const auto* managers = at(at(sess, "data"), "managers").array();
check(managers && managers->size() == 1 && s(at((*managers)[0], "status")) == "active", "one active manager");
// desktop: money in minor units, menus
const J desk = session.ui_read(O{{"kind", "desktop"}}, revision);
const J status = session.read(O{{"kind", "status"}});
const int64_t euros = at(status, "money").integer() ? *at(status, "money").integer() : -1;
check(s(at(at(at(at(desk, "data"), "accounts"), "cash"), "minor")) == std::to_string(euros * 100), "cash in cents");
const auto* menus = at(at(desk, "data"), "menuAvailability").object();
check(menus && menus->size() == 16 && s(at(menus->at("bank"), "status")) == "available", "menus at a club desk");
// squad: own club with salaries, another club without
const J own = session.ui_read(O{{"kind", "squad"}}, revision);
const auto* players = at(at(own, "data"), "players").array();
check(players && players->size() >= 11, "own squad");
check(players && !players->empty() && at((*players)[0], "salaryMonthly").object(), "own salaries known");
const J other = session.ui_read(O{{"kind", "squad"}, {"teamId", "team:5"}}, revision);
const auto* others = at(at(other, "data"), "players").array();
check(others && !others->empty() && std::holds_alternative<std::nullptr_t>(at((*others)[0], "salaryMonthly").value), "foreign salaries unknown");
// errors
check(s(at(session.ui_read(O{{"kind", "nonsense"}}, revision), "code")) == "unknown_read", "unknown read");
check(s(at(session.ui_read(O{{"kind", "desktop"}, {"managerId", "manager:7"}}, revision), "code")) ==
"manager_not_active", "other manager refused");
check(s(at(session.ui_read(O{{"kind", "squad"}, {"teamId", "club:none"}}, revision), "code")) == "unknown_team",
"unknown team");
// reads change nothing
check(modern::save_stream(session.state()) == before, "reads leave the state unchanged");
check(session.state().career_id == career, "career id unchanged");
// identities: never reused, nothing set is replaced
modern::ModernState copy = session.state();
modern::ensure_ui_identities(copy);
check(copy.manager_ids == session.state().manager_ids && copy.career_id == career, "identities stable");
copy.manager_ids.clear();
modern::ensure_ui_identities(copy);
check(copy.manager_ids.size() == 1 && copy.manager_ids[0] == "manager:2", "a freed slot gets a new id");
// 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");
}
// 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");
}
}
// advertising: the first acceptable offer, a budget
{
const J ads = session.ui_read(O{{"kind", "advertising"}}, rev);
check(s(at(ads, "messageType")) == "snapshot" && at(at(ads, "data"), "boards").array() &&
at(at(ads, "data"), "boards").array()->size() == 14, "advertising read");
std::string offer;
const auto pick = [&](const J& place) {
if (const auto* list = at(place, "offers").array())
for (const auto& o : *list)
if (offer.empty() && truth(at(o, "allowed"))) offer = s(at(o, "id"));
};
pick(at(at(ads, "data"), "shirt"));
pick(at(at(ads, "data"), "television"));
if (const auto* boards = at(at(ads, "data"), "boards").array())
for (const auto& b : *boards) pick(b);
const uint64_t before = rev;
if (!offer.empty()) {
const J done = session.ui_command(cmd("request:w1", "advertising.accept", O{{"offerId", offer}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "advertising: %s\n", cli::dump_json(done).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "advertising offer accepted");
}
const auto kept = modern::save_stream(session.state());
check(s(at(session.ui_command(cmd("request:w2", "advertising.accept", O{{"offerId", "offer:ad-3-99"}}), rev), "code")) ==
"unknown_offer" && modern::save_stream(session.state()) == kept, "unknown offer refused");
std::printf("(advertising offer %s)\n", offer.empty() ? "none" : offer.c_str());
}
// stadium: periphery, facilities, blocks; the ticket price
{
const J stadium = session.ui_read(O{{"kind", "stadium"}}, rev);
const J& d = at(stadium, "data");
if (s(at(stadium, "messageType")) != "snapshot") std::fprintf(stderr, "stadium: %s\n", cli::dump_json(stadium).c_str());
check(at(d, "periphery").array() && at(d, "periphery").array()->size() == 14 && at(d, "blocks").array() &&
at(d, "blocks").array()->size() == 8 && at(d, "facilities").array() && at(d, "facilities").array()->size() == 8,
"stadium read");
if (const auto* p = at(d, "periphery").array(); p && !p->empty())
check(!s(at((*p)[0], "name")).empty() && at((*p)[0], "stage").integer(), "traffic access with its stage");
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:e1", "ticket.commit", O{{"price", O{{"minor", "1200"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "ticket: %s\n", cli::dump_json(done).c_str());
const J after = session.ui_read(O{{"kind", "stadium"}}, rev);
check(s(at(done, "messageType")) == "command_result" && s(at(at(at(after, "data"), "ticketPrice"), "minor")) == "1200" &&
rev <= before + 1, "ticket price set");
check(s(at(session.ui_command(cmd("request:e2", "ticket.commit", O{{"price", O{{"minor", "3000"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev),
"code")) == "invalid_amount", "ticket price above 25 refused");
// building: a periphery object not built yet, then a facility level without the tip
std::string object;
if (const auto* p = at(at(after, "data"), "periphery").array())
for (const auto& o : *p)
if (object.empty() && at(o, "built").value.index() == 1 && !truth(at(o, "built")) && *at(o, "constructionDays").integer() == 0)
object = s(at(o, "id"));
const auto quote_of = [&]() { const J st = session.ui_read(O{{"kind", "stadium"}}, rev); return J(at(at(st, "data"), "quote")); };
if (!object.empty()) {
const uint64_t b0 = rev;
const J q = session.ui_command(cmd("request:e3", "quote.request", O{{"kind", "periphery"}, {"objectId", object}}), rev);
if (s(at(q, "messageType")) != "command_result") std::fprintf(stderr, "periphery quote: %s\n", cli::dump_json(q).c_str());
const J quote = quote_of();
check(s(at(q, "outcome")) == "offer_pending" && s(at(quote, "objectId")) == object && rev == b0 + 1, "periphery quoted");
const J built = session.ui_command(cmd("request:e4", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}}), rev);
if (s(at(built, "messageType")) != "command_result") std::fprintf(stderr, "periphery build: %s\n", cli::dump_json(built).c_str());
check(s(at(built, "messageType")) == "command_result" && rev == b0 + 2 && std::holds_alternative<std::nullptr_t>(quote_of().value),
"periphery built, the stadium closed");
}
{
const uint64_t b0 = rev;
const J q = session.ui_command(cmd("request:e5", "quote.request", O{{"kind", "facility"}, {"facilityId", "facility:safety"}, {"increment", 1}}), rev);
const J quote = quote_of();
if (s(at(q, "messageType")) == "command_result") {
check(s(at(quote, "kind")) == "facility" && at(quote, "price").object(), "facility quoted");
const J done = session.ui_command(cmd("request:e6", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}, {"tip", false}}), rev);
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "facility build: %s\n", cli::dump_json(done).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == b0 + 2, "facility ordered");
} else {
std::printf("(facility quote: %s)\n", s(at(q, "code")).c_str());
}
// a stand block: 1000 more places
std::string block;
int64_t places = 0;
if (const auto* blocks = at(at(after, "data"), "blocks").array())
for (const auto& b : *blocks)
if (block.empty() && *at(b, "constructionWeeks").integer() == 0 &&
*at(b, "places").integer() + 1000 <= *at(b, "maxPlaces").integer())
block = s(at(b, "id")), places = *at(b, "places").integer() + 1000;
if (!block.empty()) {
const uint64_t b1 = rev;
const J bq = session.ui_command(cmd("request:eb1", "quote.request", O{{"kind", "block"}, {"blockId", block}, {"places", places}}), rev);
const J quote = quote_of();
if (s(at(bq, "messageType")) != "command_result") std::fprintf(stderr, "block quote: %s\n", cli::dump_json(bq).c_str());
check(s(at(quote, "kind")) == "block" && *at(quote, "places").integer() == places, "block quoted");
const J built = session.ui_command(cmd("request:eb2", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}, {"tip", false}}), rev);
if (s(at(built, "messageType")) != "command_result") std::fprintf(stderr, "block build: %s\n", cli::dump_json(built).c_str());
const J st = session.ui_read(O{{"kind", "stadium"}}, rev);
int weeks = -1;
for (const auto& b : *at(at(st, "data"), "blocks").array())
if (s(at(b, "id")) == block) weeks = int(*at(b, "constructionWeeks").integer());
check(s(at(built, "messageType")) == "command_result" && rev == b1 + 2 && weeks > 0, "block expansion under way");
std::printf("(block %s to %lld places: %d weeks)\n", block.c_str(), (long long)places, weeks);
}
const J q2 = session.ui_command(cmd("request:e7", "quote.request", O{{"kind", "facility"}, {"facilityId", "facility:comfort"}, {"increment", 1}}), rev);
if (s(at(q2, "messageType")) == "command_result") {
const J declined = session.ui_command(cmd("request:e8", "stadium.commit", O{{"quoteId", at(quote_of(), "id")}, {"accept", false}}), rev);
check(s(at(declined, "messageType")) == "command_result" && std::holds_alternative<std::nullptr_t>(quote_of().value),
"facility offer declined, the stadium closed");
}
}
}
// transfers: list an own player, bid on a listed one (asking fee and salary reference)
{
const J market = session.ui_read(O{{"kind", "transfer"}}, rev);
const auto* listings = at(at(market, "data"), "listings").array();
const auto* squad = at(at(market, "data"), "squad").array();
check(s(at(market, "messageType")) == "snapshot" && listings && squad && !squad->empty(), "transfer read");
const uint64_t before = rev;
if (squad && squad->size() > 15) {
const std::string seller = s(at(squad->back(), "playerId"));
const J listed = session.ui_command(cmd("request:t9", "transfer.submit", O{{"action", "list"}, {"playerId", seller}}), rev);
if (s(at(listed, "messageType")) != "command_result") std::fprintf(stderr, "list: %s\n", cli::dump_json(listed).c_str());
check(s(at(listed, "messageType")) == "command_result" && rev == before + 1, "own player listed");
// a second player goes on the list and is taken off the market again
const std::string second = s(at((*squad)[squad->size() - 2], "playerId"));
const auto listed_now = [&](const std::string& id) {
const J now = session.ui_read(O{{"kind", "transfer"}}, rev);
const auto* rows = at(at(now, "data"), "squad").array();
if (rows) for (const auto& row : *rows) if (s(at(row, "playerId")) == id) return truth(at(row, "listed"));
return false;
};
check(s(at(session.ui_command(cmd("request:t9b", "transfer.submit", O{{"action", "withdraw"}, {"playerId", second}}), rev), "code")) == "not_listed",
"a player who is not listed cannot be withdrawn");
session.ui_command(cmd("request:t9c", "transfer.submit", O{{"action", "list"}, {"playerId", second}}), rev);
check(listed_now(second), "second player listed");
const uint64_t listed_rev = rev;
const J withdrawn = session.ui_command(cmd("request:t9d", "transfer.submit", O{{"action", "withdraw"}, {"playerId", second}}), rev);
if (s(at(withdrawn, "messageType")) != "command_result") std::fprintf(stderr, "withdraw: %s\n", cli::dump_json(withdrawn).c_str());
check(s(at(withdrawn, "messageType")) == "command_result" && rev == listed_rev + 1 && !listed_now(second) && listed_now(seller),
"the player is off the market, the other listing stays");
}
std::string listing;
J fee, salary;
if (listings)
for (const auto& l : *listings)
if (listing.empty() && !truth(at(l, "ownListing")) && !truth(at(l, "ownBidPending")))
listing = s(at(l, "id")), fee = at(l, "askingFee"), salary = at(l, "salaryReference");
if (!listing.empty()) {
// the salary reference is annual in the market row; the offer takes a monthly salary
const int64_t monthly = std::stoll(s(at(salary, "minor"))) / 12 / 100 * 100;
const uint64_t b2 = rev;
const J bid = session.ui_command(cmd("request:t10", "transfer.submit",
O{{"action", "bid"}, {"listingId", listing}, {"fee", fee},
{"monthlySalary", O{{"minor", std::to_string(monthly)}, {"currency", "EUR"}, {"minorUnits", 2}}}, {"years", 2}}), rev);
std::printf("(bid on %s: %s)\n", listing.c_str(), cli::dump_json(bid).substr(0, 260).c_str());
check((s(at(bid, "messageType")) == "command_result" && rev == b2 + 1) ||
(s(at(bid, "messageType")) == "error" && rev == b2), "bid answered or refused cleanly");
// a bid that waits for the seller can be taken back, once
const auto own_bid = [&] {
const J now = session.ui_read(O{{"kind", "transfer"}}, rev);
const auto* rows = at(at(now, "data"), "listings").array();
if (rows) for (const auto& row : *rows) if (s(at(row, "id")) == listing) return at(row, "ownBid").object() != nullptr;
return false;
};
if (own_bid()) {
const uint64_t b3 = rev;
const J back = session.ui_command(cmd("request:t10b", "transfer.submit", O{{"action", "withdrawBid"}, {"listingId", listing}}), rev);
check(s(at(back, "messageType")) == "command_result" && rev == b3 + 1 && !own_bid(), "the waiting bid is taken back");
std::printf("(bid withdrawn)\n");
}
check(s(at(session.ui_command(cmd("request:t10c", "transfer.submit", O{{"action", "withdrawBid"}, {"listingId", listing}}), rev), "code")) == "no_bid",
"no bid to take back");
}
check(s(at(session.ui_command(cmd("request:t11", "transfer.submit", O{{"action", "bid"}, {"listingId", "listing:999"}}), rev), "code")) ==
"unknown_listing", "unknown listing refused");
}
// scheduling: move a league match and take it back; a friendly
{
const J sched = session.ui_read(O{{"kind", "scheduling"}}, rev);
const auto* movable = at(at(sched, "data"), "movable").array();
check(s(at(sched, "messageType")) == "snapshot" && movable, "scheduling read");
std::string match, target;
if (movable)
for (const auto& mv : *movable)
if (match.empty() && at(mv, "targetDates").array() && !at(mv, "targetDates").array()->empty())
match = s(at(mv, "id")), target = s(at(mv, "targetDates").array()->front());
if (!match.empty()) {
const uint64_t before = rev;
const J moved = session.ui_command(cmd("request:f1", "fixture.reschedule", O{{"matchId", match}, {"date", target}}), rev);
const J again = session.ui_read(O{{"kind", "scheduling"}}, rev);
check(s(at(moved, "messageType")) == "command_result" && rev == before + 1 && at(at(again, "data"), "moved").array() &&
!at(at(again, "data"), "moved").array()->empty(), "league match moved");
// the calendar of the season: every league match once (two per opponent), the
// moved one on its new date with the planned one as original date
const J cal = session.ui_read(O{{"kind", "calendar"}, {"from", "1900-01-01"}, {"until", "2999-12-31"}}, rev);
const auto* fixtures = at(at(cal, "data"), "fixtures").array();
std::set<std::string> ids, opponents;
std::string own = s(at(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "data"), "team"), "id"));
bool moved_seen = false;
if (fixtures)
for (const auto& f : *fixtures) {
ids.insert(s(at(f, "id")));
const std::string h = s(at(at(f, "home"), "id")), a = s(at(at(f, "away"), "id"));
opponents.insert(h == own ? a : h);
if (s(at(f, "status")) == "rescheduled" && s(at(f, "scheduledDate")) == target && s(at(f, "originalDate")) != target)
moved_seen = true;
}
std::printf("(calendar: %zu days, %zu league matches, %zu opponents)\n",
at(at(cal, "data"), "days").array() ? at(at(cal, "data"), "days").array()->size() : 0, ids.size(), opponents.size());
check(fixtures && ids.size() == fixtures->size() && !opponents.empty() && ids.size() == 2 * opponents.size(),
"calendar: every league match once, two per opponent");
check(moved_seen, "calendar: the moved match on its new date");
const J undone = session.ui_command(cmd("request:f2", "fixture.reschedule", O{{"action", "undo"}, {"date", target}}), rev);
check(s(at(undone, "messageType")) == "command_result", "move taken back");
// issue 16: after the undo the match offers the same target dates as before the move
const auto targets_of = [&](const J& read) {
if (const auto* list = at(at(read, "data"), "movable").array())
for (const auto& mv : *list)
if (s(at(mv, "id")) == match) return cli::dump_json(at(mv, "targetDates"));
return std::string{};
};
check(!targets_of(sched).empty() && targets_of(session.ui_read(O{{"kind", "scheduling"}}, rev)) == targets_of(sched),
"the same target dates after the undo");
std::printf("(moved %s to %s and back)\n", match.c_str(), target.c_str());
}
const J friendly = session.ui_read(O{{"kind", "friendly"}, {"opponentId", "team:70"}, {"home", true}}, rev);
const auto* dates = at(at(friendly, "data"), "dates").array();
if (s(at(friendly, "messageType")) != "snapshot") std::fprintf(stderr, "friendly: %s\n", cli::dump_json(friendly).c_str());
check(dates && !dates->empty() && at(at(at(friendly, "data"), "cost"), "minor").string(), "friendly quote with free dates");
if (dates && !dates->empty()) {
const J day = at(dates->front(), "date");
check(s(at(session.ui_command(cmd("request:f3", "friendly.book", O{{"opponentId", "team:70"}, {"date", day}}), rev), "code")) ==
"declined", "the cost must be accepted");
const uint64_t before = rev;
const J booked = session.ui_command(cmd("request:f4", "friendly.book", O{{"opponentId", "team:70"}, {"date", day}, {"acceptCost", true}}), rev);
if (s(at(booked, "messageType")) != "command_result") std::fprintf(stderr, "friendly book: %s\n", cli::dump_json(booked).c_str());
check(s(at(booked, "messageType")) == "command_result" && rev == before + 1, "friendly booked");
}
}
// a bank credit: draft with an edit within its bounds, preview, booking
{
const J credit = session.ui_read(O{{"kind", "credit"}}, rev);
const auto* fields = at(at(credit, "data"), "fields").array();
if (s(at(credit, "messageType")) != "snapshot") std::fprintf(stderr, "credit: %s\n", cli::dump_json(credit).c_str());
check(fields && fields->size() == 8, "credit read with eight fields");
int field = -1;
int64_t value = 0;
if (fields)
for (const auto& f : *fields)
if (field < 0 && truth(at(f, "editable")) && *at(f, "max").integer() > *at(f, "min").integer()) {
field = int(*at(f, "field").integer());
value = (*at(f, "min").integer() + *at(f, "max").integer()) / 2;
}
if (field >= 0) {
const J::Array edits{J(O{{"field", field}, {"value", value}})};
const J preview = session.ui_read(O{{"kind", "credit"}, {"edits", edits}}, rev);
check(s(at(preview, "messageType")) == "snapshot", "credit preview");
int64_t too_high = 0;
for (const auto& f : *fields)
if (*at(f, "field").integer() == field) too_high = *at(f, "max").integer() + 1;
const J::Array bad{J(O{{"field", field}, {"value", too_high}})};
const J refused = session.ui_read(O{{"kind", "credit"}, {"edits", bad}}, rev);
check(s(at(refused, "code")) == "invalid_credit_edit", "credit edit beyond its bound refused");
const uint64_t before = rev;
const J booked = session.ui_command(cmd("request:k9", "bank.commit", O{{"action", "credit"}, {"edits", edits}, {"acceptFees", true}}), rev);
std::printf("(credit field %d to %lld: %s)\n", field, (long long)value, cli::dump_json(booked).substr(0, 160).c_str());
check(s(at(booked, "messageType")) == "command_result" && rev == before + 1, "credit booked");
}
}
// the surroundings: six budgets 0-6
{
const J env = session.ui_read(O{{"kind", "environment"}}, rev);
const auto* items = at(at(env, "data"), "items").array();
check(items && items->size() == 6 && at(at(env, "data"), "youth").array(), "environment read");
if (items && items->size() == 6) {
const int64_t level = *at((*items)[4], "level").integer();
const int64_t wanted = level < 6 ? level + 1 : level - 1;
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:u1", "environment.commit", O{{"itemId", "environment:doctor"}, {"level", wanted}}), rev);
const J after_env = session.ui_read(O{{"kind", "environment"}}, rev);
check(s(at(done, "messageType")) == "command_result" && rev == before + 1 &&
*at((*at(at(after_env, "data"), "items").array())[4], "level").integer() == wanted, "doctor budget changed");
check(s(at(session.ui_command(cmd("request:u2", "environment.commit", O{{"itemId", "environment:doctor"}, {"level", 9}}), rev), "code")) ==
"invalid_payload", "level above 6 refused");
}
}
// toto and the exclusive sponsor
{
const J toto = session.ui_read(O{{"kind", "toto"}}, rev);
check(s(at(toto, "messageType")) == "snapshot" && at(at(at(toto, "data"), "stake"), "minor").string(), "toto read with Money");
const J::Array column{J(1), J(0), J(2), J(1), J(1), J(0), J(2), J(1), J(1), J(0), J(2)};
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:o1", "toto.submit",
O{{"stake", O{{"minor", "5000000"}, {"currency", "EUR"}, {"minorUnits", 2}}}, {"columns", J::Array{J(column), J(column)}}}), rev);
if (truth(at(at(toto, "data"), "open")))
check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "two toto columns submitted");
else
check(s(at(done, "code")) == "toto_refused" && rev == before, "toto closed: refused without change");
check(s(at(session.ui_command(cmd("request:o2", "sponsor.answer", O{{"accept", true}}), rev), "messageType")) == "error",
"no sponsor offer to answer");
}
// 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");
}
// a rehearsal is played and taken back: no revision, and the desk reads as before
for (int k = 0; k < 3; ++k) {
const uint64_t before = rev;
const std::string desk_before = cli::dump_json(session.ui_read(O{{"kind", "desktop"}}, rev));
const std::string lineup_before = cli::dump_json(session.ui_read(O{{"kind", "lineup"}}, rev));
const J tried = session.ui_command(cmd("request:dry" + std::to_string(k), "session.advance", O{{"dryRun", true}}), rev);
check(s(at(tried, "messageType")) == "command_result" && s(at(tried, "outcome")) == "rehearsed" && rev == before,
"rehearsal accepted without a revision");
check(cli::dump_json(session.ui_read(O{{"kind", "desktop"}}, rev)) == desk_before, "rehearsal leaves the desk as it was");
check(cli::dump_json(session.ui_read(O{{"kind", "lineup"}}, rev)) == lineup_before, "rehearsal leaves the line-up as it was");
// the kickoff after a rehearsal plays the fixture the desk announced
const J next = at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "data"), "nextFixture");
const J played = session.ui_command(cmd("request:dry-play" + std::to_string(k), "session.advance", O{}), rev);
check(s(at(played, "messageType")) == "command_result", "kickoff after a rehearsal accepted");
const J recording = session.read_live(O{{"kind", "fixture"}});
if (truth(at(recording, "ok")) && next.object()) {
bool found = false;
for (const J& m : *at(recording, "matches").array())
found = found || s(at(at(m, "home"), "id")) == s(at(at(next, "home"), "id"));
check(found, "the announced fixture was the one played");
}
}
// the live ticker: advance until a kickoff played a match of the human manager, then its recording
{
J fixture;
J live_final;
for (int k = 0; k < 12; ++k) {
fixture = session.read_live(O{{"kind", "fixture"}});
if (truth(at(fixture, "ok"))) break;
check(s(at(fixture, "error")) == "live_no_human_match", "no human match: said so");
session.ui_command(cmd("request:lv" + std::to_string(k), "session.advance", O{}), rev);
}
const auto* frames = at(fixture, "frames").array();
const auto* matches = at(fixture, "matches").array();
check(truth(at(fixture, "ok")) && s(at(fixture, "source")) == "engine-recording" && frames && frames->size() >= 4 &&
matches && !matches->empty() && at(fixture, "owners").array() && !at(fixture, "owners").array()->empty(),
"live fixture of the last kickoff");
if (matches && !matches->empty())
check(at((*matches)[0], "attendance").integer() && at(at((*matches)[0], "weather"), "rain").integer(),
"crowd and weather of the ticker match before the kickoff");
if (frames && frames->size() >= 4) {
const J& last = frames->back();
const J one = session.read_live(O{{"kind", "frame"}, {"sequence", int64_t(frames->size() - 1)}});
check(truth(at(one, "ok")) && cli::dump_json(at(at(one, "frame"), "matches")) == cli::dump_json(at(last, "matches")), "one frame by sequence");
live_final = at(at(one, "frame"), "standings");
// the last frame's score is the recorded result of the match
const J m = at(at(last, "matches").array()->front(), "score");
std::printf("(live: %zu frames, %zu matches, conference %zu, final %s)\n", frames->size(), matches->size(),
at(fixture, "conference").array() ? at(fixture, "conference").array()->size() : 0, cli::dump_json(m).c_str());
}
check(s(at(session.read_live(O{{"kind", "frame"}, {"sequence", 99999}}), "error")) == "invalid_live_sequence", "bad sequence");
// the after-match steps of that kickoff
const J post = session.ui_read(O{{"kind", "postmatch"}}, rev);
const J& pd = at(post, "data");
const auto* steps = at(pd, "steps").array();
check(s(at(post, "messageType")) == "snapshot" && steps && steps->size() == 5 && truth(at((*steps)[0], "available")) &&
at(pd, "matches").array() && !at(pd, "matches").array()->empty() && at(pd, "reportMatchIds").array() &&
!at(pd, "reportMatchIds").array()->empty(), "postmatch with results and report");
// the live table at the final whistle is the league table after the matchday
if (const auto* lt = live_final.array(); lt && !lt->empty() && at(pd, "tables").array()) {
std::map<std::string, int64_t> points;
for (const auto& t : *at(pd, "tables").array())
for (const auto& r : *at(t, "rows").array()) points[s(at(at(r, "club"), "id"))] = *at(r, "points").integer();
bool same = true;
for (const auto& r : *at(lt->front(), "rows").array()) {
const auto p = points.find(s(at(at(r, "team"), "id")));
same &= p != points.end() && p->second == *at(r, "points").integer();
}
std::printf("(live table: %zu leagues, %zu rows)\n", lt->size(), at(lt->front(), "rows").array()->size());
check(same, "live table at the final whistle equals the league table");
}
std::printf("(postmatch: %zu matches, %zu tables, %zu elevens)\n", at(pd, "matches").array()->size(),
at(pd, "tables").array() ? at(pd, "tables").array()->size() : 0,
at(pd, "teamOfTheDay").array() ? at(pd, "teamOfTheDay").array()->size() : 0);
}
// a live kickoff: stops in a match of the human manager, steps, intervenes, finishes
{
bool stopped = false;
for (int k = 0; k < 12 && !stopped; ++k) {
const J started = session.ui_command(cmd("request:lr" + std::to_string(k), "session.advance", O{{"live", true}}), rev);
const J state = session.read_live(O{{"kind", "fixture"}});
stopped = truth(at(state, "live"));
if (!stopped)
check(s(at(started, "messageType")) == "command_result", "a live kickoff without a human match runs through");
}
check(stopped, "a live kickoff stood still in a match");
if (stopped) {
check(s(at(session.ui_command(cmd("request:lx", "bank.commit", O{{"action", "deposit"}}), rev), "code")) == "live_running",
"other commands wait for the live kickoff");
const J stepped = session.ui_command(cmd("request:ls", "live.step", O{{"minutes", 30}}), rev);
const J state = session.read_live(O{{"kind", "fixture"}});
check(s(at(stepped, "messageType")) == "command_result" && at(state, "minute").integer() &&
*at(state, "minute").integer() >= 30, "thirty minutes on");
std::printf("(live state: %s)\n", cli::dump_json(state).substr(0, 400).c_str());
check(at(state, "standings").array() != nullptr, "the paused kickoff names its live tables");
if (const auto* live = at(state, "matches").array(); live && !live->empty())
check(at(at((*live)[0], "weather"), "temperature").integer() != nullptr, "the paused match's weather");
std::printf("(paused live tables: %zu)\n", at(state, "standings").array() ? at(state, "standings").array()->size() : 0);
if (const auto* live = at(state, "matches").array(); live && !live->empty()) {
int goals = 0;
for (const auto& e : *at((*live)[0], "events").array()) goals += s(at(e, "kind")) == "goal";
const auto* score = at((*live)[0], "score").array();
check(score && goals == *(*score)[0].integer() + *(*score)[1].integer(), "the live goals match the score");
}
// a substitution: the last field row for the first bench row
const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev);
const auto* order = at(at(lineup, "data"), "order").array();
if (order && order->size() > 11) {
const J sub = session.ui_command(cmd("request:lsub", "live.substitute",
O{{"outPlayerId", (*order)[10]}, {"inPlayerId", (*order)[11]}}), rev);
std::printf("(live substitution: %s)\n", cli::dump_json(sub).substr(0, 200).c_str());
check(s(at(sub, "messageType")) == "command_result" || s(at(sub, "code")) == "substitution_refused",
"live substitution answered");
}
const J tactics = session.ui_read(O{{"kind", "tactics"}}, rev);
if (const auto* controls = at(at(tactics, "data"), "controls").array(); controls && controls->size() == 8) {
J::Array values;
for (const auto& c : *controls) values.push_back(at(c, "value"));
values[7] = J(*values[7].integer() == 0 ? 1 : 0);
const J changed = session.ui_command(cmd("request:ltac", "live.tactics", O{{"values", values}}), rev);
std::printf("(live tactics: %s)\n", cli::dump_json(changed).substr(0, 800).c_str());
check(s(at(changed, "messageType")) == "command_result", "live tactics changed");
}
const J done = session.ui_command(cmd("request:lf", "live.finish", O{}), rev);
check(s(at(done, "messageType")) == "command_result", "live kickoff finished");
const J fixture = session.read_live(O{{"kind", "fixture"}});
if (!truth(at(fixture, "ok"))) std::printf("(fixture: %s)\n", cli::dump_json(fixture).substr(0, 200).c_str());
check(truth(at(fixture, "ok")) && at(fixture, "frames").array() && at(fixture, "frames").array()->size() >= 4,
"the live kickoff's recording");
}
check(s(at(session.ui_command(cmd("request:lz", "live.step", O{}), rev), "code")) == "live_not_running", "no live kickoff");
}
// a paused league match: its live table (the league as it stands with the scores so far)
{
bool seen = false;
for (int k = 0; k < 16 && !seen; ++k) {
session.ui_command(cmd("request:lt" + std::to_string(k), "session.advance", O{{"live", true}}), rev);
const J state = session.read_live(O{{"kind", "fixture"}});
if (!truth(at(state, "live"))) continue;
if (const auto* tables = at(state, "standings").array(); tables && !tables->empty()) {
const auto* rows = at(tables->front(), "rows").array();
seen = rows && rows->size() >= 10 && *at(rows->front(), "rank").integer() == 1;
std::printf("(paused league table: %s, %zu rows)\n", s(at(tables->front(), "name")).c_str(), rows ? rows->size() : 0);
check(seen, "the paused league match has its live table");
}
session.ui_command(cmd("request:ltf" + std::to_string(k), "live.finish", O{}), rev);
}
if (!seen) std::printf("(no paused league match on this path)\n");
}
// a season of kickoffs: running-out contracts stop the run with decision_pending and the
// player; the advance is sent again with the answer (here: release)
{
O expiry;
int decisions = 0, advances = 0;
int national_friendly = -1; // -1 no national desk yet, 0 read, 1 booked
bool indoor_seen = false;
for (int k = 0; k < 200 && advances < 120; ++k) {
const uint64_t before = rev;
const J done = session.ui_command(cmd("request:s" + std::to_string(k), "session.advance", O{{"contractExpiry", expiry}}), rev);
if (s(at(done, "messageType")) == "command_result") {
++advances;
// the winter indoor tournament (#27): the line-up read says so and gives the
// first eleven's pairs; committing the same order keeps owner, order and pairs
if (!indoor_seen) {
const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev);
const J& data = at(lineup, "data");
if (s(at(data, "surface")) == "indoor") {
indoor_seen = true;
const auto* order = at(data, "order").array();
const auto* pairs = at(data, "pairs").array();
const auto* positions = at(data, "positions").array();
std::printf("(indoor line-up: %s)\n", cli::dump_json(at(data, "pairs")).substr(0, 300).c_str());
bool linked = pairs && positions && positions->size() == 11 && order && order->size() >= 11;
for (size_t i = 0; linked && i < pairs->size(); ++i) {
const auto* ids = at((*pairs)[i], "playerIds").array();
linked = ids && ids->size() == 2;
for (const auto& p : *positions)
if (linked && s(at(p, "playerId")) == s((*ids)[0])) linked = s(at(p, "partnerId")) == s((*ids)[1]);
}
check(linked && *at(data, "durationMinutes").integer() == 40 && *at(data, "starterCount").integer() == 11,
"indoor line-up read: eleven starters with their pairs");
const uint64_t was = rev;
const J kept = session.ui_command(cmd("request:il" + std::to_string(k), "lineup.commit", O{{"order", J(*order)}}), rev);
const J again = at(session.ui_read(O{{"kind", "lineup"}}, rev), "data");
check(s(at(kept, "messageType")) == "command_result" && rev == was + 1 &&
cli::dump_json(at(again, "order")) == cli::dump_json(at(data, "order")) &&
cli::dump_json(at(again, "pairs")) == cli::dump_json(at(data, "pairs")) &&
s(at(again, "surface")) == "indoor",
"indoor line-up commit keeps order and pairs");
}
}
// at the national coach's desk: a friendly against another nation (the quote
// draws ratings; the read previews them without moving the generator)
if (national_friendly < 0) {
const J nf = session.ui_read(O{{"kind", "friendly"}, {"opponentId", "team:384"}}, rev);
if (!truth(at(at(nf, "data"), "national"))) continue;
const J again = session.ui_read(O{{"kind", "friendly"}, {"opponentId", "team:384"}}, rev);
const auto* dates = at(at(nf, "data"), "dates").array();
check(cli::dump_json(at(nf, "data")) == cli::dump_json(at(again, "data")) && dates, "national friendly read is pure");
// the national team's line-up and tactics at the coach's desk
{
const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev);
const J tactics = session.ui_read(O{{"kind", "tactics"}}, rev);
const auto* order = at(at(lineup, "data"), "order").array();
std::printf("(national line-up: %s)\n", cli::dump_json(lineup).substr(0, 160).c_str());
check(s(at(lineup, "messageType")) == "snapshot" && order && order->size() >= 11, "national line-up read");
check(s(at(tactics, "messageType")) == "snapshot", "national tactics read");
if (order && order->size() >= 11) {
const uint64_t was = rev;
const J kept = session.ui_command(cmd("request:nl" + std::to_string(k), "lineup.commit", O{{"order", J(*order)}}), rev);
std::printf("(national line-up commit: %s)\n", cli::dump_json(kept).substr(0, 200).c_str());
check(s(at(kept, "messageType")) == "command_result" && rev == was + 1, "national line-up commit");
J::Array swapped = *order;
std::swap(swapped[0], swapped[1]);
const J moved = session.ui_command(cmd("request:nm" + std::to_string(k), "lineup.commit", O{{"order", J(swapped)}}), rev);
const J after_swap = session.ui_read(O{{"kind", "lineup"}}, rev);
const auto* now = at(at(after_swap, "data"), "order").array();
check(s(at(moved, "messageType")) == "command_result" && now && s((*now)[0]) == s((*order)[1]),
"national line-up: two players swapped");
}
}
std::printf("(national friendly: %s)\n", cli::dump_json(at(nf, "data")).substr(0, 300).c_str());
national_friendly = 0;
if (dates && !dates->empty()) {
const J day = at(dates->back(), "date");
const uint64_t was = rev;
const J booked = session.ui_command(cmd("request:nf" + std::to_string(k), "friendly.book",
O{{"opponentId", "team:384"}, {"date", day}, {"acceptCost", true}}), rev);
std::printf("(national friendly booked: %s)\n", cli::dump_json(booked).substr(0, 200).c_str());
check(s(at(booked, "messageType")) == "command_result" && rev == was + 1, "national friendly booked");
national_friendly = 1;
}
}
continue;
}
const std::string code = s(at(done, "code"));
const std::string player = s(at(at(at(done, "message"), "args"), "playerId"));
check(code == "decision_pending" && !player.empty() && rev == before, "a pending contract names the player, nothing changed");
if (code != "decision_pending" || player.empty() || expiry.count(player)) break;
expiry[player] = O{{"action", "release"}};
++decisions;
}
check(advances == 120, "two seasons of kickoffs with answered contract decisions");
check(decisions > 0, "running-out contracts were asked for");
std::printf("(date now %s)\n", s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")).c_str());
std::printf("(%d contract decisions answered)\n", decisions);
}
// the press events of the desk's team: stable ids, typed facts, the season's end
{
const J news = session.ui_read(O{{"kind", "news"}, {"limit", 5000}}, rev);
const J again = session.ui_read(O{{"kind", "news"}, {"limit", 5000}}, rev);
const auto* events = at(at(news, "data"), "events").array();
std::set<std::string> ids;
std::map<std::string, int> types;
bool facts = true;
if (events)
for (const auto& e : *events) {
ids.insert(s(at(e, "id")));
++types[s(at(e, "type"))];
if (s(at(e, "type")) == "match.result")
facts &= at(at(at(e, "data"), "score"), "for").integer() && !s(at(at(at(e, "data"), "opponent"), "id")).empty();
}
std::string summary;
for (const auto& [t, n] : types) summary += t + " " + std::to_string(n) + ", ";
std::printf("(news: %zu events: %s)\n", events ? events->size() : 0, summary.c_str());
check(s(at(news, "messageType")) == "snapshot" && events && ids.size() == events->size(), "news with unique ids");
check(cli::dump_json(at(news, "data")) == cli::dump_json(at(again, "data")), "news the same on every read");
check(types["match.result"] > 0 && types["league.position"] > 0 && facts, "match results and the season's end in the news");
{
std::map<std::string, int> journal;
for (const auto& e : std::as_const(session).state().press) ++journal[e.type + "@" + e.team];
std::string all;
for (const auto& [t, n] : journal) all += t + " " + std::to_string(n) + ", ";
std::printf("(journal: %s)\n", all.c_str());
// the confirmed commands above: an advertising contract, a bank credit
const auto noted = [&](const std::string& type) {
for (const auto& e : std::as_const(session).state().press) if (e.type == type) return true;
return false;
};
check(noted("advertising.signed") && noted("finance.loan_approved"), "journal: advertising and credit noted");
check(noted("finance.profit") || noted("finance.loss"), "journal: the months' results");
check(noted("stadium.expansion_finished"), "journal: the planned stand block finished");
}
// the journal: the new season (noted at the kickoff that changed it)
check(types["career.season_started"] > 0, "business events from the journal");
// the journal's squad comparison on copies: a player of another club joins the human
// club (a signing), then goes back (a sale)
{
const modern::ModernState& start = std::as_const(session).state();
const int club = start.manager_teams.empty() ? -1 : start.manager_teams[0];
if (club >= 0 && club < modern::league_clubs()) {
const int other = club == 0 ? 1 : 0;
const SquadRange mine = squad_range(club), theirs = squad_range(other);
size_t free_row = mine.count, from_row = theirs.count;
for (size_t row = 0; row < mine.count && free_row == mine.count; ++row)
if ((start.squad_slots[mine.first + row] & 0x0fff) == 0x0fff) free_row = row;
for (size_t row = 0; row < theirs.count && from_row == theirs.count; ++row)
if ((start.squad_slots[theirs.first + row] & 0x0fff) != 0x0fff) from_row = row;
if (free_row < mine.count && from_row < theirs.count) {
const int p = start.squad_slots[theirs.first + from_row] & 0x0fff;
modern::ModernState joined = start;
joined.squad_slots[mine.first + free_row] = uint16_t((joined.squad_slots[mine.first + free_row] & 0xf000) | p);
joined.squad_slots[theirs.first + from_row] = uint16_t(joined.squad_slots[theirs.first + from_row] | 0x0fff);
modern::journal_advance(joined, start);
modern::ModernState back = joined;
back.squad_slots[mine.first + free_row] = start.squad_slots[mine.first + free_row];
back.squad_slots[theirs.first + from_row] = start.squad_slots[theirs.first + from_row];
modern::journal_advance(back, joined);
std::vector<std::string> types;
for (size_t k = start.press.size(); k < back.press.size(); ++k) types.push_back(back.press[k].type);
check(types == std::vector<std::string>{"transfer.signed", "transfer.sold"}, "journal: a signing and a sale");
const J ev = J(modern::journal_events(back, modern::ui_team_id(back, club), "0000", "9999"));
check(ev.array() && ev.array()->size() >= 2 &&
s(at(at(at(ev.array()->back(), "data"), "toClub"), "id")) == modern::ui_team_id(back, other),
"journal events readable");
}
} else {
std::printf("(journal test skipped: national desk)\n");
}
}
// the manager's employments from the almanac, the desk's allowed commands
{
const J desk = session.ui_read(O{{"kind", "desktop"}}, rev);
const auto* jobs = at(at(at(desk, "data"), "manager"), "employments").array();
const auto* allowed = at(at(at(desk, "meta"), "scope"), "allowedCommands").array();
std::printf("(employments: %s)\n", jobs ? cli::dump_json(J(*jobs)).substr(0, 300).c_str() : "none");
bool advance = false;
if (allowed) for (const auto& a : *allowed) advance |= s(a) == "session.advance";
check(jobs && !jobs->empty() && at((*jobs)[0], "teamId").string(), "employments of the manager");
check(allowed && advance, "allowed commands of the desk");
}
// the mailbox: read, archive (the original's keep), trash and restore one message
{
const J box = session.ui_read(O{{"kind", "news"}}, rev);
const auto* messages = at(at(box, "data"), "messages").array();
std::printf("(mailbox: %zu messages)\n", messages ? messages->size() : 0);
check(messages != nullptr, "news with the mailbox");
if (messages && !messages->empty()) {
const std::string id = s(at(messages->front(), "id"));
const auto folder_of = [&]() {
const J now = session.ui_read(O{{"kind", "news"}}, rev);
if (const auto* list = at(at(now, "data"), "messages").array())
for (const auto& m : *list)
if (s(at(m, "id")) == id) return s(at(m, "folder")) + (truth(at(m, "read")) ? "+read" : "");
return std::string("gone");
};
const auto update = [&](const char* action, int n) {
return session.ui_command(cmd("request:nu" + std::to_string(n), "news.update", O{{"messageId", id}, {"action", action}}), rev);
};
const auto no_op_marks=session.state().news_marks;const auto no_op_revision=rev;
check(s(at(update("unread",0),"outcome"))=="no_change"&&session.state().news_marks==no_op_marks&&rev==no_op_revision,"mailbox: no-op must not create an empty owner map");
update("read", 1);
const std::string after_read = folder_of();
update("archive", 2);
const std::string after_archive = folder_of();
update("trash", 3);
const std::string after_trash = folder_of();
update("restore", 4);
const std::string after_restore = folder_of();
std::printf("(mailbox %s: %s, %s, %s, %s)\n", id.c_str(), after_read.c_str(), after_archive.c_str(),
after_trash.c_str(), after_restore.c_str());
check(after_read == "inbox+read" && after_archive == "archive+read" && after_trash == "trash+read" &&
after_restore == "inbox+read", "mailbox: read, archive, trash, restore");
check(s(at(update("restore", 5), "outcome")) == "no_change", "mailbox: an unchanged mark is no change");
update("unread",7);check(folder_of()=="inbox","mailbox: clearing the last mark is safe");
const auto cleared_marks=session.state().news_marks;const auto cleared_revision=rev;
check(s(at(update("unread",8),"outcome"))=="no_change"&&session.state().news_marks==cleared_marks&&rev==cleared_revision,"mailbox: repeated clearing is write-free");
check(s(at(session.ui_command(cmd("request:nu6", "news.update", O{{"messageId", "message:none"}, {"action", "read"}}), rev), "code")) ==
"unknown_message", "mailbox: unknown message");
}
}
const J few = session.ui_read(O{{"kind", "news"}, {"limit", 3}}, rev);
check(at(at(few, "data"), "events").array() && at(at(few, "data"), "events").array()->size() == 3, "news limit");
}
// 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");
// the statistics screen: real data (fictional false), unrecorded views say so
// (the club views need a club desk: on an international day the manager sits at the national one)
const J minutes = session.read_statistics_screen(O{{"section", 8}});
const bool club_desk = !std::holds_alternative<std::nullptr_t>(at(minutes, "club").value);
check(truth(at(minutes, "ok")) && !truth(at(minutes, "fictional")) &&
(!club_desk || (at(minutes, "rows").array() && at(minutes, "rows").array()->size() == 4)), "minute statistics");
const J transfers = session.read_statistics_screen(O{{"section", 0}});
check(truth(at(transfers, "ok")) && !truth(at(transfers, "available")) && s(at(transfers, "reason")) == "not_recorded",
"title chances 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(!club_desk || (at(curves, "series").array() && at(curves, "series").array()->size() == 6), "the six curves of the original");
}
// the stadium's name and its naming rights
{
const auto ground = [&] { return at(session.ui_read(O{{"kind", "stadium"}}, rev), "data"); };
const J first = ground();
if (first.object() && at(first, "namingOffers").array()) {
check(truth(at(first, "nameEditable")) && at(first, "namingOffers").array()->size() == 3 && std::holds_alternative<std::nullptr_t>(at(first, "namingRights").value),
"stadium: the name is free, three sponsors offer");
const uint64_t n0 = rev;
check(s(at(session.ui_command(cmd("request:n1", "stadium.rename", O{{"name", " "}}), rev), "code")) == "invalid_name" && rev == n0, "an empty stadium name is refused");
const J renamed = session.ui_command(cmd("request:n2", "stadium.rename", O{{"name", "Waldstadion"}}), rev);
check(s(at(renamed, "messageType")) == "command_result" && rev == n0 + 1 && s(at(ground(), "name")) == "Waldstadion", "the stadium is renamed");
const std::string offer = s(at(at(ground(), "namingOffers").array()->front(), "id"));
check(s(at(session.ui_command(cmd("request:n3", "stadium.namingRights", O{{"offerId", offer}}), rev), "code")) == "confirmation_required", "selling the name needs the confirmation");
const J sold = session.ui_command(cmd("request:n4", "stadium.namingRights", O{{"offerId", offer}, {"confirmed", true}}), rev);
const J after = ground();
check(s(at(sold, "messageType")) == "command_result" && rev == n0 + 2 && !truth(at(after, "nameEditable")) && at(after, "namingRights").object() &&
at(after, "namingOffers").array()->empty() && s(at(after, "name")) != "Waldstadion",
"the name is sold: the sponsor's arena, no further offers");
check(s(at(session.ui_command(cmd("request:n5", "stadium.rename", O{{"name", "Nordpark"}}), rev), "code")) == "name_sold" &&
s(at(session.ui_command(cmd("request:n6", "stadium.namingRights", O{{"offerId", offer}, {"confirmed", true}}), rev), "code")) == "name_sold",
"a sold name can be neither changed nor sold again");
}
}
// the annual general meeting and the interested clubs: the read, then a change of club
{
const J meeting = at(session.ui_read(O{{"kind", "assembly"}}, rev), "data");
if (truth(at(meeting, "available"))) {
const J& vote = at(meeting, "vote");
check(vote.object() && at(vote, "yes").integer() && *at(vote, "yes").integer() >= 0 && *at(vote, "yes").integer() <= 100 &&
!truth(at(meeting, "due")) && truth(at(meeting, "dismissals")),
"assembly: a vote, not due in the season, dismissals on");
const auto* offers = at(meeting, "offers").array();
check(offers && !offers->empty() && offers->size() <= 7, "assembly: one to seven interested clubs");
const std::string own = s(at(at(meeting, "club"), "teamId"));
check(cli::dump_json(at(session.ui_read(O{{"kind", "assembly"}}, rev), "data")) == cli::dump_json(meeting), "assembly: reading changes nothing");
const auto change = [&](const std::string& id, J payload) {
return session.ui_command(cmd(id, "manager.clubChange", std::move(payload)), rev);
};
const uint64_t before = rev;
check(s(at(change("request:cc1", O{{"teamId", own}}), "code")) == "confirmation_required", "club change needs the confirmation");
check(s(at(change("request:cc2", O{{"teamId", own}, {"confirmed", true}}), "code")) == "club_change_refused" && rev == before,
"a club that is not interested is refused, nothing changes");
if (offers && !offers->empty()) {
const std::string to = s(at(offers->front(), "teamId"));
const std::string cash = cli::dump_json(at(offers->front(), "cash"));
const J done = change("request:cc3", O{{"teamId", to}, {"confirmed", true}});
if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "club change: %s\n",cli::dump_json(done).c_str());
check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "club change accepted");
const J after = at(session.ui_read(O{{"kind", "assembly"}}, rev), "data");
check(s(at(at(after, "club"), "teamId")) == to, "the manager runs the new club");
const J bank = at(session.ui_read(O{{"kind", "bank"}}, rev), "data");
check(cli::dump_json(bank).find(cash) != std::string::npos, "he starts with the cash the club offered");
const J lineup = at(session.ui_read(O{{"kind", "lineup"}}, rev), "data");
check(lineup.object() != nullptr, "the new club has a line-up to read");
for (int k = 0; k < 3; ++k) {
const J next = session.ui_command(cmd("request:cc-go" + std::to_string(k), "session.advance", O{}), rev);
if (s(at(next, "messageType")) != "command_result") std::fprintf(stderr, "advance after change: %s\n",cli::dump_json(next).c_str());
check(s(at(next, "messageType")) == "command_result", "the game goes on at the new club");
}
}
}
}
// resigning: needs the confirmation; the last human manager ends the career
{
const auto resign = [&](const std::string& id, J payload) {
return session.ui_command(J(O{{"messageType", "command"}, {"requestId", id}, {"expectedRevision", std::to_string(rev)},
{"owner", O{{"managerId", "manager:1"}}}, {"kind", "manager.resign.commit"},
{"payload", std::move(payload)}}), rev);
};
check(s(at(resign("request:r1", O{}), "code")) == "confirmation_required", "resigning needs the confirmation");
const J done = resign("request:r2", O{{"confirmed", true}});
check(s(at(done, "outcome")) == "career_ended", "the last human manager ends the career");
const J ended = at(session.ui_read(O{{"kind", "session"}}, rev), "data");
check(s(at(ended, "sessionState")) == "ended", "session ended");
check(s(at(ended, "terminationReason")) == "last_human_resigned" && !truth(at(ended, "canAdvance")) &&
std::holds_alternative<std::nullptr_t>(at(ended, "activeManagerId").value) &&
at(ended, "archivedManagerIds").array() && at(ended, "archivedManagerIds").array()->size() == 1,
"the ended session: reason, archived manager, no advance");
const J& identity = at(at(done, "ownershipChange"), "archivedIdentity");
const auto* jobs = at(identity, "employments").array();
std::printf("(archived: %s)\n", cli::dump_json(identity).substr(0, 400).c_str());
check(s(at(identity, "control")) == "archived" && s(at(identity, "status")) == "resigned", "the archived identity");
bool resigned_job = false;
if (jobs) for (const auto& j : *jobs) resigned_job |= s(at(j, "endReason")) == "resigned" && at(j, "until").string();
check(resigned_job, "the employment ends with the resignation");
check(!std::as_const(session).state().career_end_reason.empty(), "the end is kept in the state (saved)");
check(s(at(resign("request:r3", O{{"confirmed", true}}), "code")) == "career_ended", "no command after the end");
}
} catch (const std::exception& ex) {
std::fprintf(stderr, "FAIL: %s\n", ex.what());
return 1;
}
if (failures == 0) std::printf("modern ui contract tests passed\n");
return failures == 0 ? 0 : 1;
}