Corregge i rilievi della revisione della finanza completa (ADR 0019). - Rating: il margine resta neutro finché la finestra non è piena e ha meno di finance.ratingMinRevenueMonths (3) mesi con ricavi, così il primo incasso piccolo dopo mesi di soli costi non fa perdere tre o quattro gradini (e non fissa uno spread pessimo per dieci anni); senza ricavi e in perdita il margine è il minimo. Corretta l'affermazione dell'ADR. - Avvisi di cassa negativa dopo finance.negativeCashNoticeDays (3) giorni di fila e notizia di rientro solo dopo quel primo avviso: una cassa che oscilla intorno a zero non riempie le notizie. - Spiegazione del rating: se il punteggio vale già il gradino sopra lo dice (NextAlreadyMet, ScoreRating) senza obiettivi negativi né leve infinite sul filo; il rimborso indicato è segnato come non possibile oggi se supera la cassa o il residuo dei prestiti (RepayAffordable). - Nuovi concorrenti: la quota dei trasporti usa Company.TransportRevenue (tariffe, noli, contratti), non dividendi incassati né commercio. - Client: barra del conto alla rovescia solo con lo scoperto, frasi intere con segnaposto in strings.csv, testo distinto per bancarotta e amministrazione controllata; ClimbOutlook.LoansAllowed allineato. - PROTOCOL.md: tabella dei valori di LedgerEntry e campi nuovi di FinanceReport; ServerTests non dipende più dal cambio di mese. Refs #39. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
490 lines
25 KiB
C#
490 lines
25 KiB
C#
using Godot;
|
||
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;
|
||
using RailEnterprise.Client.App;
|
||
|
||
namespace RailEnterprise.Client.Panels;
|
||
|
||
/// <summary>
|
||
/// «Finanze» a tutto schermo (palette 05, stile del pannello 08): a sinistra il conto economico per
|
||
/// voce con le colonne del mese in corso, dei mesi chiusi e dell'anno (o degli anni chiusi); a destra
|
||
/// il rating con la sua spiegazione, i prestiti con rimborso e richiesta, e, se la cassa è negativa, la
|
||
/// barra dei giorni che restano prima della bancarotta. Tutti i numeri arrivano dal server
|
||
/// (FinanceReport, ADR 0019): il pannello li chiede all'apertura, a ogni nuovo giorno e dopo un
|
||
/// comando, e li mostra com'è, senza calcolare utili, rating o rate.
|
||
/// </summary>
|
||
public partial class FinancePanel : VBoxContainer
|
||
{
|
||
/// <summary>Mesi chiusi e anni chiusi mostrati accanto alla colonna in corso.</summary>
|
||
private const int ClosedColumns = 5;
|
||
|
||
private readonly GameSession _session;
|
||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||
private readonly Label _cash = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||
private readonly PanelContainer _danger = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, Visible = false };
|
||
private readonly Label _dangerText = UiTheme.Text("", 15, Palette.Danger, bold: true);
|
||
private readonly ProgressBar _dangerBar = new() { MinValue = 0, MaxValue = 1, Step = 0.001, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||
private readonly Label _dangerDetail = UiTheme.Text("", 13, Palette.TextSecondary);
|
||
private readonly Button _months = new() { Text = "", ToggleMode = true, ButtonPressed = true, CustomMinimumSize = new Vector2(90, 36) };
|
||
private readonly Button _years = new() { Text = "", ToggleMode = true, CustomMinimumSize = new Vector2(90, 36) };
|
||
private readonly GridContainer _table = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
private readonly Label _tableNote = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
private readonly Label _rating = UiTheme.TitleLabel("", 56, Palette.AmberLight);
|
||
private readonly Label _ratingCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||
private readonly VBoxContainer _ratingBody = PanelKit.Column(6);
|
||
private readonly VBoxContainer _loans = PanelKit.Column(8);
|
||
private readonly Label _credit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 44), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||
private FinanceReport? _shown;
|
||
private long _requestedDay = long.MinValue;
|
||
private double _sinceRequest = double.MaxValue;
|
||
|
||
public event Action? CloseRequested;
|
||
|
||
public FinancePanel(GameSession session)
|
||
{
|
||
_session = session;
|
||
AddThemeConstantOverride("separation", 16);
|
||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||
|
||
var header = PanelKit.Row(24);
|
||
var titles = PanelKit.Column(0);
|
||
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
titles.AddChild(UiTheme.TitleLabel(T("Finanze"), 44));
|
||
titles.AddChild(_subtitle);
|
||
header.AddChild(titles);
|
||
var cash = PanelKit.Column(0);
|
||
cash.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||
var cashCaption = UiTheme.Text(T("Cassa"), 13, Palette.TextSecondary);
|
||
cashCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||
_cash.HorizontalAlignment = HorizontalAlignment.Right;
|
||
cash.AddChild(cashCaption);
|
||
cash.AddChild(_cash);
|
||
header.AddChild(cash);
|
||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||
close.Pressed += () => CloseRequested?.Invoke();
|
||
header.AddChild(close);
|
||
AddChild(header);
|
||
|
||
// barra della cassa negativa: giorni passati sul limite della difficoltà
|
||
_danger.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Danger, 12, 18));
|
||
var dangerCol = PanelKit.Column(8);
|
||
dangerCol.AddChild(_dangerText);
|
||
_dangerBar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 5, 0));
|
||
_dangerBar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Danger, Palette.Danger, 5, 0));
|
||
dangerCol.AddChild(_dangerBar);
|
||
_dangerDetail.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
dangerCol.AddChild(_dangerDetail);
|
||
_danger.AddChild(dangerCol);
|
||
AddChild(_danger);
|
||
|
||
var body = PanelKit.Row(20);
|
||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||
AddChild(body);
|
||
|
||
// conto economico
|
||
var left = Column(body, 1.35f);
|
||
var incomeHeader = PanelKit.Row(8);
|
||
var incomeTitle = UiTheme.Text(T("Conto economico"), 20, bold: true);
|
||
incomeTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
incomeHeader.AddChild(incomeTitle);
|
||
var group = new ButtonGroup();
|
||
_months.ButtonGroup = group;
|
||
_years.ButtonGroup = group;
|
||
_months.Text = T("Mesi");
|
||
_years.Text = T("Anni");
|
||
_months.Pressed += () => RefreshTable(_shown);
|
||
_years.Pressed += () => RefreshTable(_shown);
|
||
incomeHeader.AddChild(_months);
|
||
incomeHeader.AddChild(_years);
|
||
left.AddChild(incomeHeader);
|
||
_table.AddThemeConstantOverride("h_separation", 18);
|
||
_table.AddThemeConstantOverride("v_separation", 6);
|
||
left.AddChild(_table);
|
||
_tableNote.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
left.AddChild(_tableNote);
|
||
|
||
// rating e prestiti
|
||
var right = Column(body, 0.9f);
|
||
right.AddChild(UiTheme.Text(T("Rating creditizio"), 20, bold: true));
|
||
var ratingRow = PanelKit.Row(16);
|
||
ratingRow.AddChild(_rating);
|
||
_ratingCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||
_ratingCaption.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
_ratingCaption.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
ratingRow.AddChild(_ratingCaption);
|
||
right.AddChild(ratingRow);
|
||
right.AddChild(_ratingBody);
|
||
right.AddChild(PanelKit.Separator());
|
||
right.AddChild(UiTheme.Text(T("Prestiti"), 20, bold: true));
|
||
right.AddChild(_loans);
|
||
_credit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
right.AddChild(_credit);
|
||
var loanRow = PanelKit.Row(10);
|
||
loanRow.AddChild(_amount);
|
||
loanRow.AddChild(_borrow);
|
||
right.AddChild(loanRow);
|
||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
right.AddChild(_status);
|
||
_borrow.Text = T("Chiedi un prestito");
|
||
_borrow.Pressed += Borrow;
|
||
_amount.ValueChanged += _ => RefreshLoans(_shown);
|
||
|
||
_subtitle.Text = T("In attesa del quadro dal server…");
|
||
}
|
||
|
||
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, 12, 24));
|
||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Auto, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||
frame.AddChild(scroll);
|
||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||
margin.AddThemeConstantOverride("margin_right", 10);
|
||
scroll.AddChild(margin);
|
||
var col = PanelKit.Column(12);
|
||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||
margin.AddChild(col);
|
||
body.AddChild(frame);
|
||
return col;
|
||
}
|
||
|
||
public override void _Process(double delta)
|
||
{
|
||
var w = _session.World;
|
||
_sinceRequest += delta;
|
||
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
|
||
long today = Fmt.Today(w);
|
||
if (today != _requestedDay || (w.Finance is null && _sinceRequest > 5)) Request(today);
|
||
if (w.Finance is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||
}
|
||
|
||
private void Request(long day)
|
||
{
|
||
_requestedDay = day;
|
||
_sinceRequest = 0;
|
||
_session.Send(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||
}
|
||
|
||
// ------------------------------------------------------------------ aggiornamento
|
||
|
||
private void Refresh(ClientWorld w, FinanceReport report)
|
||
{
|
||
_shown = report;
|
||
_subtitle.Text = $"{Fmt.Company(w, report.Company)} · {Fmt.Date(w, report.Day)} · {T("patrimonio netto")} {report.NetWorth}";
|
||
_cash.Text = report.Cash.ToString();
|
||
_cash.AddThemeColorOverride("font_color", report.Cash.IsNegative ? Palette.Danger : Palette.AmberLight);
|
||
RefreshDanger(report);
|
||
RefreshTable(report);
|
||
RefreshRating(report);
|
||
RefreshLoans(report);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Barra della cassa negativa. Il motore conta i giorni una volta al giorno, quindi dopo un prestito il
|
||
/// contatore può restare indietro di un giorno rispetto alla cassa: il conto alla rovescia si mostra solo
|
||
/// con la cassa davvero negativa (scoperto) o in bancarotta.
|
||
/// </summary>
|
||
private void RefreshDanger(FinanceReport r)
|
||
{
|
||
bool overdraft = r.Overdraft.Cents > 0;
|
||
bool recovering = !overdraft && !r.Bankrupt && r.NegativeCashDays > 0;
|
||
_danger.Visible = overdraft || r.Bankrupt || recovering;
|
||
_dangerBar.Visible = overdraft || r.Bankrupt;
|
||
if (!_danger.Visible) return;
|
||
_dangerBar.Value = r.BankruptcyDays > 0 ? Math.Clamp((double)r.NegativeCashDays / r.BankruptcyDays, 0, 1) : 1;
|
||
if (r.Bankrupt)
|
||
{
|
||
_dangerText.Text = T("Bancarotta dichiarata");
|
||
_dangerDetail.Text = T("La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.");
|
||
return;
|
||
}
|
||
if (recovering)
|
||
{
|
||
_dangerText.Text = T("La cassa è tornata positiva");
|
||
_dangerDetail.Text = string.Format(T("Dopo {0} di cassa negativa il conto alla rovescia della bancarotta si azzera domani."), Days(r.NegativeCashDays));
|
||
return;
|
||
}
|
||
int left = Math.Max(0, r.BankruptcyDays - r.NegativeCashDays);
|
||
_dangerText.Text = r.NegativeCashDays == 0
|
||
? string.Format(T("Cassa negativa da oggi: bancarotta tra {0}"), Days(r.BankruptcyDays))
|
||
: string.Format(T("Cassa negativa da {0}: bancarotta tra {1}"), Days(r.NegativeCashDays), Days(left));
|
||
_dangerDetail.Text = string.Format(T("Scoperto {0}. Il limite della difficoltà è di {1}; riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi."),
|
||
r.Overdraft, Days(r.BankruptcyDays));
|
||
}
|
||
|
||
private static string Days(int n) => n == 1 ? $"1 {T("giorno")}" : $"{n} {T("giorni")}";
|
||
|
||
// ------------------------------------------------------------------ conto economico
|
||
|
||
private static string[] MonthNames() =>
|
||
[T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
|
||
|
||
/// <summary>Colonne da mostrare: il mese in corso e i mesi chiusi, poi l'anno in corso; oppure l'anno in corso e gli anni chiusi.</summary>
|
||
private List<IncomeColumnInfo> ShownColumns(FinanceReport r)
|
||
{
|
||
if (_years.ButtonPressed)
|
||
{
|
||
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)
|
||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedYear).Take(ClosedColumns)).ToList();
|
||
}
|
||
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentMonth)
|
||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedMonth).Take(ClosedColumns))
|
||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)).ToList();
|
||
}
|
||
|
||
private static string ColumnTitle(IncomeColumnInfo c)
|
||
{
|
||
string month = c.Month is >= 1 and <= 12 ? MonthNames()[c.Month - 1] : "";
|
||
return c.Kind switch
|
||
{
|
||
IncomeColumnInfo.CurrentMonth => $"{month} {c.Year}\n{T("in corso")}",
|
||
IncomeColumnInfo.ClosedMonth => $"{month} {c.Year}\n ",
|
||
IncomeColumnInfo.CurrentYear => $"{c.Year}\n{T("finora")}",
|
||
_ => $"{c.Year}\n ",
|
||
};
|
||
}
|
||
|
||
private void RefreshTable(FinanceReport? r)
|
||
{
|
||
foreach (var c in _table.GetChildren()) c.QueueFree();
|
||
if (r is null) return;
|
||
var columns = ShownColumns(r);
|
||
_table.Columns = columns.Count + 1;
|
||
Cell(T("Voce"), Palette.TextSecondary, bold: true, left: true);
|
||
foreach (var c in columns)
|
||
Cell(ColumnTitle(c), c.Kind is IncomeColumnInfo.CurrentMonth or IncomeColumnInfo.CurrentYear ? Palette.AmberLight : Palette.TextSecondary, bold: true);
|
||
|
||
foreach (byte section in new[] { FinanceLineInfo.SectionRevenue, FinanceLineInfo.SectionCost, FinanceLineInfo.SectionCapital })
|
||
{
|
||
// le voci sempre a zero nelle colonne mostrate non occupano righe
|
||
var lines = r.Lines.Where(l => l.Section == section && columns.Any(c => c.Value(l.Kind).Cents != 0)).ToList();
|
||
if (lines.Count == 0) continue;
|
||
Cell(SectionName(section), Palette.Amber, bold: true, left: true);
|
||
foreach (var _ in columns) Cell("", Palette.Text);
|
||
foreach (var line in lines)
|
||
{
|
||
Cell(EntryName((LedgerEntry)line.Kind), Palette.Text, left: true, indent: true);
|
||
foreach (var c in columns)
|
||
{
|
||
var v = c.Value(line.Kind);
|
||
Cell(v.Cents == 0 ? "—" : v.ToString(), v.IsNegative ? Palette.Danger : v.Cents == 0 ? Palette.TextSecondary : Palette.Text);
|
||
}
|
||
}
|
||
if (section == FinanceLineInfo.SectionCost)
|
||
{
|
||
Cell(T("Utile operativo"), Palette.Text, bold: true, left: true);
|
||
foreach (var c in columns) Cell(c.Profit.ToString(), c.Profit.IsNegative ? Palette.Danger : Palette.AmberLight, bold: true);
|
||
}
|
||
}
|
||
Cell(T("Flusso di cassa"), Palette.Text, bold: true, left: true);
|
||
foreach (var c in columns) Cell(c.CashFlow.ToString(), c.CashFlow.IsNegative ? Palette.Danger : Palette.Ok, bold: true);
|
||
_tableNote.Text = columns.Count <= 1
|
||
? T("I mesi e gli anni chiusi compaiono qui man mano che passano.")
|
||
: T("L'utile operativo comprende ricavi e costi d'esercizio; investimenti, prestiti e azioni cambiano solo la cassa.");
|
||
}
|
||
|
||
private void Cell(string text, Color color, bool bold = false, bool left = false, bool indent = false)
|
||
{
|
||
var l = UiTheme.Text(indent ? " " + text : text, 14, color, bold);
|
||
l.HorizontalAlignment = left ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||
if (left) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
else l.CustomMinimumSize = new Vector2(110, 0);
|
||
_table.AddChild(l);
|
||
}
|
||
|
||
private static string SectionName(byte section) => section switch
|
||
{
|
||
FinanceLineInfo.SectionRevenue => T("Ricavi"),
|
||
FinanceLineInfo.SectionCost => T("Costi"),
|
||
_ => T("Investimenti e finanziamenti"),
|
||
};
|
||
|
||
/// <summary>Nome della voce del registro nella lingua dell'interfaccia.</summary>
|
||
public static string EntryName(LedgerEntry e) => e switch
|
||
{
|
||
LedgerEntry.FreightRevenue => T("Noli merci"),
|
||
LedgerEntry.PassengerRevenue => T("Biglietti passeggeri"),
|
||
LedgerEntry.Trading => T("Commercio in proprio"),
|
||
LedgerEntry.Contracts => T("Contratti"),
|
||
LedgerEntry.Industries => T("Industrie possedute"),
|
||
LedgerEntry.Subsidiaries => T("Controllate"),
|
||
LedgerEntry.DividendsReceived => T("Dividendi incassati"),
|
||
LedgerEntry.RunningCosts => T("Esercizio dei treni"),
|
||
LedgerEntry.StationUpkeep => T("Stazioni e depositi"),
|
||
LedgerEntry.FleetMaintenance => T("Manutenzione dei treni"),
|
||
LedgerEntry.TrackMaintenance => T("Manutenzione dei binari"),
|
||
LedgerEntry.Wages => T("Stipendi"),
|
||
LedgerEntry.Interest => T("Interessi"),
|
||
LedgerEntry.Duties => T("Dazi"),
|
||
LedgerEntry.Storage => T("Magazzini"),
|
||
LedgerEntry.Penalties => T("Penali"),
|
||
LedgerEntry.Construction => T("Costruzioni"),
|
||
LedgerEntry.VehiclePurchase => T("Acquisto di treni"),
|
||
LedgerEntry.VehicleSale => T("Vendita di treni"),
|
||
LedgerEntry.IndustryPurchase => T("Acquisto di industrie"),
|
||
LedgerEntry.LoanTaken => T("Prestiti ricevuti"),
|
||
LedgerEntry.LoanRepaid => T("Prestiti rimborsati"),
|
||
LedgerEntry.Shares => T("Azioni"),
|
||
LedgerEntry.Dividends => T("Dividendi pagati"),
|
||
_ => T("Altro"),
|
||
};
|
||
|
||
// ------------------------------------------------------------------ rating
|
||
|
||
private static string Ratio(double value) => Fmt.Number(value, 2);
|
||
|
||
private void RefreshRating(FinanceReport r)
|
||
{
|
||
_rating.Text = r.Rating;
|
||
_ratingCaption.Text = r.RatingInitial
|
||
? T("Rating iniziale: il primo calcolo arriva a inizio mese. Le misure qui sotto sono quelle di oggi.")
|
||
: $"{T("Calcolato a inizio mese sugli ultimi")} {r.RatingMonths} {(r.RatingMonths == 1 ? T("mese chiuso") : T("mesi chiusi"))}. "
|
||
+ $"{T("Punteggio")} {Ratio(r.Score)}.";
|
||
foreach (var c in _ratingBody.GetChildren()) c.QueueFree();
|
||
|
||
_ratingBody.AddChild(Measure(T("Margine (utile / ricavi)"), r.MarginNeutral ? T("neutro") : Fmt.Pct(r.Margin, 1), r.MarginWeight, r.MarginComponent));
|
||
if (r.MarginNeutral)
|
||
_ratingBody.AddChild(Note(string.Format(T("Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating."),
|
||
r.MinRevenueMonths, r.RevenueMonths)));
|
||
string leverage = r.LeverageUnbounded ? T("patrimonio non positivo") : Ratio(r.Leverage);
|
||
_ratingBody.AddChild(Measure(T("Leva (debiti / patrimonio netto)"), leverage, r.LeverageWeight, r.LeverageComponent));
|
||
|
||
if (r.Bankrupt)
|
||
{
|
||
_ratingBody.AddChild(Note(T("In bancarotta il rating è D finché la situazione non si risolve.")));
|
||
}
|
||
else if (r.NextRating.Length == 0)
|
||
{
|
||
_ratingBody.AddChild(Note(T("È il rating più alto: i prestiti costano il minimo.")));
|
||
}
|
||
else if (r.NextAlreadyMet)
|
||
{
|
||
_ratingBody.AddChild(Note(string.Format(T("Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese."),
|
||
Ratio(r.Score), r.ScoreRating)));
|
||
}
|
||
else
|
||
{
|
||
var ways = new List<string>();
|
||
if (r.MarginReachable) ways.Add(string.Format(T("un margine di almeno {0}"), Fmt.Pct(r.MarginNeeded, 1)));
|
||
if (r.LeverageReachable)
|
||
{
|
||
string way = r.DebtToRepay.Cents <= 0 ? T("una leva non oltre {0}")
|
||
: r.RepayAffordable ? T("una leva non oltre {0} (rimborsando {1})")
|
||
: T("una leva non oltre {0} (servirebbe rimborsare {1}, più di quanto la cassa consenta oggi)");
|
||
ways.Add(string.Format(way, Ratio(r.LeverageMax), r.DebtToRepay));
|
||
}
|
||
string how = ways.Count == 0 ? T("serve migliorare insieme margine e leva") : string.Join($" {T("oppure")} ", ways);
|
||
_ratingBody.AddChild(Note(string.Format(T("Per il gradino {0} serve un punteggio di {1}: {2}."), r.NextRating, Ratio(r.NextThreshold), how)));
|
||
}
|
||
|
||
// soglie e tassi per rating
|
||
var grid = new GridContainer { Columns = 3 };
|
||
grid.AddThemeConstantOverride("h_separation", 24);
|
||
grid.AddChild(UiTheme.Text(T("Rating"), 12, Palette.TextSecondary, bold: true));
|
||
grid.AddChild(UiTheme.Text(T("Punteggio da"), 12, Palette.TextSecondary, bold: true));
|
||
grid.AddChild(UiTheme.Text(T("Tasso"), 12, Palette.TextSecondary, bold: true));
|
||
foreach (var t in r.Thresholds)
|
||
{
|
||
bool current = t.Rating == r.Rating;
|
||
var color = current ? Palette.AmberLight : Palette.TextSecondary;
|
||
grid.AddChild(UiTheme.Text(t.Rating, 12, color, current));
|
||
grid.AddChild(UiTheme.Text(Ratio(t.MinScore), 12, color, current));
|
||
grid.AddChild(UiTheme.Text(Fmt.Pct(t.LoanRate, 1), 12, color, current));
|
||
}
|
||
_ratingBody.AddChild(grid);
|
||
}
|
||
|
||
private static Control Measure(string caption, string value, float weight, float component)
|
||
{
|
||
var col = PanelKit.Column(4);
|
||
var row = PanelKit.Row(8);
|
||
var c = UiTheme.Text(caption, 14, Palette.Text);
|
||
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
row.AddChild(c);
|
||
row.AddChild(UiTheme.Text(value, 14, Palette.Text, bold: true));
|
||
col.AddChild(row);
|
||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(component, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 6) };
|
||
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 3, 0));
|
||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
|
||
col.AddChild(bar);
|
||
col.AddChild(UiTheme.Text($"{T("componente")} {Ratio(component)} × {T("peso")} {Ratio(weight)}", 12, Palette.TextSecondary));
|
||
return col;
|
||
}
|
||
|
||
private static Label Note(string text)
|
||
{
|
||
var l = UiTheme.Text(text, 13, Palette.Text);
|
||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||
return l;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||
|
||
private Money Amount => Money.FromLire((long)_amount.Value);
|
||
|
||
private void RefreshLoans(FinanceReport? r)
|
||
{
|
||
foreach (var c in _loans.GetChildren()) c.QueueFree();
|
||
if (r is null) return;
|
||
var w = _session.World;
|
||
if (r.LoanList.Count == 0) _loans.AddChild(UiTheme.Text(T("Nessun prestito in corso."), 13, Palette.TextSecondary));
|
||
foreach (var loan in r.LoanList)
|
||
{
|
||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 12));
|
||
var col = PanelKit.Column(4);
|
||
var head = PanelKit.Row(8);
|
||
var title = UiTheme.Text($"{T("Residuo")} {loan.Remaining} {T("su")} {loan.Principal}", 14, Palette.Text, bold: true);
|
||
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||
head.AddChild(title);
|
||
head.AddChild(UiTheme.Text($"{Fmt.Pct(loan.AnnualRate, 1)} {T("fisso")}", 14, Palette.AmberLight, bold: true));
|
||
col.AddChild(head);
|
||
col.AddChild(UiTheme.Text(
|
||
$"{T("Rata mensile")} {loan.Payment} ({T("interessi")} {loan.NextInterest}) · {loan.MonthsLeft} {T("mesi")} · {T("scadenza")} {Fmt.Date(w, loan.MaturityDay)}",
|
||
12, Palette.TextSecondary));
|
||
var buttons = PanelKit.Row(8);
|
||
var part = Money.Min(Amount, loan.Remaining);
|
||
var repay = new Button { Text = $"{T("Rimborsa")} {part}", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
repay.Disabled = part >= loan.Remaining;
|
||
int id = loan.Loan;
|
||
repay.Pressed += () => Repay(id, part);
|
||
var all = new Button { Text = $"{T("Estingui")} ({loan.Remaining})", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||
var remaining = loan.Remaining;
|
||
all.Pressed += () => Repay(id, remaining);
|
||
buttons.AddChild(repay);
|
||
buttons.AddChild(all);
|
||
col.AddChild(buttons);
|
||
card.AddChild(col);
|
||
_loans.AddChild(card);
|
||
}
|
||
|
||
_borrow.Disabled = !r.LoansAllowed || r.LoanAvailable.Cents <= 0;
|
||
_credit.Text = r.Bankrupt ? T("In bancarotta non si possono chiedere prestiti")
|
||
: r.Receivership ? T("In amministrazione controllata non si possono chiedere prestiti")
|
||
: string.Format(T("Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni."),
|
||
r.LoanAvailable, r.MaxLoan, Fmt.Pct(r.NewLoanRate, 1), Fmt.Pct(r.BaseRate, 1), r.Rating, Fmt.Pct(r.Spread, 1), r.LoanTermMonths / 12);
|
||
}
|
||
|
||
private void Borrow() =>
|
||
_session.Command(new TakeLoanCommand(Amount), r =>
|
||
{
|
||
_status.Text = r.Message;
|
||
Request(Fmt.Today(_session.World));
|
||
});
|
||
|
||
private void Repay(int loan, Money amount) =>
|
||
_session.Command(new RepayLoanCommand(new LoanId(loan), amount), r =>
|
||
{
|
||
_status.Text = r.Message;
|
||
Request(Fmt.Today(_session.World));
|
||
});
|
||
}
|