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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 12:59:16 +01:00
1 parent 2e5215c570
commit 9bf64b9286
32 files changed
+2338 -118

No files matched your search

@@ -53,6 +53,9 @@ public sealed class ClientWorld(GameData data)
/// <summary>Quadro della scalata (F6), su richiesta: lo usano il pannello «La tua scalata» e la barra superiore.</summary>
public ClimbReport? Climb { get; private set; }
/// <summary>Quadro delle finanze (F6), su richiesta: lo usa il pannello «Finanze».</summary>
public FinanceReport? Finance { get; private set; }
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
public int TapeVersion { get; private set; }
@@ -141,6 +144,10 @@ public sealed class ClientWorld(GameData data)
Climb = m;
DetailVersion++;
return true;
case FinanceReport m:
Finance = m;
DetailVersion++;
return true;
case MaintenanceAlert m:
Alerts.Insert(0, m);
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
@@ -162,6 +169,7 @@ public sealed class ClientWorld(GameData data)
Chronicle = null;
Market = null;
Climb = null;
Finance = null;
Alerts.Clear();
Summary = m.Summary;
SessionId = m.SessionId;
+2
View File
@@ -45,6 +45,8 @@ public enum MessageId : ushort
SaveList = 133,
/// <summary>Quadro della scalata: livelli, sblocchi, requisiti, stato patrimoniale (F6).</summary>
ClimbReport = 134,
/// <summary>Quadro delle finanze: conto economico per voce, rating spiegato, prestiti, bancarotta (F6).</summary>
FinanceReport = 135,
}
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
@@ -241,6 +241,8 @@ public enum DetailKind : byte
Market = 7,
/// <summary>Quadro della scalata (risposta ClimbReport, F6; Id ignorato).</summary>
Climb = 8,
/// <summary>Quadro delle finanze (risposta FinanceReport, F6; Id ignorato).</summary>
Finance = 9,
}
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
@@ -0,0 +1,262 @@
using RailEnterprise.Core.Common;
namespace RailEnterprise.Protocol.Messages;
// Messaggi della fase F6: pannello «Finanze» definitivo. Il quadro arriva su richiesta (RequestDetail con
// DetailKind.Finance) ed è calcolato dal server con FinanceOutlook (ADR 0019): il client lo mostra com'è,
// senza calcolare utili, rating o rate.
/// <summary>Voce del conto economico in ordine di presentazione: Kind come LedgerEntry del Core, Section 0 ricavi, 1 costi, 2 investimenti e finanziamenti.</summary>
public sealed class FinanceLineInfo
{
public const byte SectionRevenue = 0, SectionCost = 1, SectionCapital = 2;
public byte Kind { get; init; }
public byte Section { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Kind); w.U8(Section);
w.Flags(0);
}
public static FinanceLineInfo Read(ref SpanReader r)
{
var m = new FinanceLineInfo { Kind = r.U8(), Section = r.U8() };
r.Flags();
return m;
}
}
/// <summary>
/// Colonna del conto economico: Kind 0 mese in corso, 1 mese chiuso, 2 anno in corso, 3 anno chiuso;
/// Month 1–12 (0 per gli anni); Values con le sole voci diverse da zero (Kind = LedgerEntry); utile
/// operativo e flusso di cassa del motore.
/// </summary>
public sealed class IncomeColumnInfo
{
public const byte CurrentMonth = 0, ClosedMonth = 1, CurrentYear = 2, ClosedYear = 3;
public byte Kind { get; init; }
public int Year { get; init; }
public byte Month { get; init; }
public List<AmountInfo> Values { get; init; } = [];
public Money Profit { get; init; }
public Money CashFlow { get; init; }
/// <summary>Valore di una voce (zero se assente).</summary>
public Money Value(byte entry)
{
foreach (var v in Values)
{
if (v.Kind == entry) return v.Value;
}
return Money.Zero;
}
public void Write(ref SpanWriter w)
{
w.U8(Kind); w.I32(Year); w.U8(Month);
w.Count(Values.Count);
foreach (var v in Values) v.Write(ref w);
w.Money(Profit); w.Money(CashFlow);
w.Flags(0);
}
public static IncomeColumnInfo Read(ref SpanReader r)
{
byte kind = r.U8();
int year = r.I32();
byte month = r.U8();
var values = new List<AmountInfo>();
for (int n = r.Count(), i = 0; i < n; i++) values.Add(AmountInfo.Read(ref r));
var m = new IncomeColumnInfo { Kind = kind, Year = year, Month = month, Values = values, Profit = r.Money(), CashFlow = r.Money() };
r.Flags();
return m;
}
}
/// <summary>Soglia di un rating: punteggio minimo e tasso di un nuovo prestito con quel rating.</summary>
public sealed class RatingThresholdInfo
{
public string Rating { get; init; } = "";
public float MinScore { get; init; }
public float LoanRate { get; init; }
public void Write(ref SpanWriter w)
{
w.String(Rating); w.F32(MinScore); w.F32(LoanRate);
w.Flags(0);
}
public static RatingThresholdInfo Read(ref SpanReader r)
{
var m = new RatingThresholdInfo { Rating = r.String(), MinScore = r.F32(), LoanRate = r.F32() };
r.Flags();
return m;
}
}
/// <summary>Prestito in corso: capitale, residuo, tasso fisso, mesi restanti, rata, interessi della prossima rata, scadenza.</summary>
public sealed class FinanceLoanInfo
{
public int Loan { get; init; }
public Money Principal { get; init; }
public Money Remaining { get; init; }
public float AnnualRate { get; init; }
public int MonthsLeft { get; init; }
public Money Payment { get; init; }
public Money NextInterest { get; init; }
public long MaturityDay { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Loan); w.Money(Principal); w.Money(Remaining); w.F32(AnnualRate); w.I32(MonthsLeft); w.Money(Payment); w.Money(NextInterest); w.I64(MaturityDay);
w.Flags(0);
}
public static FinanceLoanInfo Read(ref SpanReader r)
{
var m = new FinanceLoanInfo
{
Loan = r.I32(), Principal = r.Money(), Remaining = r.Money(), AnnualRate = r.F32(), MonthsLeft = r.I32(),
Payment = r.Money(), NextInterest = r.Money(), MaturityDay = r.I64(),
};
r.Flags();
return m;
}
}
/// <summary>
/// Quadro delle finanze della compagnia della sessione (F6, ADR 0019): conto economico per voce (mese in
/// corso, mesi chiusi, anno in corso, anni chiusi), spiegazione del rating, prestiti, fido e conto alla
/// rovescia della bancarotta.
/// </summary>
public sealed class FinanceReport : IMessage
{
public MessageId Id => MessageId.FinanceReport;
public long Day { get; init; }
public int Company { get; init; }
public Money Cash { get; init; }
public Money NetWorth { get; init; }
public Money Loans { get; init; }
public Money Overdraft { get; init; }
/// <summary>Voci in ordine di presentazione e colonne del conto economico.</summary>
public List<FinanceLineInfo> Lines { get; init; } = [];
public List<IncomeColumnInfo> Columns { get; init; } = [];
/// <summary>Rating e sua spiegazione: misure dell'ultimo calcolo, componenti, punteggio.</summary>
public string Rating { get; init; } = "";
/// <summary>Prima del primo calcolo mensile: rating iniziale dei dati, misure di oggi.</summary>
public bool RatingInitial { get; init; }
public byte RatingMonths { get; init; }
public float Margin { get; init; }
/// <summary>Debiti / patrimonio netto; con <see cref="LeverageUnbounded"/> il patrimonio non è positivo e la leva è infinita.</summary>
public float Leverage { get; init; }
public bool LeverageUnbounded { get; init; }
public float MarginWeight { get; init; }
public float LeverageWeight { get; init; }
public float MarginComponent { get; init; }
public float LeverageComponent { get; init; }
public float Score { get; init; }
public List<RatingThresholdInfo> Thresholds { get; init; } = [];
/// <summary>Gradino sopra ("" ad AAA) con la soglia, il margine che basterebbe, la leva massima e il debito da rimborsare.</summary>
public string NextRating { get; init; } = "";
public float NextThreshold { get; init; }
public float MarginNeeded { get; init; }
public bool MarginReachable { get; init; }
public float LeverageMax { get; init; }
public bool LeverageReachable { get; init; }
public Money DebtToRepay { get; init; }
/// <summary>Prestiti, fido e condizioni di un nuovo prestito (base della difficoltà + spread del rating).</summary>
public List<FinanceLoanInfo> LoanList { get; init; } = [];
public Money MaxLoan { get; init; }
public Money LoanAvailable { get; init; }
public float NewLoanRate { get; init; }
public float BaseRate { get; init; }
public float Spread { get; init; }
public int LoanTermMonths { get; init; }
public Money LoanStep { get; init; }
public bool LoansAllowed { get; init; } = true;
/// <summary>Giorni di cassa negativa e limite della difficoltà prima della bancarotta.</summary>
public int NegativeCashDays { get; init; }
public int BankruptcyDays { get; init; }
public bool Bankrupt { get; init; }
public bool Receivership { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.I32(Company); w.Money(Cash); w.Money(NetWorth); w.Money(Loans); w.Money(Overdraft);
w.Count(Lines.Count);
foreach (var l in Lines) l.Write(ref w);
w.Count(Columns.Count);
foreach (var c in Columns) c.Write(ref w);
w.String(Rating); w.Bool(RatingInitial); w.U8(RatingMonths); w.F32(Margin); w.F32(Leverage); w.Bool(LeverageUnbounded);
w.F32(MarginWeight); w.F32(LeverageWeight); w.F32(MarginComponent); w.F32(LeverageComponent); w.F32(Score);
w.Count(Thresholds.Count);
foreach (var t in Thresholds) t.Write(ref w);
w.String(NextRating); w.F32(NextThreshold); w.F32(MarginNeeded); w.Bool(MarginReachable); w.F32(LeverageMax); w.Bool(LeverageReachable);
w.Money(DebtToRepay);
w.Count(LoanList.Count);
foreach (var l in LoanList) l.Write(ref w);
w.Money(MaxLoan); w.Money(LoanAvailable); w.F32(NewLoanRate); w.F32(BaseRate); w.F32(Spread); w.I32(LoanTermMonths); w.Money(LoanStep);
w.Bool(LoansAllowed);
w.I32(NegativeCashDays); w.I32(BankruptcyDays); w.Bool(Bankrupt); w.Bool(Receivership);
w.Flags(0);
}
public static FinanceReport Read(ref SpanReader r)
{
long day = r.I64();
int company = r.I32();
var cash = r.Money();
var worth = r.Money();
var loans = r.Money();
var overdraft = r.Money();
var lines = new List<FinanceLineInfo>();
for (int n = r.Count(), i = 0; i < n; i++) lines.Add(FinanceLineInfo.Read(ref r));
var columns = new List<IncomeColumnInfo>();
for (int n = r.Count(), i = 0; i < n; i++) columns.Add(IncomeColumnInfo.Read(ref r));
string rating = r.String();
bool initial = r.Bool();
byte months = r.U8();
float margin = r.F32(), leverage = r.F32();
bool unbounded = r.Bool();
float marginWeight = r.F32(), leverageWeight = r.F32(), marginComponent = r.F32(), leverageComponent = r.F32(), score = r.F32();
var thresholds = new List<RatingThresholdInfo>();
for (int n = r.Count(), i = 0; i < n; i++) thresholds.Add(RatingThresholdInfo.Read(ref r));
string next = r.String();
float nextThreshold = r.F32(), marginNeeded = r.F32();
bool marginReachable = r.Bool();
float leverageMax = r.F32();
bool leverageReachable = r.Bool();
var repay = r.Money();
var loanList = new List<FinanceLoanInfo>();
for (int n = r.Count(), i = 0; i < n; i++) loanList.Add(FinanceLoanInfo.Read(ref r));
var maxLoan = r.Money();
var available = r.Money();
float newRate = r.F32(), baseRate = r.F32(), spread = r.F32();
int term = r.I32();
var step = r.Money();
bool allowed = r.Bool();
int negDays = r.I32(), limit = r.I32();
bool bankrupt = r.Bool(), receivership = r.Bool();
r.Flags();
return new FinanceReport
{
Day = day, Company = company, Cash = cash, NetWorth = worth, Loans = loans, Overdraft = overdraft,
Lines = lines, Columns = columns,
Rating = rating, RatingInitial = initial, RatingMonths = months, Margin = margin, Leverage = leverage, LeverageUnbounded = unbounded,
MarginWeight = marginWeight, LeverageWeight = leverageWeight, MarginComponent = marginComponent, LeverageComponent = leverageComponent,
Score = score, Thresholds = thresholds,
NextRating = next, NextThreshold = nextThreshold, MarginNeeded = marginNeeded, MarginReachable = marginReachable,
LeverageMax = leverageMax, LeverageReachable = leverageReachable, DebtToRepay = repay,
LoanList = loanList, MaxLoan = maxLoan, LoanAvailable = available, NewLoanRate = newRate, BaseRate = baseRate, Spread = spread,
LoanTermMonths = term, LoanStep = step, LoansAllowed = allowed,
NegativeCashDays = negDays, BankruptcyDays = limit, Bankrupt = bankrupt, Receivership = receivership,
};
}
}
@@ -33,6 +33,7 @@ public static class MessageCodec
MessageId.Chronicle => Chronicle.Read(ref r),
MessageId.MarketReport => MarketReport.Read(ref r),
MessageId.ClimbReport => ClimbReport.Read(ref r),
MessageId.FinanceReport => FinanceReport.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),