Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*, variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos: CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly. Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
947 lines
50 KiB
C#
947 lines
50 KiB
C#
using Godot;
|
||
using RailEnterprise.Client.App;
|
||
using RailEnterprise.Client.Net;
|
||
using RailEnterprise.Core.Commands;
|
||
using RailEnterprise.Core.Common;
|
||
using RailEnterprise.Core.Economy;
|
||
using RailEnterprise.Protocol.Client;
|
||
using RailEnterprise.Protocol.Messages;
|
||
using static RailEnterprise.Client.App.Localization;
|
||
|
||
namespace RailEnterprise.Client.Panels;
|
||
|
||
/// <summary>
|
||
/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
|
||
/// 05): listino delle compagnie, offerte pubbliche in corso con adesioni e difese, scheda della
|
||
/// compagnia scelta (libro dei soci, prezzo mensile, storico annuale) e operazioni: compravendita,
|
||
/// quotazione, dividendo, riacquisto, offerta pubblica, fusione, offerte alle aste delle fallite.
|
||
/// I dati arrivano dal listino giornaliero (MarketTape) e dalle schede chieste al server; ogni
|
||
/// operazione è un comando e l'esito (anche il rifiuto per livello) si mostra com'è.
|
||
/// </summary>
|
||
public partial class CompaniesPanel : VBoxContainer
|
||
{
|
||
private const float WPrice = 80, WCap = 86, WWorth = 86, WMine = 56;
|
||
|
||
private readonly GameSession _session;
|
||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||
private readonly VBoxContainer _banner = PanelKit.Column(6);
|
||
private readonly VBoxContainer _rows = PanelKit.Column(4);
|
||
private readonly VBoxContainer _bids = PanelKit.Column(8);
|
||
private readonly VBoxContainer _card = PanelKit.Column(8);
|
||
private readonly SeriesChart _chart = new(150);
|
||
private readonly Label _chartCaption = UiTheme.Text("", 14, bold: true);
|
||
private readonly VBoxContainer _register = PanelKit.Column(6);
|
||
private readonly VBoxContainer _history = PanelKit.Column(4);
|
||
private readonly VBoxContainer _actions = PanelKit.Column(8);
|
||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||
private readonly Dictionary<int, CompanyRow> _rowById = [];
|
||
private readonly Dictionary<int, (Label Text, ProgressBar Bar)> _bidProgress = [];
|
||
private string _bidsKey = "", _actionsKey = "", _bannerKey = "", _rowsKey = "";
|
||
private int _selected = -1;
|
||
private int _tapeVersion = -1, _entityVersion = -1, _detailVersion = -1;
|
||
private double _requestSelected, _requestAll = double.MaxValue, _sinceRefresh = double.MaxValue;
|
||
private Action? _updateEstimates;
|
||
|
||
public event Action? CloseRequested;
|
||
public event Action? ChronicleRequested;
|
||
|
||
public CompaniesPanel(GameSession session)
|
||
{
|
||
_session = session;
|
||
AddThemeConstantOverride("separation", 14);
|
||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||
|
||
var header = PanelKit.Row(12);
|
||
var titles = PanelKit.Column(0);
|
||
titles.AddChild(UiTheme.TitleLabel(T("Compagnie e borsa"), 40));
|
||
titles.AddChild(_subtitle);
|
||
header.AddChild(titles);
|
||
var chronicle = new Button { Text = T("Cronaca provvisoria"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(0, 40) };
|
||
chronicle.TooltipText = T("La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio.");
|
||
chronicle.Pressed += () => ChronicleRequested?.Invoke();
|
||
header.AddChild(chronicle);
|
||
var close = new Button { Text = T("Chiudi"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(96, 40) };
|
||
close.Pressed += () => CloseRequested?.Invoke();
|
||
header.AddChild(close);
|
||
AddChild(header);
|
||
AddChild(_banner);
|
||
|
||
var body = PanelKit.Row(16);
|
||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||
AddChild(body);
|
||
|
||
var left = Column(body, 1.5f);
|
||
left.AddChild(UiTheme.Text(T("Listino"), 16, bold: true));
|
||
var sm = session.World.Data.Balance.StockMarket;
|
||
left.AddChild(Wrapped($"{T("Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e")} " +
|
||
$"{Fmt.Number(sm.EarningsMultiple, 0)} {T("volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.")}", 12, Palette.TextSecondary));
|
||
left.AddChild(TableHeader());
|
||
left.AddChild(_rows);
|
||
left.AddChild(PanelKit.Separator());
|
||
left.AddChild(UiTheme.Text(T("Offerte pubbliche in corso"), 16, bold: true));
|
||
left.AddChild(_bids);
|
||
|
||
var center = Column(body, 1f);
|
||
center.AddChild(_card);
|
||
center.AddChild(_chartCaption);
|
||
center.AddChild(_chart);
|
||
center.AddChild(UiTheme.Text(T("Libro dei soci"), 16, bold: true));
|
||
center.AddChild(_register);
|
||
|
||
var right = Column(body, 0.9f);
|
||
right.AddChild(UiTheme.Text(T("Storico annuale"), 16, bold: true));
|
||
right.AddChild(_history);
|
||
right.AddChild(PanelKit.Separator());
|
||
right.AddChild(UiTheme.Text(T("Operazioni"), 16, bold: true));
|
||
right.AddChild(_actions);
|
||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
right.AddChild(_status);
|
||
|
||
Select(session.World.Summary?.CompanyId ?? 0);
|
||
}
|
||
|
||
/// <summary>Compagnia della scheda (−1 se nessuna).</summary>
|
||
public int Selected => _selected;
|
||
|
||
public void Select(int company)
|
||
{
|
||
_selected = company;
|
||
_requestSelected = double.MaxValue;
|
||
_sinceRefresh = double.MaxValue;
|
||
_status.Text = "";
|
||
foreach (var (id, row) in _rowById) row.SetSelected(id == company);
|
||
}
|
||
|
||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||
{
|
||
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 16));
|
||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||
frame.AddChild(scroll);
|
||
// margine destro: la barra di scorrimento non tocca i numeri allineati a destra
|
||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
margin.AddThemeConstantOverride("margin_right", 10);
|
||
scroll.AddChild(margin);
|
||
var col = PanelKit.Column(10);
|
||
margin.AddChild(col);
|
||
body.AddChild(frame);
|
||
return col;
|
||
}
|
||
|
||
public override void _Process(double delta)
|
||
{
|
||
var w = _session.World;
|
||
_requestSelected += delta;
|
||
_requestAll += delta;
|
||
_sinceRefresh += delta;
|
||
// tutte le schede ogni 5 s (quote del giocatore e soci dei bersagli), quella aperta ogni secondo
|
||
if (_requestAll >= 5)
|
||
{
|
||
_requestAll = 0;
|
||
_requestSelected = 0;
|
||
foreach (int id in w.Companies.Values.Where(c => !c.Merged).Select(c => c.Id).Order())
|
||
_session.Send(new RequestDetail { Kind = DetailKind.Company, Target = id });
|
||
}
|
||
else if (_requestSelected >= 1 && _selected >= 0)
|
||
{
|
||
_requestSelected = 0;
|
||
_session.Send(new RequestDetail { Kind = DetailKind.Company, Target = _selected });
|
||
}
|
||
bool changed = w.TapeVersion != _tapeVersion || w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion;
|
||
if (changed && _sinceRefresh >= 0.25) Refresh();
|
||
}
|
||
|
||
private void Result(CommandResultMessage r)
|
||
{
|
||
_status.Text = r.Message;
|
||
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.Ok : Palette.Danger);
|
||
_requestAll = double.MaxValue;
|
||
}
|
||
|
||
private void Refresh()
|
||
{
|
||
var w = _session.World;
|
||
_sinceRefresh = 0;
|
||
_tapeVersion = w.TapeVersion;
|
||
_entityVersion = w.EntityVersion;
|
||
_detailVersion = w.DetailVersion;
|
||
int me = Me(w);
|
||
double portfolio = w.Companies.Values.Where(c => c.Id != me && !c.Merged && !c.Bankrupt).Sum(c => Mine(w, c.Id) * PriceCents(w, c.Id));
|
||
_subtitle.Text = (w.Tape is { } tape ? $"{T("Listino del")} {Fmt.Date(w, tape.Day)}" : T("In attesa del listino del giorno…")) +
|
||
$" · {T("portafoglio azioni")} {Money.FromCentsRounded(portfolio)}";
|
||
RefreshBanner(w);
|
||
RefreshRows(w);
|
||
RefreshBids(w);
|
||
RefreshCard(w);
|
||
RefreshHistory(w);
|
||
RefreshActions(w);
|
||
_updateEstimates?.Invoke();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ dati di comodo (solo lettura)
|
||
|
||
private static int Me(ClientWorld w) => w.Summary?.CompanyId ?? 0;
|
||
|
||
private static SharePrice? Quote(ClientWorld w, int id) => w.Tape?.Shares.FirstOrDefault(s => s.Company == id);
|
||
|
||
/// <summary>Prezzo per azione in centesimi: dal listino se c'è, altrimenti dalla scheda dell'entità.</summary>
|
||
private static double PriceCents(ClientWorld w, int id) =>
|
||
Quote(w, id) is { PriceCents: > 0 } q ? q.PriceCents : w.Companies.TryGetValue(id, out var c) ? c.SharePriceCents : 0;
|
||
|
||
private static long Outstanding(ClientWorld w, int id)
|
||
{
|
||
if (Quote(w, id) is { Outstanding: > 0 } q) return q.Outstanding;
|
||
if (w.CompanyCards.TryGetValue(id, out var card)) return card.TotalShares - card.Treasury;
|
||
return w.Data.Balance.StockMarket.Shares;
|
||
}
|
||
|
||
/// <summary>Azioni della compagnia del giocatore nella compagnia indicata (dal libro dei soci).</summary>
|
||
private static long Mine(ClientWorld w, int id)
|
||
{
|
||
int me = Me(w);
|
||
if (!w.CompanyCards.TryGetValue(id, out var card)) return 0;
|
||
return card.Holdings.Where(h => id == me ? h.Holder == HoldingInfo.Founder : h.Holder == me).Sum(h => h.Shares);
|
||
}
|
||
|
||
/// <summary>Vero/falso se il libro dei soci è noto, null se la scheda non è ancora arrivata.</summary>
|
||
private static bool? Holds(ClientWorld w, int id) => w.CompanyCards.ContainsKey(id) ? Mine(w, id) > 0 : null;
|
||
|
||
// ------------------------------------------------------------------ amministrazione controllata
|
||
|
||
private void RefreshBanner(ClientWorld w)
|
||
{
|
||
int me = Me(w);
|
||
var info = w.Companies.GetValueOrDefault(me);
|
||
long today = Fmt.Today(w);
|
||
string key = info is { Receivership: true } ? $"{info.ReceivershipUntilDay}|{info.ControlledBy}|{today}|{info.FounderShare:0.000}" : "";
|
||
if (key == _bannerKey) return;
|
||
_bannerKey = key;
|
||
foreach (var c in _banner.GetChildren()) c.QueueFree();
|
||
if (info is not { Receivership: true }) return;
|
||
var sm = w.Data.Balance.StockMarket;
|
||
var box = new PanelContainer();
|
||
box.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 14));
|
||
var row = PanelKit.Row(16);
|
||
box.AddChild(row);
|
||
var col = PanelKit.Column(4);
|
||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
col.AddChild(UiTheme.Text($"{T("Amministrazione controllata")} · {T("controlla la compagnia")} {Fmt.Company(w, info.ControlledBy)}", 16, Palette.AmberLight, bold: true));
|
||
long left = Math.Max(0, info.ReceivershipUntilDay - today);
|
||
col.AddChild(Wrapped($"{T("Riacquista almeno il")} {Fmt.Pct(sm.RansomShare, 0)} {T("delle azioni entro il")} {Fmt.Date(w, info.ReceivershipUntilDay)} ({left} {T("giorni")}), " +
|
||
$"{T("altrimenti la partita finisce. Intanto versi il")} {Fmt.Pct(sm.ReceivershipDividend, 0)} {T("degli utili come dividendo e non puoi chiedere prestiti.")} " +
|
||
$"{T("Oggi il fondatore ha il")} {Fmt.Pct(info.FounderShare)}.", 13, Palette.Text));
|
||
row.AddChild(col);
|
||
var buy = UiTheme.Primary(T("Riacquista azioni"));
|
||
buy.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||
buy.Pressed += () => Select(me);
|
||
row.AddChild(buy);
|
||
_banner.AddChild(box);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ listino
|
||
|
||
private static Control TableHeader()
|
||
{
|
||
var row = PanelKit.Row(6);
|
||
var name = UiTheme.Text(T("Compagnia"), 12, Palette.TextSecondary);
|
||
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
name.CustomMinimumSize = new Vector2(24, 0);
|
||
row.AddChild(new Control { CustomMinimumSize = new Vector2(10, 0) });
|
||
row.AddChild(name);
|
||
foreach (var (text, width) in new[] { (T("Prezzo · var."), WPrice), (T("Capitalizz."), WCap), (T("Patrimonio"), WWorth), (T("Tua quota"), WMine) })
|
||
{
|
||
var l = UiTheme.Text(text, 12, Palette.TextSecondary);
|
||
l.CustomMinimumSize = new Vector2(width, 0);
|
||
l.HorizontalAlignment = HorizontalAlignment.Right;
|
||
row.AddChild(l);
|
||
}
|
||
row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
|
||
return row;
|
||
}
|
||
|
||
private void RefreshRows(ClientWorld w)
|
||
{
|
||
int me = Me(w);
|
||
var companies = w.Companies.Values.Where(c => !c.Merged)
|
||
.OrderBy(c => c.Id == me ? 0 : c.Bankrupt ? 2 : 1)
|
||
.ThenByDescending(c => PriceCents(w, c.Id) * Outstanding(w, c.Id))
|
||
.ThenBy(c => c.Id).ToList();
|
||
string key = string.Join(",", companies.Select(c => c.Id));
|
||
if (key != _rowsKey)
|
||
{
|
||
_rowsKey = key;
|
||
foreach (var c in _rows.GetChildren()) c.QueueFree();
|
||
_rowById.Clear();
|
||
foreach (var c in companies)
|
||
{
|
||
int id = c.Id;
|
||
var row = new CompanyRow();
|
||
row.Pressed += () => Select(id);
|
||
_rowById[id] = row;
|
||
_rows.AddChild(row);
|
||
row.SetSelected(id == _selected);
|
||
}
|
||
}
|
||
foreach (var c in companies)
|
||
{
|
||
var q = Quote(w, c.Id);
|
||
double price = PriceCents(w, c.Id);
|
||
long outstanding = Outstanding(w, c.Id);
|
||
var parts = new List<string>();
|
||
if (c.Id == me) parts.Add(T("la tua compagnia"));
|
||
if (c.Bankrupt)
|
||
{
|
||
parts.Add(T("fallita, attivi all'asta"));
|
||
}
|
||
else
|
||
{
|
||
parts.Add(Fmt.Tier(w, c.Tier));
|
||
if (c.Personality.Length > 0) parts.Add(Fmt.Personality(w, c.Personality));
|
||
if (!c.Listed) parts.Add(T("non quotata"));
|
||
if (c.ControlledBy >= 0) parts.Add($"{T("controllata da")} {Fmt.Company(w, c.ControlledBy)}");
|
||
if (c.Receivership) parts.Add(T("amministrazione controllata"));
|
||
}
|
||
double mine = c.Id == me ? c.FounderShare : outstanding > 0 && w.CompanyCards.ContainsKey(c.Id) ? (double)Mine(w, c.Id) / outstanding : -1;
|
||
_rowById[c.Id].Update(
|
||
Fmt.CompanyColor(w, c.Id), c.Name, string.Join(" · ", parts),
|
||
c.Bankrupt ? "—" : Fmt.Price(price), c.Listed && q is not null && !c.Bankrupt ? Fmt.Change(q.Change) : "—",
|
||
!c.Listed || q is null ? Palette.TextSecondary : q.Change > 0.0005f ? Palette.Ok : q.Change < -0.0005f ? Palette.Danger : Palette.TextSecondary,
|
||
c.Bankrupt ? "—" : Money.FromCentsRounded(price * outstanding).ToString("short"), c.NetWorth.ToString("short"),
|
||
mine < 0 ? "…" : mine <= 0 ? "—" : Fmt.Pct(mine), c.Listed && !c.Bankrupt, c.Bankrupt || c.Receivership);
|
||
}
|
||
}
|
||
|
||
/// <summary>Riga del listino: pulsante piatto con le colonne allineate.</summary>
|
||
private sealed partial class CompanyRow : Button
|
||
{
|
||
private readonly ColorRect _swatch = new() { CustomMinimumSize = new Vector2(10, 28), SizeFlagsVertical = SizeFlags.ShrinkCenter };
|
||
private readonly Label _name = UiTheme.Text("", 14, bold: true);
|
||
private readonly Label _sub = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
private readonly Label _price = UiTheme.Text("", 14, bold: true);
|
||
private readonly Label _change = UiTheme.Text("", 12);
|
||
private readonly Label _cap = UiTheme.Text("", 13);
|
||
private readonly Label _worth = UiTheme.Text("", 13);
|
||
private readonly Label _mine = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
|
||
|
||
public CompanyRow()
|
||
{
|
||
CustomMinimumSize = new Vector2(0, 50);
|
||
FocusMode = FocusModeEnum.None;
|
||
AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
|
||
AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
|
||
SetSelected(false);
|
||
var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||
row.AddThemeConstantOverride("separation", 6);
|
||
row.SetAnchorsPreset(LayoutPreset.FullRect);
|
||
row.OffsetLeft = 8;
|
||
row.OffsetRight = -8;
|
||
AddChild(row);
|
||
row.AddChild(_swatch);
|
||
var names = new VBoxContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
|
||
names.AddThemeConstantOverride("separation", -2);
|
||
foreach (var l in new[] { _name, _sub })
|
||
{
|
||
l.ClipText = true;
|
||
l.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||
l.CustomMinimumSize = new Vector2(24, 0);
|
||
names.AddChild(l);
|
||
}
|
||
row.AddChild(names);
|
||
// prezzo con la variazione del giorno sotto
|
||
var price = new VBoxContainer { CustomMinimumSize = new Vector2(WPrice, 0), SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
|
||
price.AddThemeConstantOverride("separation", -2);
|
||
foreach (var l in new[] { _price, _change })
|
||
{
|
||
l.HorizontalAlignment = HorizontalAlignment.Right;
|
||
price.AddChild(l);
|
||
}
|
||
row.AddChild(price);
|
||
foreach (var (l, width) in new[] { (_cap, WCap), (_worth, WWorth), (_mine, WMine) })
|
||
{
|
||
l.CustomMinimumSize = new Vector2(width, 0);
|
||
l.HorizontalAlignment = HorizontalAlignment.Right;
|
||
l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||
row.AddChild(l);
|
||
}
|
||
foreach (var l in new[] { _name, _sub, _price, _change, _cap, _worth, _mine }) l.MouseFilter = MouseFilterEnum.Ignore;
|
||
_swatch.MouseFilter = MouseFilterEnum.Ignore;
|
||
}
|
||
|
||
public void SetSelected(bool on)
|
||
{
|
||
AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
|
||
}
|
||
|
||
public void Update(Color color, string name, string sub, string price, string change, Color changeColor, string cap, string worth, string mine, bool listed, bool alarm)
|
||
{
|
||
_swatch.Color = color;
|
||
_name.Text = name;
|
||
_sub.Text = sub;
|
||
TooltipText = $"{name}\n{sub}";
|
||
_sub.AddThemeColorOverride("font_color", alarm ? Palette.Danger : Palette.TextSecondary);
|
||
_price.Text = price;
|
||
_price.AddThemeColorOverride("font_color", listed ? Palette.Text : Palette.TextSecondary);
|
||
_change.Text = change;
|
||
_change.AddThemeColorOverride("font_color", changeColor);
|
||
_cap.Text = cap;
|
||
_worth.Text = worth;
|
||
_mine.Text = mine;
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ offerte pubbliche
|
||
|
||
private void RefreshBids(ClientWorld w)
|
||
{
|
||
int me = Me(w);
|
||
var bids = w.Tape?.Bids ?? [];
|
||
string key = string.Join(";", bids.Select(b => $"{b.Bid},{b.Defenses},{b.Knight},{b.Accepted},{Holds(w, b.Target)}")) + "|" + string.Join(",", w.Companies.Values.Where(c => c.Bankrupt || c.Merged).Select(c => c.Id).Order());
|
||
if (key != _bidsKey)
|
||
{
|
||
_bidsKey = key;
|
||
_bidProgress.Clear();
|
||
foreach (var c in _bids.GetChildren()) c.QueueFree();
|
||
if (bids.Count == 0)
|
||
{
|
||
var sm = w.Data.Balance.StockMarket;
|
||
_bids.AddChild(Wrapped($"{T("Nessuna offerta in corso. Un'offerta dura")} {sm.BidDurationDays} {T("giorni e offre un premio tra il")} {Fmt.Pct(sm.BidPremiumMin, 0)} " +
|
||
$"{T("e il")} {Fmt.Pct(sm.BidPremiumMax, 0)} {T("sul prezzo di mercato.")}", 13, Palette.TextSecondary));
|
||
}
|
||
foreach (var b in bids) _bids.AddChild(BidBox(w, b, me));
|
||
}
|
||
long today = Fmt.Today(w);
|
||
foreach (var b in bids)
|
||
{
|
||
if (!_bidProgress.TryGetValue(b.Bid, out var p)) continue;
|
||
p.Text.Text = $"{T("impegnato")} {Fmt.Pct(b.CommittedShare)} {T("di")} {Fmt.Pct(b.TargetShare, 0)} · {T("scade il")} {Fmt.Date(w, b.ExpiresDay)} ({Math.Max(0, b.ExpiresDay - today)} {T("giorni")})";
|
||
p.Bar.MaxValue = Math.Max(0.0001, b.TargetShare);
|
||
p.Bar.Value = Math.Min(b.CommittedShare, b.TargetShare);
|
||
}
|
||
}
|
||
|
||
private Control BidBox(ClientWorld w, BidInfo b, int me)
|
||
{
|
||
bool mine = b.Target == me || b.Bidder == me;
|
||
var box = new PanelContainer();
|
||
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, mine ? Palette.Amber : Palette.Border, 8, 12));
|
||
var col = PanelKit.Column(6);
|
||
box.AddChild(col);
|
||
col.AddChild(Wrapped($"{Fmt.Company(w, b.Bidder)} → {Fmt.Company(w, b.Target)}", 15, null, bold: true));
|
||
double market = PriceCents(w, b.Target);
|
||
string premium = market > 0 ? $" ({Fmt.Change(b.PricePerShare.Cents / market - 1)} {T("sul mercato")})" : "";
|
||
col.AddChild(Wrapped($"{Fmt.Price(b.PricePerShare.Cents)} {T("per azione")}{premium} · {T("obiettivo")} {Fmt.Pct(b.TargetShare, 0)}", 13, null));
|
||
var bar = new ProgressBar { ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
|
||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
|
||
col.AddChild(bar);
|
||
var progress = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
col.AddChild(progress);
|
||
_bidProgress[b.Bid] = (progress, bar);
|
||
if (DefenseText(w, b) is { Length: > 0 } defenses) col.AddChild(Wrapped(defenses, 12, Palette.AmberLight));
|
||
|
||
int bidId = b.Bid;
|
||
if (b.Target == me)
|
||
{
|
||
var sm = w.Data.Balance.StockMarket;
|
||
col.AddChild(Wrapped($"{T("La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del")} {Fmt.Pct(sm.ExtraDividendCashShare, 0)} " +
|
||
$"{T("della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il")} {Fmt.Pct(sm.WhiteKnightPremium, 0)}.", 12, Palette.TextSecondary));
|
||
var row = PanelKit.Row(6);
|
||
var buyback = new Button { Text = T("Riacquisto"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
buyback.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.Buyback }, Result);
|
||
row.AddChild(buyback);
|
||
var dividend = new Button { Text = T("Dividendo straordinario"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
dividend.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.ExtraDividend }, Result);
|
||
row.AddChild(dividend);
|
||
col.AddChild(row);
|
||
var knightRow = PanelKit.Row(6);
|
||
var knights = new OptionButton { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
|
||
var knightIds = w.Companies.Values.Where(c => c.Id != me && c.Id != b.Bidder && !c.Bankrupt && !c.Merged).OrderBy(c => c.Id).Select(c => c.Id).ToList();
|
||
foreach (int k in knightIds) knights.AddItem(Fmt.Company(w, k));
|
||
knightRow.AddChild(knights);
|
||
var knight = new Button { Text = T("Cavaliere bianco"), Disabled = knightIds.Count == 0 };
|
||
knight.Pressed += () =>
|
||
{
|
||
if (knights.Selected < 0 || knights.Selected >= knightIds.Count) return;
|
||
_session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(knightIds[knights.Selected]) }, Result);
|
||
};
|
||
knightRow.AddChild(knight);
|
||
col.AddChild(knightRow);
|
||
}
|
||
else if (b.Bidder == me)
|
||
{
|
||
col.AddChild(Wrapped(T("La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade."), 12, Palette.TextSecondary));
|
||
}
|
||
else if (Holds(w, b.Target) != false)
|
||
{
|
||
var respond = b.Accepted ? new Button { Text = T("Ritira l'adesione") } : UiTheme.Primary(T("Aderisci con le tue azioni"));
|
||
bool accept = !b.Accepted;
|
||
respond.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), accept), Result);
|
||
col.AddChild(respond);
|
||
if (b.Accepted) col.AddChild(UiTheme.Text(T("Hai aderito con tutte le tue azioni."), 12, Palette.Ok));
|
||
}
|
||
return box;
|
||
}
|
||
|
||
private static string DefenseText(ClientWorld w, BidInfo b)
|
||
{
|
||
var parts = new List<string>();
|
||
if ((b.Defenses & (1 << (int)BidDefense.None)) != 0) parts.Add(T("respinta dal consiglio"));
|
||
if ((b.Defenses & (1 << (int)BidDefense.Buyback)) != 0) parts.Add(T("riacquisto"));
|
||
if ((b.Defenses & (1 << (int)BidDefense.ExtraDividend)) != 0) parts.Add(T("dividendo straordinario"));
|
||
if ((b.Defenses & (1 << (int)BidDefense.WhiteKnight)) != 0) parts.Add($"{T("cavaliere bianco")} {Fmt.Company(w, b.Knight)}");
|
||
return parts.Count == 0 ? "" : $"{T("Difese del bersaglio")}: {string.Join(", ", parts)}";
|
||
}
|
||
|
||
// ------------------------------------------------------------------ scheda della compagnia
|
||
|
||
private void RefreshCard(ClientWorld w)
|
||
{
|
||
foreach (var c in _card.GetChildren()) c.QueueFree();
|
||
foreach (var c in _register.GetChildren()) c.QueueFree();
|
||
int me = Me(w);
|
||
if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
|
||
{
|
||
_chartCaption.Text = "";
|
||
_chart.Show([], [], v => "", SeriesChart.Style.Line, Palette.Amber, T("Scegli una compagnia nel listino"));
|
||
return;
|
||
}
|
||
var card = w.CompanyCards.GetValueOrDefault(_selected);
|
||
var head = PanelKit.Row(10);
|
||
var swatch = new ColorRect { Color = Fmt.CompanyColor(w, info.Id), CustomMinimumSize = new Vector2(12, 34), SizeFlagsVertical = SizeFlags.ShrinkCenter };
|
||
head.AddChild(swatch);
|
||
var title = UiTheme.TitleLabel(info.Name, 30);
|
||
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
head.AddChild(title);
|
||
_card.AddChild(head);
|
||
|
||
var badges = new HFlowContainer();
|
||
badges.AddThemeConstantOverride("h_separation", 6);
|
||
badges.AddThemeConstantOverride("v_separation", 6);
|
||
badges.AddChild(UiTheme.Badge(Fmt.Tier(w, info.Tier)));
|
||
if (info.Id == me) badges.AddChild(Tag(T("la tua compagnia"), Palette.AmberLight));
|
||
if (info.Personality.Length > 0) badges.AddChild(Tag(Fmt.Personality(w, info.Personality), Palette.Staff));
|
||
badges.AddChild(Tag(info.Listed ? T("quotata") : T("non quotata"), info.Listed ? Palette.Ok : Palette.TextSecondary));
|
||
if (info.ControlledBy >= 0) badges.AddChild(Tag($"{T("controllata da")} {Fmt.Company(w, info.ControlledBy)}", Palette.Amber));
|
||
if (info.Receivership) badges.AddChild(Tag(T("amministrazione controllata"), Palette.Danger));
|
||
if (info.Bankrupt) badges.AddChild(Tag(T("fallita"), Palette.Danger));
|
||
_card.AddChild(badges);
|
||
|
||
double price = PriceCents(w, info.Id);
|
||
var stats1 = PanelKit.Row(8);
|
||
stats1.AddChild(PanelKit.Stat(T("Prezzo per azione"), PanelKit.Value(info.Bankrupt ? "—" : Fmt.Price(price))));
|
||
stats1.AddChild(PanelKit.Stat(T("Capitalizzazione"), PanelKit.Value(card?.MarketCap.ToString("short") ?? Money.FromCentsRounded(price * Outstanding(w, info.Id)).ToString("short"))));
|
||
stats1.AddChild(PanelKit.Stat(T("Patrimonio netto"), PanelKit.Value(info.NetWorth.ToString("short"))));
|
||
_card.AddChild(stats1);
|
||
var stats2 = PanelKit.Row(8);
|
||
var profit = PanelKit.Value(info.AnnualProfit.ToString("short"));
|
||
if (info.AnnualProfit.IsNegative) profit.AddThemeColorOverride("font_color", Palette.Danger);
|
||
stats2.AddChild(PanelKit.Stat(T("Utile annuo"), profit));
|
||
stats2.AddChild(PanelKit.Stat(T("Dividendi (12 mesi)"), PanelKit.Value(card?.DividendsYear.ToString("short") ?? "—")));
|
||
stats2.AddChild(PanelKit.Stat(T("Debito"), PanelKit.Value(card?.Debt.ToString("short") ?? "—")));
|
||
_card.AddChild(stats2);
|
||
_card.AddChild(PanelKit.Pair(T("Cassa"), PanelKit.Value(info.Cash.ToString())));
|
||
_card.AddChild(PanelKit.Pair(T("Sentiment del mercato"), PanelKit.Value("×" + Fmt.Number(info.Sentiment, 2))));
|
||
if (card is { ControlDays: >= 0 } && info.ControlledBy >= 0)
|
||
_card.AddChild(PanelKit.Pair(T("Controllo"), PanelKit.Value($"{Fmt.Company(w, info.ControlledBy)} · {card.ControlDays} {T("giorni")}")));
|
||
|
||
var prices = card?.PriceHistory ?? [];
|
||
_chartCaption.Text = prices.Count > 0 ? $"{T("Prezzo dell'azione a fine mese")} · {T("ultimi")} {prices.Count} {T("mesi")}" : T("Prezzo dell'azione a fine mese");
|
||
_chart.Show(prices, [], Fmt.PricePrecise, SeriesChart.Style.Line, Fmt.CompanyColor(w, info.Id),
|
||
card is null ? T("Scheda in arrivo dal server…") : T("Lo storico si forma alla fine di ogni mese"));
|
||
|
||
BuildRegister(w, info, card);
|
||
}
|
||
|
||
private void BuildRegister(ClientWorld w, CompanyInfo info, CompanyCard? card)
|
||
{
|
||
if (card is null)
|
||
{
|
||
_register.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||
return;
|
||
}
|
||
int me = Me(w);
|
||
long outstanding = Math.Max(1, card.TotalShares - card.Treasury);
|
||
var holders = card.Holdings.Where(h => h.Shares > 0)
|
||
.OrderBy(h => h.Holder == HoldingInfo.Founder ? 0 : h.Holder == HoldingInfo.Market ? 2 : 1)
|
||
.ThenByDescending(h => h.Shares).ThenBy(h => h.Holder).ToList();
|
||
|
||
// barra a segmenti delle quote
|
||
var bar = new HBoxContainer { CustomMinimumSize = new Vector2(0, 14) };
|
||
bar.AddThemeConstantOverride("separation", 2);
|
||
foreach (var h in holders)
|
||
bar.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = Math.Max(0.002f, h.Shares / (float)card.TotalShares) });
|
||
if (card.Treasury > 0)
|
||
bar.AddChild(new ColorRect { Color = Palette.Border, SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = card.Treasury / (float)card.TotalShares });
|
||
_register.AddChild(bar);
|
||
|
||
double control = w.Data.Balance.StockMarket.ControlShare;
|
||
foreach (var h in holders)
|
||
{
|
||
double share = (double)h.Shares / outstanding;
|
||
string name = h.Holder switch
|
||
{
|
||
HoldingInfo.Founder => info.Id == me ? T("Fondatore (tu)") : T("Fondatore privato"),
|
||
HoldingInfo.Market => T("Mercato (flottante)"),
|
||
_ => Fmt.Company(w, h.Holder) + (h.Holder == me ? " (" + T("tu") + ")" : ""),
|
||
};
|
||
var row = PanelKit.Row(8);
|
||
row.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), CustomMinimumSize = new Vector2(10, 10), SizeFlagsVertical = SizeFlags.ShrinkCenter });
|
||
var n = UiTheme.Text(name, 13, h.Holder == me || (h.Holder == HoldingInfo.Founder && info.Id == me) ? Palette.AmberLight : Palette.Text);
|
||
n.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
n.ClipText = true;
|
||
n.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||
n.CustomMinimumSize = new Vector2(40, 0);
|
||
row.AddChild(n);
|
||
var count = UiTheme.Text(Fmt.Shares(h.Shares), 13, Palette.TextSecondary);
|
||
count.HorizontalAlignment = HorizontalAlignment.Right;
|
||
row.AddChild(count);
|
||
var pct = UiTheme.Text(Fmt.Pct(share), 13, share > control && h.Holder != HoldingInfo.Market ? Palette.Amber : Palette.Text, bold: true);
|
||
pct.CustomMinimumSize = new Vector2(64, 0);
|
||
pct.HorizontalAlignment = HorizontalAlignment.Right;
|
||
row.AddChild(pct);
|
||
_register.AddChild(row);
|
||
}
|
||
if (card.Treasury > 0)
|
||
_register.AddChild(PanelKit.Pair(T("Azioni proprie (non votano)"), PanelKit.Value(Fmt.Shares(card.Treasury))));
|
||
_register.AddChild(Wrapped($"{T("Quote sulle")} {Fmt.Shares(outstanding)} {T("azioni in circolazione: oltre il")} {Fmt.Pct(control, 0)} {T("si controlla la compagnia.")}", 12, Palette.TextSecondary));
|
||
}
|
||
|
||
private static Color HolderColor(ClientWorld w, int holder) => holder switch
|
||
{
|
||
HoldingInfo.Founder => Palette.Amber,
|
||
HoldingInfo.Market => Palette.TextSecondary,
|
||
_ => Fmt.CompanyColor(w, holder),
|
||
};
|
||
|
||
// ------------------------------------------------------------------ storico annuale
|
||
|
||
private void RefreshHistory(ClientWorld w)
|
||
{
|
||
foreach (var c in _history.GetChildren()) c.QueueFree();
|
||
var card = _selected >= 0 ? w.CompanyCards.GetValueOrDefault(_selected) : null;
|
||
if (card is null || card.History.Count == 0)
|
||
{
|
||
_history.AddChild(Wrapped(card is null ? T("Scheda in arrivo dal server…") : T("Nessun anno concluso: lo storico si scrive a fine anno."), 13, Palette.TextSecondary));
|
||
return;
|
||
}
|
||
var grid = new GridContainer { Columns = 5, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
grid.AddThemeConstantOverride("h_separation", 12);
|
||
grid.AddThemeConstantOverride("v_separation", 4);
|
||
foreach (string h in new[] { T("Anno"), T("Patrimonio"), T("Utile"), T("Treni"), T("Liv.") })
|
||
{
|
||
var l = UiTheme.Text(h, 12, Palette.TextSecondary);
|
||
l.HorizontalAlignment = h == T("Anno") ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||
if (h == T("Patrimonio")) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
grid.AddChild(l);
|
||
}
|
||
foreach (var y in Enumerable.Reverse(card.History).Take(8))
|
||
{
|
||
grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
|
||
foreach (var (text, color) in new[]
|
||
{
|
||
(y.NetWorth.ToString("short"), Palette.Text),
|
||
(y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Text),
|
||
($"{y.Trains}", Palette.Text),
|
||
($"{y.Tier}", Palette.Text),
|
||
})
|
||
{
|
||
var l = UiTheme.Text(text, 13, color);
|
||
l.HorizontalAlignment = HorizontalAlignment.Right;
|
||
grid.AddChild(l);
|
||
}
|
||
}
|
||
_history.AddChild(grid);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ operazioni
|
||
|
||
private void RefreshActions(ClientWorld w)
|
||
{
|
||
int me = Me(w);
|
||
if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
|
||
{
|
||
if (_actionsKey.Length > 0) Clear(_actions);
|
||
_actionsKey = "";
|
||
return;
|
||
}
|
||
var card = w.CompanyCards.GetValueOrDefault(_selected);
|
||
var meInfo = w.Companies.GetValueOrDefault(me);
|
||
bool auction = card is { AuctionEndDay: >= 0 };
|
||
bool bidOpen = w.Tape?.Bids.Any(b => b.Target == _selected) == true;
|
||
string key = $"{_selected}|{info.Listed}|{info.Bankrupt}|{info.Merged}|{info.ControlledBy == me}|{auction}|{bidOpen}|{meInfo?.Listed}|{meInfo?.Receivership}|{card is null}";
|
||
if (key == _actionsKey) return;
|
||
_actionsKey = key;
|
||
Clear(_actions);
|
||
_updateEstimates = null;
|
||
if (card is null)
|
||
{
|
||
_actions.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
|
||
return;
|
||
}
|
||
if (info.Id == me) BuildOwnActions(w, info);
|
||
else if (info.Bankrupt) BuildAuction(w, info, card);
|
||
else BuildTradeActions(w, info, bidOpen);
|
||
}
|
||
|
||
private static void Clear(Container c)
|
||
{
|
||
foreach (var child in c.GetChildren()) child.QueueFree();
|
||
}
|
||
|
||
/// <summary>Operazioni sulla compagnia del giocatore: quotazione, dividendo, riacquisto.</summary>
|
||
private void BuildOwnActions(ClientWorld w, CompanyInfo me)
|
||
{
|
||
var sm = w.Data.Balance.StockMarket;
|
||
var updates = new List<Action>();
|
||
if (!me.Listed)
|
||
{
|
||
_actions.AddChild(UiTheme.Text(T("Quotazione in borsa"), 14, bold: true));
|
||
var slider = new HSlider { MinValue = 1, MaxValue = Math.Round(sm.IpoMaxShare * 100), Step = 1, Value = Math.Round(sm.IpoMaxShare * 100 / 2), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
var label = UiTheme.Text("", 13);
|
||
label.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
_actions.AddChild(slider);
|
||
_actions.AddChild(label);
|
||
void Estimate()
|
||
{
|
||
long shares = (long)Math.Round(sm.Shares * slider.Value / 100);
|
||
label.Text = $"{T("Colloca il")} {Fmt.Number(slider.Value, 0)}% {T("del capitale")} ({Fmt.Shares(shares)} {T("azioni")}): {T("incasso stimato")} ≈ {Money.FromCentsRounded(shares * PriceCents(_session.World, me.Id))}";
|
||
}
|
||
slider.ValueChanged += _ => Estimate();
|
||
updates.Add(Estimate);
|
||
var ipo = UiTheme.Primary(T("Quotati in borsa"));
|
||
ipo.Pressed += () => _session.Command(new IpoCommand(slider.Value / 100), Result);
|
||
_actions.AddChild(ipo);
|
||
if (Fmt.UnlockTier(w, u => u.Ipo) is { } tier)
|
||
_actions.AddChild(Wrapped($"{T("La quotazione si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
|
||
}
|
||
else
|
||
{
|
||
_actions.AddChild(UiTheme.Text(T("Dividendo"), 14, bold: true));
|
||
var row = PanelKit.Row(6);
|
||
var perShare = new SpinBox { MinValue = 0.01, MaxValue = 1000, Step = 0.01, Value = 0.01, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
perShare.TooltipText = T("Dividendo per azione");
|
||
row.AddChild(perShare);
|
||
var pay = new Button { Text = T("Paga dividendo") };
|
||
pay.Pressed += () => _session.Command(new PayDividendCommand(new Money((long)Math.Round(perShare.Value * 100))), Result);
|
||
row.AddChild(pay);
|
||
_actions.AddChild(row);
|
||
var total = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
total.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
_actions.AddChild(total);
|
||
void Estimate() => total.Text = $"{T("Totale")} {new Money((long)Math.Round(perShare.Value * 100) * Outstanding(_session.World, me.Id))} {T("agli azionisti; i dividendi alzano il sentiment del titolo.")}";
|
||
perShare.ValueChanged += _ => Estimate();
|
||
updates.Add(Estimate);
|
||
}
|
||
if (me.Listed || me.Receivership)
|
||
{
|
||
_actions.AddChild(PanelKit.Separator());
|
||
_actions.AddChild(UiTheme.Text(T("Riacquisto di azioni proprie"), 14, bold: true));
|
||
updates.Add(QuantityRow(w, me.Id, T("Riacquista"), null, n => new BuySharesCommand(new CompanyId(me.Id), n, Money.Zero), null,
|
||
me.Receivership ? T("In amministrazione controllata compri anche dal controllante, con il premio di riscatto.") : T("Le azioni tornano al fondatore e alzano la tua quota.")));
|
||
}
|
||
_updateEstimates = () => { foreach (var u in updates) u(); };
|
||
}
|
||
|
||
/// <summary>Compravendita, offerta pubblica e fusione per le altre compagnie.</summary>
|
||
private void BuildTradeActions(ClientWorld w, CompanyInfo target, bool bidOpen)
|
||
{
|
||
var sm = w.Data.Balance.StockMarket;
|
||
int me = Me(w);
|
||
var updates = new List<Action>();
|
||
int id = target.Id;
|
||
if (target.Listed)
|
||
{
|
||
_actions.AddChild(UiTheme.Text(T("Compravendita di azioni"), 14, bold: true));
|
||
updates.Add(QuantityRow(w, id, T("Compra"), T("Vendi"),
|
||
n => new BuySharesCommand(new CompanyId(id), n, Money.Zero),
|
||
n => new SellSharesCommand(new CompanyId(id), n, Money.Zero),
|
||
$"{T("Spread")} {Fmt.Pct(sm.Spread, 0)}; {T("al massimo il")} {Fmt.Pct(sm.MaxDailyTradeShare, 0)} {T("del capitale per ordine.")}"));
|
||
}
|
||
else
|
||
{
|
||
_actions.AddChild(Wrapped(T("Non quotata: le sue azioni non sono sul mercato."), 13, Palette.TextSecondary));
|
||
}
|
||
|
||
if (target.ControlledBy == me)
|
||
{
|
||
_actions.AddChild(PanelKit.Separator());
|
||
_actions.AddChild(UiTheme.Text(T("Fusione"), 14, bold: true));
|
||
var info = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
info.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
_actions.AddChild(info);
|
||
updates.Add(() =>
|
||
{
|
||
long days = _session.World.CompanyCards.GetValueOrDefault(id)?.ControlDays ?? 0;
|
||
info.Text = $"{T("La controlli da")} {Math.Max(0, days)} {T("giorni")}; {T("la fusione è possibile dopo")} {sm.MergeAfterDays} {T("giorni e liquida le minoranze al prezzo di mercato.")}";
|
||
});
|
||
var merge = UiTheme.Primary(T("Incorpora la controllata"));
|
||
merge.Pressed += () => _session.Command(new MergeCompanyCommand(new CompanyId(id)), Result);
|
||
_actions.AddChild(merge);
|
||
}
|
||
else if (target.Listed)
|
||
{
|
||
_actions.AddChild(PanelKit.Separator());
|
||
_actions.AddChild(UiTheme.Text(T("Offerta pubblica di acquisto"), 14, bold: true));
|
||
if (bidOpen)
|
||
{
|
||
_actions.AddChild(Wrapped(T("C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra."), 12, Palette.TextSecondary));
|
||
}
|
||
else
|
||
{
|
||
double pMin = sm.BidPremiumMin * 100, pMax = sm.BidPremiumMax * 100;
|
||
var premiumLabel = UiTheme.Text("", 13);
|
||
var premium = new HSlider { MinValue = pMin, MaxValue = pMax, Step = 1, Value = pMin, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
_actions.AddChild(premiumLabel);
|
||
_actions.AddChild(premium);
|
||
var shareLabel = UiTheme.Text("", 13);
|
||
double minTarget = Math.Floor(sm.ControlShare * 100) + 1;
|
||
var share = new HSlider { MinValue = minTarget, MaxValue = 100, Step = 1, Value = minTarget, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
_actions.AddChild(shareLabel);
|
||
_actions.AddChild(share);
|
||
var cost = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
cost.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
_actions.AddChild(cost);
|
||
long Cents() => BidCents(PriceCents(_session.World, id), premium.Value / 100, sm.BidPremiumMin, sm.BidPremiumMax);
|
||
void Estimate()
|
||
{
|
||
var world = _session.World;
|
||
double market = PriceCents(world, id);
|
||
long cents = Cents();
|
||
string effective = market > 0 ? Fmt.Change(cents / market - 1) : "—";
|
||
premiumLabel.Text = $"{T("Premio")} {Fmt.Number(premium.Value, 0)}% · {Fmt.Price(cents)} {T("per azione")} ({effective} {T("sul mercato")}: {Fmt.PricePrecise(market)})";
|
||
shareLabel.Text = $"{T("Quota obiettivo")} {Fmt.Number(share.Value, 0)}%";
|
||
long outstanding = Outstanding(world, id);
|
||
long needed = Math.Max(0, (long)Math.Ceiling(share.Value / 100 * outstanding) - Mine(world, id));
|
||
cost.Text = $"{T("Impegno massimo")} {new Money(needed * cents)} {T("per")} {Fmt.Shares(needed)} {T("azioni")}; {T("durata")} {sm.BidDurationDays} {T("giorni")}.";
|
||
}
|
||
premium.ValueChanged += _ => Estimate();
|
||
share.ValueChanged += _ => Estimate();
|
||
updates.Add(Estimate);
|
||
var launch = UiTheme.Primary(T("Lancia l'offerta"));
|
||
launch.Pressed += () => _session.Command(new LaunchBidCommand(new CompanyId(id), new Money(Cents()), share.Value / 100), Result);
|
||
_actions.AddChild(launch);
|
||
if (Fmt.UnlockTier(w, u => u.HostileTakeover) is { } tier)
|
||
_actions.AddChild(Wrapped($"{T("Le scalate ostili si sbloccano al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
|
||
}
|
||
}
|
||
_updateEstimates = () => { foreach (var u in updates) u(); };
|
||
}
|
||
|
||
/// <summary>Offerta all'asta degli attivi di una compagnia fallita (offerta = prezzo per azione × azioni).</summary>
|
||
private void BuildAuction(ClientWorld w, CompanyInfo seller, CompanyCard card)
|
||
{
|
||
if (card.AuctionEndDay < 0)
|
||
{
|
||
_actions.AddChild(Wrapped(T("Compagnia fallita: nessuna asta in corso."), 13, Palette.TextSecondary));
|
||
return;
|
||
}
|
||
int id = seller.Id;
|
||
long total = Math.Max(1, card.TotalShares);
|
||
_actions.AddChild(UiTheme.Text(T("Asta degli attivi"), 14, bold: true));
|
||
var best = PanelKit.Value();
|
||
var closing = PanelKit.Value();
|
||
var minimum = PanelKit.Value();
|
||
_actions.AddChild(PanelKit.Pair(T("Base d'asta"), minimum));
|
||
_actions.AddChild(PanelKit.Pair(T("Miglior offerta"), best));
|
||
_actions.AddChild(PanelKit.Pair(T("Chiusura"), closing));
|
||
var row = PanelKit.Row(6);
|
||
// l'offerta si esprime in lire; il protocollo la trasmette come prezzo per azione intero in centesimi
|
||
double step = total / 100.0;
|
||
var offer = new SpinBox { MinValue = step, MaxValue = 1e12, Step = step, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
row.AddChild(offer);
|
||
var bid = UiTheme.Primary(T("Offri all'asta"));
|
||
bid.Pressed += () =>
|
||
{
|
||
long perShare = (long)Math.Ceiling(offer.Value * 100 / total - 1e-9);
|
||
_session.Command(new LaunchBidCommand(new CompanyId(id), new Money(perShare), 1), Result);
|
||
};
|
||
row.AddChild(bid);
|
||
_actions.AddChild(row);
|
||
_actions.AddChild(Wrapped(T("Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita."), 12, Palette.TextSecondary));
|
||
bool initialized = false;
|
||
_updateEstimates = () =>
|
||
{
|
||
var world = _session.World;
|
||
var c = world.CompanyCards.GetValueOrDefault(id);
|
||
if (c is null || c.AuctionEndDay < 0) return;
|
||
minimum.Text = c.AuctionMin.ToString();
|
||
best.Text = c.AuctionBestBidder >= 0 ? $"{c.AuctionBest} · {Fmt.Company(world, c.AuctionBestBidder)}" : T("nessuna");
|
||
closing.Text = $"{Fmt.Date(world, c.AuctionEndDay)} ({Math.Max(0, c.AuctionEndDay - Fmt.Today(world))} {T("giorni")})";
|
||
double floor = Math.Max(c.AuctionMin.Cents, c.AuctionBest.Cents + 1) / 100.0;
|
||
double next = Math.Ceiling(floor / step) * step;
|
||
if (!initialized || (offer.Value < next && !offer.GetLineEdit().HasFocus()))
|
||
{
|
||
initialized = true;
|
||
offer.SetValueNoSignal(next);
|
||
}
|
||
};
|
||
}
|
||
|
||
/// <summary>Riga quantità di azioni + pulsanti, con la stima del controvalore e delle azioni possedute.</summary>
|
||
private Action QuantityRow(ClientWorld w, int company, string first, string? second,
|
||
Func<long, GameCommand> firstCommand, Func<long, GameCommand>? secondCommand, string note)
|
||
{
|
||
var sm = w.Data.Balance.StockMarket;
|
||
long max = Math.Max(1, (long)(sm.Shares * sm.MaxDailyTradeShare));
|
||
var row = PanelKit.Row(6);
|
||
var qty = new SpinBox { MinValue = 1, MaxValue = max, Step = 1, CustomArrowStep = 1000, Rounded = true, Value = Math.Min(10_000, max), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
qty.TooltipText = T("Numero di azioni");
|
||
row.AddChild(qty);
|
||
var a = UiTheme.Primary(first);
|
||
a.Pressed += () => _session.Command(firstCommand((long)qty.Value), Result);
|
||
row.AddChild(a);
|
||
if (second is not null && secondCommand is not null)
|
||
{
|
||
var b = new Button { Text = second };
|
||
b.Pressed += () => _session.Command(secondCommand((long)qty.Value), Result);
|
||
row.AddChild(b);
|
||
}
|
||
_actions.AddChild(row);
|
||
var estimate = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
estimate.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
_actions.AddChild(estimate);
|
||
_actions.AddChild(Wrapped(note, 12, Palette.TextSecondary));
|
||
void Estimate()
|
||
{
|
||
var world = _session.World;
|
||
long held = Mine(world, company);
|
||
long outstanding = Math.Max(1, Outstanding(world, company));
|
||
long free = Quote(world, company)?.FreeFloat ?? 0;
|
||
estimate.Text = $"{T("Controvalore")} ≈ {Money.FromCentsRounded(qty.Value * PriceCents(world, company))} · " +
|
||
$"{(company == Me(world) ? T("il fondatore ha") : T("possiedi"))} {Fmt.Shares(held)} {T("azioni")} ({Fmt.Pct((double)held / outstanding)}) · {T("sul mercato")} {Fmt.Shares(free)}";
|
||
}
|
||
qty.ValueChanged += _ => Estimate();
|
||
return Estimate;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Prezzo intero (centesimi) dell'offerta per il premio scelto, tenuto dentro i limiti del premio
|
||
/// nonostante l'arrotondamento al centesimo.
|
||
/// </summary>
|
||
private static long BidCents(double market, double premium, double min, double max)
|
||
{
|
||
double basis = Math.Max(1e-6, market);
|
||
long cents = (long)Math.Round(basis * (1 + premium));
|
||
if (cents / basis - 1 < min) cents = (long)Math.Ceiling(basis * (1 + min) - 1e-9);
|
||
if (cents / basis - 1 > max) cents = (long)Math.Floor(basis * (1 + max) + 1e-9);
|
||
return Math.Max(1, cents);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ mattoni
|
||
|
||
private static PanelContainer Tag(string text, Color color)
|
||
{
|
||
var p = new PanelContainer();
|
||
p.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, color, 4, 6));
|
||
p.AddChild(UiTheme.Text(text, 12, color, bold: true));
|
||
return p;
|
||
}
|
||
|
||
private static Label Wrapped(string text, int size, Color? color, bool bold = false)
|
||
{
|
||
var l = UiTheme.Text(text, size, color, bold);
|
||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
return l;
|
||
}
|
||
}
|