Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Panels/TradeBox.cs
T
Alby96andClaude Opus 5.5 596ce2c376
CI / Build e test (pull_request) Successful in 1m19s
CI / Immagine Docker (pull_request) Successful in 29s
F6: compravendita in proprio, correzioni della revisione
La revisione ha trovato casi in cui la merce della compagnia, già pagata,
poteva perdersi o restare bloccata, e il magazzino di destinazione
restare prenotato per sempre. Le correzioni:

- Il percorso della merce propria rispetta i flag carico e scarico delle
  fermate: LineGraph.From ha l'opzione stopFlags. ShipGoods rifiuta con
  Blocked la spedizione che esiste solo ignorando i flag. I pacchetti dei
  clienti non cambiano: l'accettazione F4 dà ancora 35/20 e 75/2.
- La scadenza in stazione della merce propria riparte a ogni trasbordo.
- La merce propria in attesa ricalcola ogni giorno il tratto sulle linee
  di quel giorno; se non c'è più un percorso torna nel magazzino.
- La merce propria a bordo scende alla prima fermata quando il suo tratto
  non è più sulla linea del treno. Un treno che lascia la linea
  (riassegnato, al deposito, in riserva, fine copertura) la lascia alla
  stazione dove si trova o alla prossima fermata.
- Una stazione con merce propria in partenza o in arrivo non si demolisce.
- La merce propria, in magazzino e in viaggio, entra nel valore contabile
  al prezzo globale: un acquisto non abbassa più il patrimonio netto
  dell'intero importo.
- Solo l'acquisto richiede lo sblocco del livello: la merce ereditata con
  una fusione si vende e si spedisce, e il riquadro del pannello compare.
- Nel riquadro, la stazione di arrivo predefinita è diversa da quella di
  partenza.

ADR 0016 e STATE aggiornati; sei test nuovi in TradingTests.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:05:29 +01:00

237 lines
11 KiB
C#

using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Riquadro «Compravendita in proprio» del Mercato globale, quando il livello lo sblocca (ADR 0016):
/// scelta della stazione propria, quantità, Compra, Vendi e Spedisci a un'altra stazione per la
/// merce scelta nel pannello; giacenze del magazzino. Prezzi, disponibilità e giacenze arrivano dal
/// server nel MarketReport: i comandi li ricalcola il server. I controlli restano gli stessi tra un
/// quadro e l'altro, così le scelte non si perdono a ogni nuovo giorno.
/// </summary>
public sealed partial class TradeBox : VBoxContainer
{
/// <summary>Margine sul prezzo mostrato: si compra fino al 10 % sopra e si vende fino al 10 % sotto.</summary>
private const double PriceTolerance = 0.10;
private readonly GameSession _session;
private readonly OptionButton _station = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
private readonly OptionButton _destination = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
private readonly SpinBox _quantity = new() { MinValue = 1, MaxValue = 100_000, Step = 1, Rounded = true, Value = 50, SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Label _good = UiTheme.Text("", 14, bold: true);
private readonly Label _quote = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _capacity = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly VBoxContainer _stock = PanelKit.Column(2);
private readonly Label _status = UiTheme.Text("", 12);
private readonly Button _buy = UiTheme.Primary(T("Compra"));
private readonly Button _sell = new() { Text = T("Vendi") };
private readonly Button _ship = new() { Text = T("Spedisci a") };
private readonly List<int> _stationIds = [];
private readonly List<int> _destinationIds = [];
private MarketReport? _report;
private int _goodId = -1;
private bool _buyAllowed = true;
/// <summary>Esito di un comando: il pannello chiede subito un quadro aggiornato.</summary>
public event Action? Traded;
public TradeBox(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
foreach (var l in new[] { _quote, _capacity, _status }) l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
var station = PanelKit.Row(6);
station.AddChild(UiTheme.Text(T("Stazione"), 13, Palette.TextSecondary));
station.AddChild(_station);
AddChild(station);
_station.ItemSelected += _ =>
{
PickDestination(SelectedDestination);
Render();
};
AddChild(_good);
AddChild(_quote);
var qty = PanelKit.Row(6);
qty.AddChild(UiTheme.Text(T("Quantità"), 13, Palette.TextSecondary));
qty.AddChild(_quantity);
AddChild(qty);
var trade = PanelKit.Row(6);
_buy.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_sell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_buy.TooltipText = T("Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.");
_sell.TooltipText = T("Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.");
_buy.Pressed += Buy;
_sell.Pressed += Sell;
trade.AddChild(_buy);
trade.AddChild(_sell);
AddChild(trade);
var ship = PanelKit.Row(6);
_ship.TooltipText = T("Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.");
_ship.Pressed += Ship;
ship.AddChild(_ship);
ship.AddChild(_destination);
AddChild(ship);
AddChild(_capacity);
AddChild(UiTheme.Text(T("In magazzino"), 13, Palette.TextSecondary, bold: true));
AddChild(_stock);
AddChild(_status);
}
/// <summary>
/// Aggiorna stazioni, quotazioni e giacenze dal quadro ricevuto, per la merce scelta. Senza lo
/// sblocco del livello (<paramref name="buyAllowed"/> falso) si vende e si spedisce solo la merce
/// già in magazzino, per esempio quella ereditata da una fusione.
/// </summary>
public void Update(MarketReport report, int good, bool buyAllowed = true)
{
_report = report;
_goodId = good;
_buyAllowed = buyAllowed;
var w = _session.World;
int keep = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
int keepTo = SelectedDestination;
_stationIds.Clear();
_station.Clear();
foreach (var h in report.Warehouses)
{
_stationIds.Add(h.Station);
_station.AddItem(StationName(w, h.Station));
}
int index = _stationIds.IndexOf(keep);
if (_stationIds.Count > 0) _station.Select(index >= 0 ? index : 0);
_destinationIds.Clear();
_destination.Clear();
foreach (var h in report.Warehouses)
{
_destinationIds.Add(h.Station);
_destination.AddItem(StationName(w, h.Station));
}
PickDestination(keepTo);
Render();
}
private int SelectedDestination =>
_destination.Selected >= 0 && _destination.Selected < _destinationIds.Count ? _destinationIds[_destination.Selected] : -1;
/// <summary>
/// Mantiene la stazione di arrivo scelta se è ancora nell'elenco e diversa da quella di partenza,
/// altrimenti sceglie la prima diversa dalla partenza.
/// </summary>
private void PickDestination(int keep)
{
if (_destinationIds.Count == 0) return;
int from = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
int to = _destinationIds.IndexOf(keep);
if (to < 0 || _destinationIds[to] == from) to = _destinationIds.FindIndex(id => id != from);
_destination.Select(to >= 0 ? to : 0);
}
private WarehouseInfo? Current =>
_report is null || _station.Selected < 0 || _station.Selected >= _stationIds.Count
? null
: _report.Warehouses.FirstOrDefault(h => h.Station == _stationIds[_station.Selected]);
private WarehouseGoodInfo? CurrentGood => Current?.Goods.FirstOrDefault(g => g.Good == _goodId);
private void Render()
{
var w = _session.World;
foreach (var c in _stock.GetChildren()) c.QueueFree();
var house = Current;
bool any = house is not null && _goodId >= 0 && _goodId < w.Data.Goods.Count;
_buy.Disabled = _sell.Disabled = _ship.Disabled = !any;
if (!any)
{
_good.Text = "";
_quote.Text = T("Costruisci una stazione per avere un magazzino dove comprare e vendere.");
_capacity.Text = "";
return;
}
string unit = w.Data.Goods[_goodId].Unit;
var g = CurrentGood;
_good.Text = $"{T("Merce")}: {GoodName(w, _goodId)} · {T("in magazzino")} {g?.Units ?? 0} {unit}";
string buy = g is { BuyPrice: >= 0 }
? $"{T("Si compra a")} {Price(g.BuyPrice)}/{unit} ({Fmt.Number(g.BuyUnits, 0)} {unit} {T("disponibili")})"
: T("Nessun produttore né hub nel bacino la vende");
string sell = g is { SellPrice: >= 0 }
? $"{T("si vende a")} {Price(g.SellPrice)}/{unit} ({Fmt.Number(g.SellUnits, 0)} {unit} {T("richieste")})"
: T("nessun consumatore né hub nel bacino la compra");
_quote.Text = $"{buy}; {sell}. {T("Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.")}";
_buy.Disabled = !_buyAllowed || g is not { BuyPrice: >= 0 };
_sell.Disabled = g is not { SellPrice: >= 0 } || g.Units <= 0;
_ship.Disabled = (g?.Units ?? 0) <= 0 || _destinationIds.Count < 2;
int used = house!.Goods.Sum(x => x.Units) + house.Incoming;
_capacity.Text = $"{T("Magazzino")}: {Fmt.Number(used, 0)} / {Fmt.Number(house.Capacity, 0)} {T("unità")}"
+ (house.Incoming > 0 ? $" ({T("di cui")} {Fmt.Number(house.Incoming, 0)} {T("in arrivo")})" : "");
var held = house.Goods.Where(x => x.Units > 0).ToList();
if (held.Count == 0) _stock.AddChild(UiTheme.Text(T("Vuoto"), 12, Palette.TextSecondary));
foreach (var x in held)
_stock.AddChild(PanelKit.Pair(GoodName(w, x.Good), PanelKit.Value($"{Fmt.Number(x.Units, 0)} {w.Data.Goods[x.Good].Unit}")));
}
private void Buy()
{
if (Current is not { } house || CurrentGood is not { BuyPrice: >= 0 } g) return;
var max = Money.FromCentsRounded(g.BuyPrice * (1 + PriceTolerance));
_session.Command(new BuyGoodsCommand(new StationId(house.Station), GoodId(), Units(), max), Result);
}
private void Sell()
{
if (Current is not { } house || CurrentGood is not { SellPrice: >= 0 } g) return;
var min = Money.FromCentsRounded(g.SellPrice * (1 - PriceTolerance));
_session.Command(new SellGoodsCommand(new StationId(house.Station), GoodId(), Units(), min), Result);
}
private void Ship()
{
if (Current is not { } house || _destination.Selected < 0 || _destination.Selected >= _destinationIds.Count) return;
int to = _destinationIds[_destination.Selected];
if (to == house.Station)
{
ShowStatus(T("Scegli una stazione di arrivo diversa da quella di partenza"), false);
return;
}
_session.Command(new ShipGoodsCommand(new StationId(house.Station), new StationId(to), GoodId(), Units()), Result);
}
private string GoodId() => _session.World.Data.Goods[_goodId].Id;
private int Units() => (int)Math.Max(1, Math.Round(_quantity.Value));
private void Result(CommandResultMessage r)
{
ShowStatus(r.Message, r.Ok);
Traded?.Invoke();
}
private void ShowStatus(string text, bool ok)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", ok ? Palette.Ok : Palette.Danger);
}
private static string StationName(ClientWorld w, int station) =>
w.Stations.TryGetValue(station, out var s) ? s.Name : $"{T("Stazione")} {station}";
private static string GoodName(ClientWorld w, int good)
{
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
}