663 lines
47 KiB
C++
663 lines
47 KiB
C++
// SPDX-License-Identifier: GPL-3.0-only
|
||
#include "modern/ui/engine_bridge.hpp"
|
||
#include <algorithm>
|
||
#include <array>
|
||
#include <charconv>
|
||
#include <set>
|
||
#include <limits>
|
||
#include <chrono>
|
||
#include "modern/ui/demo_calendar.hpp"
|
||
|
||
namespace bmh::modern_ui {
|
||
namespace {
|
||
void require(bool yes, const char *message) {
|
||
if (!yes) throw editor::Error(message);
|
||
}
|
||
uint64_t revision(const Json &v) {
|
||
require(v.is_string(), "Engine-Revision ist keine Dezimalzeichenkette.");
|
||
const auto &s = v.get_ref<const std::string &>();
|
||
uint64_t n = 0;
|
||
const auto r = std::from_chars(s.data(), s.data() + s.size(), n);
|
||
require(!s.empty() && r.ec == std::errc() && r.ptr == s.data() + s.size(),
|
||
"Ungültige Engine-Revision.");
|
||
return n;
|
||
}
|
||
}
|
||
int64_t engine_money_minor(const Json &money) {
|
||
require(money.is_object() && money.value("currency", "") == "EUR" &&
|
||
money.value("minorUnits", -1) == 2 && money.at("minor").is_string(),
|
||
"Nicht unterstützte Engine-Geldeinheit.");
|
||
const auto &s = money.at("minor").get_ref<const std::string &>();
|
||
int64_t n = 0;
|
||
const auto r = std::from_chars(s.data(), s.data() + s.size(), n);
|
||
require(!s.empty() && r.ec == std::errc() && r.ptr == s.data() + s.size(),
|
||
"Ungültiger Engine-Geldbetrag.");
|
||
return n;
|
||
}
|
||
void validate_engine_desk(const Json &bundle) {
|
||
const auto &meta = bundle.at("desktop").at("meta");
|
||
(void)revision(meta.at("stateRevision"));
|
||
require(meta.at("careerId").is_string() && !meta.at("careerId").get<std::string>().empty() &&
|
||
meta.at("worldId").is_string() && meta.at("scope").at("managerId").is_string(),
|
||
"Engine-Kontext fehlt.");
|
||
for (const auto *kind : {"session", "desktop", "camps"}) {
|
||
const auto &item = bundle.at(kind);
|
||
require(item.value("messageType", "") == "snapshot" && item.at("data").value("kind", "") == kind,
|
||
"Engine-Ansicht ist nicht verfügbar.");
|
||
const auto &other = item.at("meta");
|
||
for (const auto *key : {"contractVersion", "careerId", "worldId", "worldRevision", "stateRevision", "scope"})
|
||
require(other.at(key) == meta.at(key), "Engine-Ansichten haben unterschiedliche Kontexte.");
|
||
require(other.value("contractVersion", "") == "bmh-modern-ui@draft1", "Unbekannter Engine-Vertrag.");
|
||
}
|
||
const auto &desk = bundle.at("desktop").at("data");
|
||
require(desk.at("manager").at("id") == meta.at("scope").at("managerId") &&
|
||
desk.at("team").at("id") == meta.at("scope").at("teamId"),
|
||
"Manager oder Mannschaft passen nicht zum Engine-Kontext.");
|
||
(void)engine_money_minor(desk.at("accounts").at("cash"));
|
||
std::set<std::string> ids;
|
||
for (const auto &camp : bundle.at("camps").at("data").at("camps"))
|
||
require(camp.at("id").is_string() && ids.insert(camp.at("id").get<std::string>()).second,
|
||
"Doppelte Trainingslager-ID.");
|
||
}
|
||
Json engine_camp_command(const Json &bundle, const std::string &id,
|
||
const Json &focus, const std::string &request_id) {
|
||
validate_engine_desk(bundle);
|
||
require(!request_id.empty(), "Anfrage-ID fehlt.");
|
||
const auto &meta = bundle.at("desktop").at("meta");
|
||
const auto commands = meta.at("scope").value("allowedCommands", Json::array());
|
||
require(commands.is_array() && std::find(commands.begin(), commands.end(), Json("camp.book")) != commands.end(), "Trainingslagerbuchung ist in diesem Kontext gesperrt.");
|
||
require(meta.at("scope").at("role") == "club", "Trainingslager sind am National-Schreibtisch gesperrt.");
|
||
const Json *chosen = nullptr;
|
||
for (const auto &camp : bundle.at("camps").at("data").at("camps"))
|
||
if (camp.at("id") == id) chosen = &camp;
|
||
require(chosen, "Unbekanntes Trainingslager.");
|
||
const auto "e = chosen->at("quote");
|
||
require(quote.is_object() && quote.value("allowed", false), "Dieses Trainingslager kann derzeit nicht gebucht werden.");
|
||
require(quote.at("expectedRevision") == meta.at("stateRevision") &&
|
||
quote.at("ownerManagerId") == meta.at("scope").at("managerId") &&
|
||
quote.at("teamId") == meta.at("scope").at("teamId") &&
|
||
quote.at("scopeId") == meta.at("scope").at("scopeId"),
|
||
"Das Trainingslagerangebot ist veraltet oder gehört einem anderen Manager.");
|
||
require(engine_money_minor(quote.at("total")) >= 0, "Ungültiger Trainingslagerpreis.");
|
||
require(focus.is_object() && focus.size() == 3, "Ungültige Trainingsschwerpunkte.");
|
||
for (const auto *key : {"condition", "technique", "play"})
|
||
require(focus.at(key).is_number_integer() && focus.at(key).get<int64_t>() >= 0 &&
|
||
focus.at(key).get<uint64_t>() <= 15, "Trainingsschwerpunkt außerhalb des Bereichs 0–15.");
|
||
return {{"messageType", "command"}, {"requestId", request_id},
|
||
{"careerId", meta.at("careerId")}, {"expectedRevision", meta.at("stateRevision")},
|
||
{"owner", {{"managerId", meta.at("scope").at("managerId")}}},
|
||
{"kind", "camp.book"}, {"payload", {{"campId", id}, {"focus", focus}}}};
|
||
}
|
||
|
||
namespace {
|
||
const Json &lineup_read(const Json &bundle, const char *kind) {
|
||
const auto &read = bundle.at(kind), &meta = bundle.at("desktop").at("meta");
|
||
require(read.value("messageType", "") == "snapshot" && read.at("data").value("kind", "") == kind,
|
||
"Diese Engine-Ansicht ist in diesem Kontext nicht verfügbar.");
|
||
for (const auto *key : {"contractVersion", "careerId", "worldId", "worldRevision", "stateRevision", "scope"})
|
||
require(read.at("meta").at(key) == meta.at(key), "Engine-Ansichten haben unterschiedliche Kontexte.");
|
||
return read.at("data");
|
||
}
|
||
Json metric_value(const Json &row, const char *key) {
|
||
const auto &metrics = row.at("metrics");
|
||
if (!metrics.contains(key) || !metrics.at(key).is_object()) return nullptr;
|
||
const auto &metric = metrics.at(key);
|
||
if (metric.contains("availability") && metric.at("availability").value("status", "") != "available") return nullptr;
|
||
const auto value = metric.value("value", Json());
|
||
return value.is_number_integer() ? value : Json();
|
||
}
|
||
}
|
||
Json engine_lineup_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &squad = lineup_read(bundle, "squad"), &lineup = lineup_read(bundle, "lineup");
|
||
const auto &team = bundle.at("desktop").at("meta").at("scope").at("teamId");
|
||
require(squad.at("team").at("id") == team && lineup.at("teamId") == team,
|
||
"Aufstellung gehört einer anderen Mannschaft.");
|
||
require(lineup.at("order").is_array() && lineup.at("rows").is_array() && lineup.at("positions").is_array(),
|
||
"Ungültige Aufstellungsdaten.");
|
||
std::map<std::string, Json> members, roles, positions;
|
||
for (const auto &row : squad.at("players")) {
|
||
const auto id = row.at("player").at("id").get<std::string>();
|
||
require(!id.empty() && members.emplace(id, row).second, "Doppelte Spieler-ID im Kader.");
|
||
}
|
||
for (const auto &row : lineup.at("rows"))
|
||
require(roles.emplace(row.at("playerId").get<std::string>(), row.at("role")).second, "Doppelte Aufstellungszeile.");
|
||
for (const auto &point : lineup.at("positions")) {
|
||
const auto id = point.at("playerId").get<std::string>();
|
||
require(members.contains(id) && positions.emplace(id, point).second, "Unbekannte oder doppelte Spielfeldposition.");
|
||
}
|
||
const auto depth_max = lineup.at("depthMax").get<int>(), lane_max = lineup.at("laneMax").get<int>();
|
||
require(depth_max > 0 && lane_max > 0, "Ungültige Spielfeldkoordinaten.");
|
||
Json rows = Json::array(), points = Json::array(); std::set<std::string> ids;
|
||
for (const auto &value : lineup.at("order")) {
|
||
const auto id = value.get<std::string>();
|
||
require(members.contains(id) && roles.contains(id) && ids.insert(id).second, "Aufstellung enthält fremde oder doppelte Spieler.");
|
||
const auto &raw = members.at(id), &person = raw.at("player");
|
||
Json row = {{"id", id}, {"name", person.at("name")}, {"slot", rows.size()},
|
||
{"position", person.at("positions").empty() ? Json() : person.at("positions")[0]},
|
||
{"nation", person.at("nationIds").empty() ? Json() : person.at("nationIds")[0]},
|
||
{"role", roles.at(id)}, {"availability", raw.at("availability")}, {"age", raw.at("age")}};
|
||
for (const auto *key : {"condition", "technique", "form", "strength"}) row[key] = metric_value(raw, key);
|
||
for (const auto *key : {"corner", "free_kick", "tackling", "passing", "shooting", "speed", "teamplay"})
|
||
row[key] = raw.at("skills").value(key, Json());
|
||
for (const auto *key : {"motivation", "goals", "assists", "games", "grade"}) row[key] = nullptr;
|
||
const auto role = roles.at(id).get<std::string>();
|
||
require(role == "starter" || role == "bench" || role == "reserve", "Unbekannter Kaderstatus.");
|
||
row["status"] = role == "starter" ? "Startelf" : role == "bench" ? "Ersatzbank" : "—";
|
||
rows.push_back(std::move(row));
|
||
if (points.size() < lineup.at("positions").size()) {
|
||
if (!positions.contains(id)) points.push_back(nullptr);
|
||
else {
|
||
const auto &point = positions.at(id); const int x = point.at("depth"), y = point.at("lane");
|
||
points.push_back(x >= 0 && x <= depth_max && y >= 0 && y <= lane_max ? Json::array({x, y}) : Json());
|
||
}
|
||
}
|
||
}
|
||
require(ids.size() == members.size() && ids.size() == roles.size(), "Aufstellung enthält nicht den vollständigen Kader.");
|
||
return {{"ok", true}, {"rows", rows}, {"field_count", points.size()},
|
||
{"board", {{"order", lineup.at("order")}, {"points", points}, {"depth_max", depth_max}, {"lane_max", lane_max}}}};
|
||
}
|
||
Json engine_lineup_command(const Json &bundle, const Json &order, const std::string &request_id) {
|
||
const auto projection = engine_lineup_projection(bundle);
|
||
const auto &meta = bundle.at("desktop").at("meta");
|
||
const auto commands = meta.at("scope").value("allowedCommands", Json::array());
|
||
require(!request_id.empty() && commands.is_array() && std::find(commands.begin(), commands.end(), Json("lineup.commit")) != commands.end(),
|
||
"Aufstellungsänderungen sind in diesem Kontext gesperrt.");
|
||
require(order.is_array() && order.size() == projection.at("board").at("order").size(), "Der vollständige Kader wird benötigt.");
|
||
std::set<std::string> expected, proposed;
|
||
for (const auto &id : projection.at("board").at("order")) expected.insert(id.get<std::string>());
|
||
for (const auto &id : order) require(id.is_string() && proposed.insert(id.get<std::string>()).second, "Doppelte oder ungültige Spieler-ID.");
|
||
require(proposed == expected, "Die Aufstellung enthält fremde oder fehlende Spieler.");
|
||
return {{"messageType", "command"}, {"requestId", request_id}, {"careerId", meta.at("careerId")},
|
||
{"expectedRevision", meta.at("stateRevision")}, {"owner", {{"managerId", meta.at("scope").at("managerId")}}},
|
||
{"kind", "lineup.commit"}, {"payload", {{"order", order}}}};
|
||
}
|
||
|
||
namespace {
|
||
Json sports_command(const Json &bundle, const char *kind, const Json &payload, const std::string &id) {
|
||
validate_engine_desk(bundle);
|
||
const auto &meta = bundle.at("desktop").at("meta");
|
||
const auto commands = meta.at("scope").value("allowedCommands", Json::array());
|
||
require(!id.empty() && commands.is_array() && std::find(commands.begin(), commands.end(), Json(kind)) != commands.end(),
|
||
"Diese Änderung ist im aktuellen Kontext nicht verfügbar.");
|
||
return {{"messageType", "command"}, {"requestId", id}, {"careerId", meta.at("careerId")},
|
||
{"expectedRevision", meta.at("stateRevision")}, {"owner", {{"managerId", meta.at("scope").at("managerId")}}},
|
||
{"kind", kind}, {"payload", payload}};
|
||
}
|
||
int whole_in_range(const Json &v, int lo, int hi) {
|
||
require(v.is_number_integer() && v.get<int64_t>() >= lo && v.get<int64_t>() <= hi,
|
||
"Wert außerhalb des verfügbaren Bereichs.");
|
||
return v.get<int>();
|
||
}
|
||
}
|
||
Json engine_tactics_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "tactics");
|
||
require(data.at("teamId") == bundle.at("desktop").at("meta").at("scope").at("teamId"), "Taktik gehört einer anderen Mannschaft.");
|
||
require(data.at("controls").is_array() && data.at("controls").size() == 8, "Unvollständige Taktikeinstellungen.");
|
||
Json out = {{"values", Json::array()}, {"limits", Json::array()}, {"minima", Json::array()}, {"labels", Json::array()}};
|
||
// These bounds describe the existing board's visual capacity, not engine rules.
|
||
const std::array<int, 8> visual_limits{3,3,3,3,1,1,1,11};
|
||
for (int i = 0; i < 8; ++i) {
|
||
const Json *control = nullptr;
|
||
for (const auto &item : data.at("controls")) if (item.at("id") == "tactic:" + std::to_string(i)) {
|
||
require(!control, "Doppelte Taktik-ID."); control = &item;
|
||
}
|
||
require(control, "Taktikeinstellung fehlt.");
|
||
const auto &range = control->at("range");
|
||
const int lo = whole_in_range(range.at("min"), 0, visual_limits[size_t(i)]);
|
||
const int hi = whole_in_range(range.at("max"), lo, visual_limits[size_t(i)]);
|
||
require(range.at("step") == 1, "Diese Taktikschrittweite wird noch nicht dargestellt.");
|
||
out["values"].push_back(whole_in_range(control->at("value"), lo, hi));
|
||
out["limits"].push_back(hi); out["minima"].push_back(lo);
|
||
out["labels"].push_back(control->at("label").at("text"));
|
||
}
|
||
const auto board = engine_lineup_projection(bundle).at("board");
|
||
require(board.at("points").size() == 11, "Die Taktiktafel benötigt gelieferte Spielfeldpositionen.");
|
||
std::set<std::string> occupied;
|
||
for (const auto &point : board.at("points")) require(point.is_array() && occupied.insert(point.dump()).second, "Spielfeldpositionen sind nicht vollständig bekannt.");
|
||
out["board"] = board;
|
||
return out;
|
||
}
|
||
Json engine_tactics_command(const Json &bundle, const Json &values, const std::string &id) {
|
||
const auto base = engine_tactics_projection(bundle);
|
||
require(values.is_array() && values.size() == 8, "Acht Taktikwerte werden benötigt.");
|
||
for (size_t i = 0; i < 8; ++i) (void)whole_in_range(values[i], base.at("minima")[i], base.at("limits")[i]);
|
||
return sports_command(bundle, "tactics.commit", {{"values", values}}, id);
|
||
}
|
||
Json engine_training_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "training"), &squad = lineup_read(bundle, "squad");
|
||
const auto &team = bundle.at("desktop").at("meta").at("scope").at("teamId");
|
||
require(data.at("teamId") == team && squad.at("team").at("id") == team, "Training gehört einer anderen Mannschaft.");
|
||
Json out = {{"club", team}, {"types", Json::array()}, {"areas", Json::array()}, {"players", Json::object()},
|
||
{"roster", Json::array()}, {"initialized", data.at("initialized")}, {"limits", data.at("limits")}};
|
||
const auto group = [&](const char *name, const std::vector<std::string> &ids) {
|
||
require(data.at(name).is_array() && data.at(name).size() == ids.size(), "Unvollständiger Trainingsplan.");
|
||
for (const auto &id : ids) {
|
||
const Json *chosen = nullptr;
|
||
for (const auto &item : data.at(name)) if (item.at("id") == id) { require(!chosen, "Doppelte Trainings-ID."); chosen = &item; }
|
||
require(chosen && chosen->at("min") == 1 && chosen->at("max") == 3, "Trainingsgruppe wird nicht unterstützt.");
|
||
out[name].push_back(whole_in_range(chosen->at("allocation"), 1, 3));
|
||
}
|
||
};
|
||
group("types", {"training:type/goalkeepers", "training:type/defence", "training:type/midfield", "training:type/attack"});
|
||
group("areas", {"training:area/fitness", "training:area/skill", "training:area/corner", "training:area/free_kick", "training:area/tackling", "training:area/pass", "training:area/shot", "training:area/speed", "training:area/game"});
|
||
std::map<std::string, Json> people;
|
||
for (const auto &row : squad.at("players")) require(people.emplace(row.at("player").at("id").get<std::string>(), row).second, "Doppelter Kaderspieler.");
|
||
for (const auto &row : data.at("players")) {
|
||
const auto id = row.at("playerId").get<std::string>();
|
||
require(people.contains(id) && !out.at("players").contains(id), "Fremder oder doppelter Trainingsspieler.");
|
||
const auto &person = people.at(id);
|
||
out["players"][id] = {{"intensity", whole_in_range(row.at("intensity"), 0, 3)}, {"focus", whole_in_range(row.at("focus"), 0, 7)}};
|
||
out["roster"].push_back({{"id", id}, {"name", person.at("player").at("name")}, {"positions", person.at("player").at("positions")},
|
||
{"attributes", {{"strength", metric_value(person, "strength")}}}});
|
||
}
|
||
require(out.at("players").size() == people.size(), "Trainingskader ist unvollständig.");
|
||
const int automation = whole_in_range(data.at("automation"), 0, 255);
|
||
// Reflect the original screen's four stored subordinate flags. This client
|
||
// never writes the automation byte; only the engine changes it on commit.
|
||
out["autos"] = Json::array({bool(automation & 2), bool(automation & 4), bool(automation & 8), bool(automation & 16)});
|
||
out["master_auto"] = bool(automation & 1);
|
||
return out;
|
||
}
|
||
Json engine_training_command(const Json &bundle, const Json &draft, const std::string &id) {
|
||
const auto base = engine_training_projection(bundle);
|
||
for (const auto *group : {"types", "areas"}) {
|
||
require(draft.at(group).is_array() && draft.at(group).size() == base.at(group).size(), "Trainingsplan ist unvollständig.");
|
||
for (const auto &n : draft.at(group)) (void)whole_in_range(n, 1, 3);
|
||
}
|
||
int types = 0, fitness = 0, areas = 0;
|
||
for (const auto &v : draft.at("types")) types += v.get<int>();
|
||
for (size_t i = 0; i < 9; ++i) (i < 2 ? fitness : areas) += draft.at("areas")[i].get<int>();
|
||
require(types <= base.at("limits").at("types").get<int>() && fitness <= base.at("limits").at("fitnessAndSkill").get<int>() && areas <= base.at("limits").at("otherAreas").get<int>(), "Ballbudget überschritten.");
|
||
require(draft.at("players").is_object() && draft.at("players").size() == base.at("players").size(), "Trainingskader ist unvollständig.");
|
||
Json changed = Json::array();
|
||
for (const auto &[pid, row] : draft.at("players").items()) {
|
||
require(base.at("players").contains(pid) && row.at("focus") == base.at("players").at(pid).at("focus"), "Spielerschwerpunkte sind noch schreibgeschützt.");
|
||
if (row.at("intensity") != base.at("players").at(pid).at("intensity"))
|
||
changed.push_back({{"playerId", pid}, {"intensity", whole_in_range(row.at("intensity"), 1, 3)}});
|
||
}
|
||
return sports_command(bundle, "training.commit", {{"types", draft.at("types")}, {"areas", draft.at("areas")}, {"players", changed}}, id);
|
||
}
|
||
|
||
Json engine_bank_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "bank");
|
||
require(data.at("teamId") == bundle.at("desktop").at("meta").at("scope").at("teamId"), "Bank gehört einer anderen Mannschaft.");
|
||
const auto &accounts = data.at("accounts");
|
||
const auto cash = engine_money_minor(accounts.at("cash")), deposit = engine_money_minor(accounts.at("deposit"));
|
||
require(cash == engine_money_minor(bundle.at("desktop").at("data").at("accounts").at("cash")) && deposit >= 0, "Widersprüchliche Kontostände.");
|
||
Json assets = {{"stocks", Json::array()}, {"properties", Json::array()}};
|
||
Json finance = {{"stocks", Json::array()}, {"properties", Json::array()}};
|
||
int64_t properties = 0, stocks = 0;
|
||
for (const auto *key : {"stocks", "funds"}) {
|
||
const bool stock = std::string(key) == "stocks";
|
||
const auto dest = stock ? "stocks" : "properties";
|
||
const auto &rows = data.at(key);
|
||
require(rows.is_array() && !rows.empty() && rows.size() <= size_t(stock ? 12 : 6), "Ungültiger Bankkatalog.");
|
||
std::set<std::string> ids;
|
||
for (const auto &row : rows) {
|
||
const auto id = row.at("id").get<std::string>();
|
||
bool known = false;
|
||
for (int i = 0; i < (stock ? 12 : 6); ++i) known |= id == std::string(stock ? "stock:" : "fund:") + std::to_string(i);
|
||
require(known && ids.insert(id).second, "Unbekannte oder doppelte Bankanlage.");
|
||
const auto price = engine_money_minor(row.at("price"));
|
||
const int owned = whole_in_range(row.at("owned"), 0, 65535), max = whole_in_range(row.at("maxToBuy"), 0, 99999999);
|
||
require(price >= 0 && price <= 99999999999LL, "Ungültiger Anlagenpreis.");
|
||
require(price == 0 || max <= std::numeric_limits<int64_t>::max() / price, "Anlagengesamtpreis ist zu groß.");
|
||
std::string name = row.at("name").is_string() ? row.at("name").get<std::string>() : row.at("name").value("text", "");
|
||
// A missing backend label is identified, never filled from a demo company.
|
||
if (name.empty() || name.starts_with("%%")) name = std::string(stock ? "Aktie · " : "Immobilie · ") + id;
|
||
Json item = {{"id", id}, {"name", name}, {"price", price}, {"owned", owned}, {"maxToBuy", max}};
|
||
if (stock) {
|
||
item["previous"] = engine_money_minor(row.at("previousPrice"));
|
||
item["history"] = Json::array();
|
||
require(row.at("history").is_array() && row.at("history").size() <= 1000, "Ungültiger Kursverlauf.");
|
||
for (const auto &point : row.at("history")) item["history"].push_back(engine_money_minor(point));
|
||
stocks += price * owned;
|
||
} else {
|
||
item["image"] = "bank.property." + id.substr(5);
|
||
properties += price * owned;
|
||
}
|
||
assets[dest].push_back(item); finance[dest].push_back(owned);
|
||
}
|
||
}
|
||
return {{"assets", assets}, {"state", {{"deposit", deposit}, {"finance", finance}}},
|
||
{"summary", {{"ok", true}, {"cash", cash}, {"deposit", deposit}, {"properties", properties}, {"stocks", stocks},
|
||
{"credit_line", engine_money_minor(accounts.at("creditLine"))}}}};
|
||
}
|
||
Json engine_bank_command(const Json &bundle, const Json &payload, const std::string &request_id) {
|
||
const auto projection = engine_bank_projection(bundle);
|
||
const auto action = payload.at("action").get<std::string>();
|
||
if (action == "deposit" || action == "withdraw") {
|
||
require(payload.size() == 2, "Ungültiger Bankauftrag.");
|
||
const auto amount = engine_money_minor(payload.at("amount"));
|
||
require(amount > 0 && amount % 100 == 0 && amount <= 9999999900LL &&
|
||
amount <= projection.at("summary").at(action == "deposit" ? "cash" : "deposit").get<int64_t>(), "Betrag überschreitet das verfügbare Guthaben.");
|
||
} else if (action == "buy" || action == "sell") {
|
||
require(payload.size() == 3, "Ungültiger Anlagenauftrag.");
|
||
const auto id = payload.at("assetId").get<std::string>();
|
||
const Json *asset = nullptr;
|
||
for (const auto *key : {"stocks", "properties"}) for (const auto &row : projection.at("assets").at(key)) if (row.at("id") == id) asset = &row;
|
||
require(asset, "Unbekannte Bankanlage.");
|
||
(void)whole_in_range(payload.at("count"), 1, asset->at(action == "buy" ? "maxToBuy" : "owned").get<int>());
|
||
} else require(false, "Nicht unterstützter Bankauftrag.");
|
||
return sports_command(bundle, "bank.commit", payload, request_id);
|
||
}
|
||
Json engine_ticket_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "stadium");
|
||
require(data.at("teamId") == bundle.at("desktop").at("meta").at("scope").at("teamId"), "Eintritt gehört einer anderen Mannschaft.");
|
||
const auto price = engine_money_minor(data.at("ticketPrice"));
|
||
const auto lo = engine_money_minor(data.at("ticketPriceRange").at("min")), hi = engine_money_minor(data.at("ticketPriceRange").at("max"));
|
||
require(lo >= 0 && hi <= 9999999900LL && lo <= price && price <= hi && lo % 100 == 0 && hi % 100 == 0 && price % 100 == 0, "Ungültige Eintrittspreise.");
|
||
return {{"ticket", price / 100}, {"min", lo / 100}, {"max", hi / 100}};
|
||
}
|
||
Json engine_ticket_command(const Json &bundle, int euros, const std::string &request_id) {
|
||
const auto price = engine_ticket_projection(bundle);
|
||
require(euros >= price.at("min").get<int64_t>() && euros <= price.at("max").get<int64_t>(), "Eintritt außerhalb des erlaubten Bereichs.");
|
||
return sports_command(bundle, "ticket.commit", {{"price", {{"currency", "EUR"}, {"minorUnits", 2}, {"minor", std::to_string(int64_t(euros) * 100)}}}}, request_id);
|
||
}
|
||
|
||
Json engine_credit_projection(const Json &bundle, const Json &read) {
|
||
validate_engine_desk(bundle);
|
||
auto context = bundle; context["credit"] = read;
|
||
const auto data = lineup_read(context, "credit");
|
||
require(data.at("lenderId") == "bank" && data.at("fields").is_array() && data.at("fields").size() == 8 && data.at("saved").size() == 6,
|
||
"Ungültige Kreditansicht.");
|
||
for (int i = 0; i < 8; ++i) {
|
||
const auto &f = data.at("fields")[size_t(i)];
|
||
require(f.at("field") == i && f.at("editable").is_boolean(), "Ungültiges Kreditfeld.");
|
||
(void)whole_in_range(f.at("value"), 0, INT32_MAX);
|
||
if (f.at("editable") == true) {
|
||
const auto lo = whole_in_range(f.at("min"), 0, INT32_MAX), hi = whole_in_range(f.at("max"), lo, INT32_MAX);
|
||
(void)hi;
|
||
}
|
||
}
|
||
for (const auto *key : {"fees", "refund", "principalPaid"}) require(engine_money_minor(data.at(key)) >= 0, "Ungültige Kreditkosten.");
|
||
return data;
|
||
}
|
||
Json engine_credit_command(const Json &bundle, const Json &read, const Json &edits, const std::string &request_id) {
|
||
const auto credit = engine_credit_projection(bundle, read);
|
||
require(credit.at("saved")[0] == 0, "Für Änderungen laufender Kredite fehlt noch die vollständige Gebührenvorschau.");
|
||
require(edits.is_array() && !edits.empty() && edits.size() <= 64, "Keine gültigen Kreditänderungen.");
|
||
for (const auto &e : edits) {
|
||
require(e.is_object() && e.size() == 2, "Ungültige Kreditänderung.");
|
||
(void)whole_in_range(e.at("field"), 0, 7); (void)whole_in_range(e.at("value"), 0, 99999999);
|
||
}
|
||
// The engine replays this ordered edit list and owns fees and all loan maths.
|
||
return sports_command(bundle, "bank.commit", {{"action", "credit"}, {"lenderId", "bank"}, {"edits", edits}, {"acceptFees", true}}, request_id);
|
||
}
|
||
|
||
Json engine_environment_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "environment");
|
||
require(bundle.at("desktop").at("meta").at("scope").at("role") == "club", "Umfeld ist nur am Vereinsschreibtisch verfügbar.");
|
||
const std::array<const char *, 6> keys{"youth_youngest", "youth_academy", "youth_oldest", "co_trainer", "doctor", "physio"};
|
||
const std::array<const char *, 6> ids{"youth-a", "youth-b", "youth-c", "coach", "doctor", "physio"};
|
||
const std::array<const char *, 6> names{"Nachwuchs · Jüngste", "Nachwuchs · Mittlere", "Nachwuchs · Ältere", "Co-Trainer", "Vereinsarzt", "Masseur"};
|
||
require(data.at("items").is_array() && data.at("items").size() == 6 && data.at("youth").is_array() && data.at("youth").size() == 3, "Unvollständiges Umfeld.");
|
||
Json rows = Json::array(); std::set<std::string> seen;
|
||
for (size_t i = 0; i < keys.size(); ++i) {
|
||
const std::string id = std::string("environment:") + keys[i];
|
||
const Json *item = nullptr, *youth = nullptr;
|
||
for (const auto &r : data.at("items")) if (r.at("id") == id) { require(!item, "Doppelte Umfeld-ID."); item = &r; }
|
||
require(item, "Unbekannte Umfeldzuordnung.");
|
||
const int max = whole_in_range(item->at("maxLevel"), 0, 6), level = whole_in_range(item->at("level"), 0, max);
|
||
const auto cost = engine_money_minor(item->at("monthly")), step = engine_money_minor(item->at("stepCost"));
|
||
require(cost >= 0 && step >= 0 && step <= std::numeric_limits<int64_t>::max() / 6, "Ungültige Umfeldkosten.");
|
||
Json row = {{"id", ids[i]}, {"engine_id", id}, {"name", names[i]}, {"level", level}, {"max", max}, {"cost", cost}, {"step", step},
|
||
{"image", i < 3 ? "youth" : "staff"}, {"cell", i < 3 ? int(i) : int(i - 3)}, {"rank", nullptr}, {"league", nullptr}};
|
||
if (i < 3) {
|
||
for (const auto &y : data.at("youth")) if (y.at("id") == std::string("youth:") + keys[i]) { require(!youth, "Doppelte Nachwuchs-ID."); youth = &y; }
|
||
require(youth, "Nachwuchsmannschaft fehlt.");
|
||
// Like the original presenter: the stored place/league are zero-based.
|
||
row["rank"] = whole_in_range(youth->at("place"), 0, 11) + 1;
|
||
row["league"] = whole_in_range(youth->at("league"), 0, 2) + 1;
|
||
}
|
||
rows.push_back(row);
|
||
}
|
||
return {{"ok", true}, {"rows", rows}};
|
||
}
|
||
Json engine_environment_command(const Json &bundle, const std::string &id, int level, const std::string &request_id) {
|
||
const auto view = engine_environment_projection(bundle);
|
||
const Json *item = nullptr;
|
||
for (const auto &row : view.at("rows")) if (row.at("engine_id") == id) item = &row;
|
||
require(item && level >= 0 && level <= item->at("max").get<int>(), "Unbekannte Umfeldstufe.");
|
||
return sports_command(bundle, "environment.commit", {{"itemId", id}, {"level", level}}, request_id);
|
||
}
|
||
namespace {
|
||
std::string business_text(const Json &v) {
|
||
if (v.is_null()) return "—";
|
||
return v.is_string() ? v.get<std::string>() : v.value("text", "—");
|
||
}
|
||
}
|
||
Json engine_advertising_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "advertising");
|
||
require(data.at("teamId") == bundle.at("desktop").at("meta").at("scope").at("teamId"), "Werbung gehört einer anderen Mannschaft.");
|
||
require(data.at("boards").is_array() && data.at("boards").size() == 14 && data.at("budgets").is_array() && data.at("budgets").size() == 3, "Unvollständige Werbung.");
|
||
const auto commands = bundle.at("desktop").at("meta").at("scope").value("allowedCommands", Json::array());
|
||
const bool contracts_allowed = commands.is_array() && std::find(commands.begin(), commands.end(), Json("advertising.accept")) != commands.end();
|
||
const bool budgets_allowed = commands.is_array() && std::find(commands.begin(), commands.end(), Json("budget.commit")) != commands.end();
|
||
Json slots = Json::array(), spending = Json::array();
|
||
for (int i = 0; i < 16; ++i) {
|
||
const std::string id = i < 14 ? "ad:board/" + std::to_string(i) : i == 14 ? "ad:shirt" : "ad:tv";
|
||
const std::string label = i < 14 ? "Bande " + std::to_string(i + 1) : i == 14 ? "Trikotwerbung" : "TV-Rechte";
|
||
const Json *raw = i == 14 ? &data.at("shirt") : i == 15 ? &data.at("television") : nullptr;
|
||
if (i < 14) for (const auto &row : data.at("boards")) if (row.at("id") == id) { require(!raw, "Doppelte Werbefläche."); raw = &row; }
|
||
require(raw && raw->at("id") == id && raw->at("active").is_boolean(), "Ungültige Werbefläche.");
|
||
const bool active = raw->at("active");
|
||
const auto amount = engine_money_minor(raw->at("monthly"));
|
||
require(amount >= 0, "Ungültiger Werbebetrag.");
|
||
Json slot = {{"id", id}, {"slot", i}, {"label", label}, {"active", active}, {"name", active ? business_text(raw->at("sponsor")) : "Platz frei"},
|
||
{"sponsor", active ? 0 : -1}, {"amount", amount}, {"months", whole_in_range(raw->at("monthsRemaining"), 0, 255)}, {"choices", Json::array()}};
|
||
// sponsor here is only an artwork switch; commands use the exact offer ID.
|
||
auto current = slot; current.erase("choices"); current["can_accept"] = false; current["boards"] = 1; current["offer_id"] = nullptr;
|
||
if (active) slot["choices"].push_back(current);
|
||
require(raw->at("offers").is_array() && raw->at("offers").size() <= 200, "Ungültige Angebotsliste.");
|
||
std::set<std::string> seen;
|
||
for (const auto &offer : raw->at("offers")) {
|
||
const auto offer_id = offer.at("id").get<std::string>(), prefix = "offer:ad-" + std::to_string(i) + "-";
|
||
require(offer_id.starts_with(prefix) && offer_id.size() > prefix.size() &&
|
||
offer_id.find_first_not_of("0123456789", prefix.size()) == std::string::npos && seen.insert(offer_id).second, "Angebot gehört einer anderen Werbefläche.");
|
||
require(offer.at("allowed").is_boolean(), "Angebotssperre fehlt.");
|
||
const auto monthly = engine_money_minor(offer.at("monthly")); require(monthly >= 0, "Ungültiger Angebotspreis.");
|
||
slot["choices"].push_back({{"offer_id", offer_id}, {"name", business_text(offer.at("sponsor"))}, {"label", label}, {"sponsor", 0},
|
||
{"amount", monthly}, {"months", whole_in_range(offer.at("months"), 1, 255)}, {"boards", whole_in_range(offer.at("boards"), 1, 14)}, {"active", false}, {"can_accept", offer.at("allowed") == true && contracts_allowed}});
|
||
}
|
||
if (slot["choices"].empty()) { current["name"] = "Keine Angebote"; slot["choices"].push_back(current); }
|
||
slots.push_back(slot);
|
||
}
|
||
const std::array<const char *, 3> budget_ids{"budget:merchandise", "budget:press", "budget:fans"}, names{"Fanartikel", "Öffentlichkeitsarbeit", "Fanbetreuung"};
|
||
for (size_t i = 0; i < 3; ++i) {
|
||
const Json *row = nullptr;
|
||
for (const auto &r : data.at("budgets")) if (r.at("id") == budget_ids[i]) { require(!row, "Doppeltes Werbebudget."); row = &r; }
|
||
require(row && row->at("available").is_boolean(), "Werbebudget fehlt.");
|
||
const auto current = engine_money_minor(row->at("current")), max = engine_money_minor(row->at("maximum"));
|
||
require(current >= 0 && current % 100 == 0 && max >= 0 && max % 100 == 0, "Ungültige Budgetgrenzen.");
|
||
spending.push_back({{"id", budget_ids[i]}, {"name", names[i]}, {"amount", current}, {"max", max}, {"available", row->at("available") == true && budgets_allowed},
|
||
{"delivery_weeks", whole_in_range(row->at("deliveryWeeks"), 0, 255)}, {"suggestion_step", i == 0 ? 50000 : 5000}});
|
||
}
|
||
return {{"ok", true}, {"slots", slots}, {"spending", spending}, {"income", engine_money_minor(data.at("preview").at("income"))},
|
||
{"expenses", engine_money_minor(data.at("preview").at("expenses"))}, {"balance", engine_money_minor(data.at("preview").at("balance"))}};
|
||
}
|
||
Json engine_advertising_quote(const Json &bundle, int slot, int choice) {
|
||
const auto view = engine_advertising_projection(bundle);
|
||
require(slot >= 0 && slot < 16, "Unbekannte Werbefläche.");
|
||
const auto &choices = view.at("slots")[size_t(slot)].at("choices");
|
||
require(choice >= 0 && size_t(choice) < choices.size(), "Unbekanntes Werbeangebot.");
|
||
auto out = choices[size_t(choice)]; out["can_cycle"] = choices.size() > 1;
|
||
return out;
|
||
}
|
||
Json engine_advertising_command(const Json &bundle, const std::string &id, const std::string &request_id) {
|
||
const auto view = engine_advertising_projection(bundle); bool allowed = false;
|
||
for (const auto &s : view.at("slots")) for (const auto &c : s.at("choices")) if (c.at("offer_id") == id) allowed = c.at("can_accept");
|
||
require(allowed, "Dieses Werbeangebot ist nicht mehr verfügbar.");
|
||
return sports_command(bundle, "advertising.accept", {{"offerId", id}}, request_id);
|
||
}
|
||
Json engine_budget_command(const Json &bundle, const std::string &id, int64_t euros, const std::string &request_id) {
|
||
const auto view = engine_advertising_projection(bundle); const Json *row = nullptr;
|
||
for (const auto &r : view.at("spending")) if (r.at("id") == id) row = &r;
|
||
require(row && row->at("available") == true && row->at("delivery_weeks") == 0 && euros >= 0 && euros <= 99999999 && euros <= row->at("max").get<int64_t>() / 100,
|
||
"Budget ist gesperrt oder außerhalb des verfügbaren Bereichs.");
|
||
return sports_command(bundle, "budget.commit", {{"budgetId", id}, {"amount", {{"currency", "EUR"}, {"minorUnits", 2}, {"minor", std::to_string(euros * 100)}}}}, request_id);
|
||
}
|
||
|
||
Json engine_contracts_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &data = lineup_read(bundle, "contracts"), &meta = bundle.at("desktop").at("meta");
|
||
require(data.at("teamId") == meta.at("scope").at("teamId"), "Verträge gehören einer anderen Mannschaft.");
|
||
const auto squad = engine_lineup_projection(bundle);
|
||
require(data.at("players").is_array() && data.at("players").size() == squad.at("rows").size(), "Verträge und Kader passen nicht zusammen.");
|
||
const auto commands = meta.at("scope").value("allowedCommands", Json::array());
|
||
const auto allowed = [&](const char *name) { return commands.is_array() && std::find(commands.begin(), commands.end(), Json(name)) != commands.end(); };
|
||
Json rows = Json::array(); int64_t total = 0; std::set<std::string> ids;
|
||
for (const auto &member : squad.at("rows")) {
|
||
const Json *person = nullptr; const auto id = member.at("id").get<std::string>();
|
||
for (const auto &p : data.at("players")) if (p.at("playerId") == id) { require(!person, "Doppelte Vertrags-ID."); person = &p; }
|
||
require(person, "Vertrag fehlt für einen Kaderspieler.");
|
||
auto row = member;
|
||
const auto salary = engine_money_minor(person->at("salaryMonthly"));
|
||
require(salary >= 0 && salary <= std::numeric_limits<int64_t>::max() - total, "Ungültiges Monatsgehalt."); total += salary;
|
||
require(person->at("contractRemaining").at("unit") == "months" && person->at("offerBlocked").is_boolean(), "Unbekannte Vertragseinheit oder Sperre.");
|
||
row["name"] = person->at("name"); row["position"] = person->at("position");
|
||
row["age"] = whole_in_range(person->at("age"), 0, 255);
|
||
row["salary"] = salary; row["months"] = whole_in_range(person->at("contractRemaining").at("value"), 0, 255);
|
||
row["insurance"] = whole_in_range(person->at("insuranceMonths"), 0, 255);
|
||
row["insurance_fee"] = engine_money_minor(person->at("insuranceFee"));
|
||
require(row.at("insurance_fee").get<int64_t>() >= 0, "Ungültiger Versicherungsbetrag.");
|
||
row["source_label"] = "Aktuelles Monatsgehalt";
|
||
row["shoot"] = member.at("shooting"); row["pass"] = member.at("passing"); row["team"] = member.at("teamplay");
|
||
row["can_request"] = !person->at("offerBlocked").get<bool>() && allowed("quote.request") && allowed("contract.offer") && allowed("contract.cancel");
|
||
require(person->at("bonuses").is_array() && person->at("bonuses").size() == 7, "Unvollständige Prämienstufen.");
|
||
row["premiums"] = Json::array(); for (const auto &v : person->at("bonuses")) row["premiums"].push_back(whole_in_range(v, 0, 255));
|
||
rows.push_back(row); ids.insert(id);
|
||
}
|
||
Json quote;
|
||
if (!data.at("quote").is_null()) {
|
||
const auto &q = data.at("quote"); const auto id = q.at("id").get<std::string>();
|
||
require(id.starts_with("quote:contract-") && id.size() > 15 && q.at("playerId").is_string() && ids.contains(q.at("playerId").get<std::string>()), "Verhandlung gehört einem fremden Spieler.");
|
||
require(q.at("demands").is_array() && q.at("demands").size() == 4, "Unvollständige Gehaltsforderungen.");
|
||
const auto max = engine_money_minor(q.at("maxMonthlySalary"));
|
||
require(max >= 0 && max % 100 == 0 && max <= 9999999900LL, "Ungültige Gehaltsgrenze.");
|
||
Json demands = Json::array({nullptr,nullptr,nullptr,nullptr}); std::set<int> terms;
|
||
for (const auto &d : q.at("demands")) {
|
||
const int years = whole_in_range(d.at("years"), 1, 4); require(terms.insert(years).second, "Doppelte Vertragslaufzeit.");
|
||
const auto amount = engine_money_minor(d.at("monthlyDemand")); require(amount >= 0 && amount % 100 == 0, "Ungültige Gehaltsforderung.");
|
||
// The legacy contract service uses zero / UINT32_MAX for unavailable terms.
|
||
if (amount > 0 && amount != 429496729500LL) demands[size_t(years - 1)] = amount;
|
||
}
|
||
quote = {{"id", id}, {"player", q.at("playerId")}, {"demands", demands}, {"max_salary", max}, {"can_offer", allowed("contract.offer")}};
|
||
}
|
||
return {{"ok", true}, {"club", data.at("teamId")}, {"rows", rows}, {"salary_total", total}, {"bonuses", Json::array()}, {"quote", quote}};
|
||
}
|
||
Json engine_contract_request(const Json &bundle, const std::string &id, const std::string &request_id) {
|
||
const auto view = engine_contracts_projection(bundle); bool allowed = false;
|
||
require(view.at("quote").is_null(), "Bitte zuerst die laufende Verhandlung schließen.");
|
||
for (const auto &r : view.at("rows")) if (r.at("id") == id) allowed = r.at("can_request");
|
||
require(allowed, "Dieser Spieler kann derzeit nicht verhandeln.");
|
||
return sports_command(bundle, "quote.request", {{"kind", "contract"}, {"playerId", id}}, request_id);
|
||
}
|
||
Json engine_contract_offer(const Json &bundle, const std::string &player, const std::string &id, int years, int64_t euros, const std::string &request_id) {
|
||
const auto q = engine_contracts_projection(bundle).at("quote");
|
||
require(q.is_object() && q.at("id") == id && q.at("player") == player, "Die Verhandlung ist nicht mehr aktuell.");
|
||
require(years >= 1 && years <= 4 && !q.at("demands")[size_t(years - 1)].is_null() && euros >= 0 && euros <= q.at("max_salary").get<int64_t>() / 100, "Ungültige Laufzeit oder Gehalt.");
|
||
return sports_command(bundle, "contract.offer", {{"quoteId", id}, {"years", years}, {"monthlySalary", {{"currency", "EUR"}, {"minorUnits", 2}, {"minor", std::to_string(euros * 100)}}}}, request_id);
|
||
}
|
||
Json engine_contract_cancel(const Json &bundle, const std::string &id, const std::string &request_id) {
|
||
const auto q = engine_contracts_projection(bundle).at("quote");
|
||
require(q.is_object() && q.at("id") == id, "Diese Verhandlung ist nicht mehr geöffnet.");
|
||
return sports_command(bundle, "contract.cancel", {{"quoteId", id}}, request_id);
|
||
}
|
||
|
||
namespace {
|
||
std::chrono::sys_days calendar_iso_day(const std::string &s) {
|
||
require(s.size() == 10 && s[4] == '-' && s[7] == '-', "Ungültiges Kalenderdatum.");
|
||
for (size_t i = 0; i < s.size(); ++i) if (i != 4 && i != 7) require(s[i] >= '0' && s[i] <= '9', "Ungültige Datumsziffer.");
|
||
const auto d = std::chrono::year_month_day{std::chrono::year(std::stoi(s.substr(0,4))), std::chrono::month(unsigned(std::stoi(s.substr(5,2)))), std::chrono::day(unsigned(std::stoi(s.substr(8,2))))};
|
||
require(d.ok(), "Ungültiger Kalendertag."); return std::chrono::sys_days{d};
|
||
}
|
||
int calendar_index(const Json &view, const Json &date) {
|
||
require(date.is_string(), "Kalenderdatum fehlt.");
|
||
const auto index = (calendar_iso_day(date.get<std::string>()) - calendar_iso_day(view.at("start"))).count();
|
||
require(index >= 0 && index < view.at("count").get<int>(), "Datum liegt außerhalb der angezeigten Saison."); return int(index);
|
||
}
|
||
bool schedule_permission(const Json &bundle) {
|
||
const auto commands = bundle.at("desktop").at("meta").at("scope").value("allowedCommands", Json::array());
|
||
return commands.is_array() && std::find(commands.begin(),commands.end(),Json("fixture.reschedule")) != commands.end();
|
||
}
|
||
}
|
||
Json engine_calendar_projection(const Json &bundle) {
|
||
validate_engine_desk(bundle);
|
||
const auto &meta = bundle.at("desktop").at("meta"), &data = lineup_read(bundle, "calendar");
|
||
require(meta.at("scope").at("role") == "club", "Der Vereinskalender ist am National-Schreibtisch nicht verfügbar.");
|
||
const auto start = meta.at("season").at("startDate").get<std::string>(), end = meta.at("season").at("endDate").get<std::string>();
|
||
const auto days = calendar_days(start); // Gregorian geometry only; no demo fixtures or date rules.
|
||
require(!days.empty() && days.back().iso == end && data.at("from") == start && data.at("until") == end, "Unvollständiger Saisonkalender.");
|
||
Json view = {{"start",start},{"end",end},{"count",days.size()},{"events",Json::object()},{"fixtures",Json::array()},{"league",nullptr}};
|
||
const auto today = (calendar_iso_day(meta.at("date")) - calendar_iso_day(start)).count(); view["today"] = today >= 0 && today < int(days.size()) ? Json(today) : Json();
|
||
require(data.at("fixtures").is_array() && data.at("days").is_array(), "Kalenderdaten fehlen.");
|
||
const auto own = meta.at("scope").at("teamId"); std::map<std::string,Json> fixtures; std::set<std::string> leagues;
|
||
for (const auto &f : data.at("fixtures")) {
|
||
const auto id = f.at("id").get<std::string>(); require(!id.empty() && !fixtures.contains(id), "Doppelte Kalenderpartie.");
|
||
require(f.at("home").at("id") == own || f.at("away").at("id") == own, "Kalenderpartie gehört einem anderen Verein.");
|
||
auto row = f; row["day"] = calendar_index(view,f.at("scheduledDate")); (void)calendar_index(view,f.at("originalDate"));
|
||
(void)whole_in_range(f.at("round"),1,10000);
|
||
const auto status=f.at("status").get<std::string>();require(status=="scheduled"||status=="played"||status=="rescheduled"||status=="postponed"||status=="void","Unbekannter Spielstatus.");
|
||
if(!f.at("result").is_null()) {require(f.at("result").is_array()&&f.at("result").size()==2,"Ungültiges Ergebnis.");for(const auto &v:f.at("result"))(void)whole_in_range(v,0,10000);}
|
||
if(f.at("competition").value("kind","")=="league")leagues.insert(f.at("competition").at("id").get<std::string>());
|
||
fixtures.emplace(id,row); view["fixtures"].push_back(row);
|
||
}
|
||
if(leagues.size()==1)view["league"]=*leagues.begin();
|
||
std::set<int> seen;
|
||
for(const auto &raw:data.at("days")) {
|
||
const int index=calendar_index(view,raw.at("date"));require(seen.insert(index).second,"Doppelter Kalendertag.");
|
||
(void)whole_in_range(raw.at("seasonDay"),0,366);
|
||
require(raw.at("eventKinds").is_array()&&raw.at("fixtureIds").is_array(),"Kalenderereignisse fehlen.");
|
||
std::set<std::string> ids;
|
||
for(const auto &id:raw.at("fixtureIds")) {require(id.is_string()&&fixtures.contains(id.get<std::string>())&&ids.insert(id.get<std::string>()).second,"Unbekannte oder doppelte Kalenderreferenz.");require(fixtures.at(id.get<std::string>()).at("day")==index,"Partie steht am falschen Datum.");}
|
||
for(const auto &kind:raw.at("eventKinds"))require(kind.is_string(),"Ungültiger Kalendertermin.");
|
||
view["events"][std::to_string(index)]={{"kinds",raw.at("eventKinds")},{"ids",raw.at("fixtureIds")}};
|
||
}
|
||
for(const auto &[id,f]:fixtures) {
|
||
const auto key=std::to_string(f.at("day").get<int>());
|
||
require(view.at("events").contains(key),"Partie ohne Kalendertag.");
|
||
const auto &ids=view.at("events").at(key).at("ids");require(std::find(ids.begin(),ids.end(),Json(id))!=ids.end(),"Partie fehlt in den Tagesreferenzen.");
|
||
}
|
||
return view;
|
||
}
|
||
Json engine_scheduling_projection(const Json &bundle) {
|
||
const auto calendar=engine_calendar_projection(bundle);const auto &data=lineup_read(bundle,"scheduling"),&own=bundle.at("desktop").at("meta").at("scope").at("teamId");
|
||
require(data.at("movable").is_array()&&data.at("moved").is_array(),"Verlegungsdaten fehlen.");
|
||
Json result={{"movable",Json::array()},{"moved",Json::array()},{"allowed",schedule_permission(bundle)}};std::set<std::string> ids;
|
||
for(const auto *key:{"movable","moved"})for(const auto &raw:data.at(key)) {
|
||
auto row=raw;row["day"]=calendar_index(calendar,raw.at("date"));
|
||
require(raw.at("home").at("id")==own||raw.at("away").at("id")==own,"Verlegung gehört einem anderen Verein.");
|
||
(void)whole_in_range(raw.at("round"),1,10000);
|
||
bool linked=false;for(const auto &f:calendar.at("fixtures"))linked|=f.at("day")==row.at("day")&&f.at("round")==row.at("round")&&f.at("home").at("id")==row.at("home").at("id")&&f.at("away").at("id")==row.at("away").at("id");
|
||
require(linked,"Verlegung ohne passende Kalenderpartie.");
|
||
if(std::string(key)=="movable") {
|
||
require(raw.at("id").is_string()&&!raw.at("id").get<std::string>().empty()&&ids.insert(raw.at("id").get<std::string>()).second,"Doppelte Verlegungs-ID.");
|
||
require(raw.at("targetDates").is_array(),"Zieltermine fehlen.");row["targets"]=Json::array();std::set<int> targets;
|
||
for(const auto &date:raw.at("targetDates")) {const int d=calendar_index(calendar,date);require(targets.insert(d).second&&d!=row.at("day"),"Doppelter oder unveränderter Zieltermin.");row["targets"].push_back(d);}
|
||
}
|
||
result[key].push_back(row);
|
||
}
|
||
return result;
|
||
}
|
||
Json engine_reschedule_command(const Json &bundle,const std::string &match,const std::string &date,const std::string &request_id) {
|
||
const auto view=engine_scheduling_projection(bundle);bool found=false;
|
||
for(const auto &row:view.at("movable"))if(row.at("id")==match)for(const auto &target:row.at("targetDates"))found|=target==date;
|
||
require(found,"Partie oder Zieltermin ist nicht mehr verfügbar.");
|
||
return sports_command(bundle,"fixture.reschedule",{{"matchId",match},{"date",date}},request_id);
|
||
}
|
||
Json engine_reschedule_undo(const Json &bundle,const std::string &date,const std::string &request_id) {
|
||
const auto view=engine_scheduling_projection(bundle);bool found=false;
|
||
for(const auto &row:view.at("moved"))found|=row.at("date")==date;
|
||
require(found,"An diesem Termin ist keine Rücknahme verfügbar.");
|
||
return sports_command(bundle,"fixture.reschedule",{{"action","undo"},{"date",date}},request_id);
|
||
}
|
||
} // namespace bmh::modern_ui
|