Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Panels/FinancePanel.cs
T
Alby96andClaude Opus 5.5 9bf64b9286 F6: finanza completa con prestiti per rating, conto economico e bancarotta
Completa la finanza della guida 6.3 partendo da un'analisi delle lacune
(ADR 0019): prestiti, fido per livello, rate e bancarotta ai giorni di
difficulty.json c'erano già; mancavano gli stipendi delle compagnie, un
rating spiegabile, il conto economico per voce e gli avvisi.

- Prestiti a tasso fisso (base della difficoltà + spread del rating
  all'accensione), per non innescare la spirale rating -> rata -> utile;
  rimborso anticipato parziale e totale con messaggi chiari in italiano.
- Rating mensile da margine (utile/ricavi sugli ultimi 12 mesi chiusi) e
  leva (debiti/patrimonio netto); il motore conserva le misure e
  FinanceOutlook spiega soglie, tassi e cosa serve per salire.
- Voci nuove del registro (stazioni e depositi, magazzini, dazi, dividendi
  incassati) e stipendi del personale presente nei depositi, così il conto
  economico per voce somma esattamente all'utile operativo del motore.
- Mesi e anni chiusi per voce nel salvataggio (versione 7, con migrazione
  e nell'hash); avvisi di cassa negativa alle scadenze fisse prima del
  limite della difficoltà, esito dell'ADR 0012 invariato.
- Protocollo: DetailKind.Finance e FinanceReport; client: pannello
  «Finanze» a tutto schermo con conto economico, rating, prestiti e barra
  della cassa negativa, schermata 18_finanze nel pilota automatico.
- Test in Economy/FinanceTests.cs, round-trip del protocollo e quadro via
  WebSocket; IA e accettazioni F4/F5 invariate.

Refs #39.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:59:16 +01:00

465 lines
23 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
private void RefreshDanger(FinanceReport r)
{
bool negative = r.NegativeCashDays > 0 || r.Overdraft.Cents > 0 || r.Bankrupt;
_danger.Visible = negative;
if (!negative) return;
int left = Math.Max(0, r.BankruptcyDays - r.NegativeCashDays);
_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;
}
_dangerText.Text = $"{T("Cassa negativa da")} {Days(r.NegativeCashDays)}: {T("bancarotta tra")} {Days(left)}";
_dangerDetail.Text = $"{T("Scoperto")} {r.Overdraft}. {T("Il limite della difficoltà è di")} {Days(r.BankruptcyDays)}; "
+ T("riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi.");
}
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)"), Fmt.Pct(r.Margin, 1), r.MarginWeight, r.MarginComponent));
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
{
var ways = new List<string>();
if (r.MarginReachable) ways.Add($"{T("un margine di almeno")} {Fmt.Pct(r.MarginNeeded, 1)}");
if (r.LeverageReachable)
{
string repay = r.DebtToRepay.Cents > 0 ? $" ({T("rimborsando")} {r.DebtToRepay})" : "";
ways.Add($"{T("una leva non oltre")} {Ratio(r.LeverageMax)}{repay}");
}
string how = ways.Count == 0 ? T("serve migliorare insieme margine e leva") : string.Join($" {T("oppure")} ", ways);
_ratingBody.AddChild(Note($"{T("Per salire a")} {r.NextRating} {T("serve un punteggio di")} {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.LoansAllowed
? T("In amministrazione controllata non si possono chiedere prestiti")
: $"{T("Fido disponibile")} {r.LoanAvailable} {T("su")} {r.MaxLoan}. {T("Un nuovo prestito costa il")} {Fmt.Pct(r.NewLoanRate, 1)} "
+ $"{T("fisso")} ({T("base")} {Fmt.Pct(r.BaseRate, 1)} + {T("rating")} {r.Rating} {Fmt.Pct(r.Spread, 1)}) {T("per")} {r.LoanTermMonths / 12} {T("anni")}.";
}
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));
});
}