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:
1 parent
2e5215c570
commit
9bf64b9286
32 files changed
+2338
-118
No files matched your search
@@ -390,6 +390,15 @@ public sealed class FinanceBalance
|
||||
public required CreditRating StartingRating { get; init; }
|
||||
public required int DepreciationYearsTrack { get; init; }
|
||||
public required double BookValueFloor { get; init; }
|
||||
/// <summary>Mesi chiusi conservati per voce: conto economico mensile e finestra del rating (ADR 0019).</summary>
|
||||
public required int IncomeMonths { get; init; }
|
||||
/// <summary>Anni chiusi conservati per voce nel conto economico annuale (ADR 0019).</summary>
|
||||
public required int IncomeYears { get; init; }
|
||||
/// <summary>
|
||||
/// Giorni mancanti alla bancarotta in cui la compagnia riceve un avviso, in ordine decrescente
|
||||
/// (oltre all'avviso del primo giorno di cassa negativa, ADR 0019).
|
||||
/// </summary>
|
||||
public required int[] BankruptcyWarningDaysLeft { get; init; }
|
||||
}
|
||||
|
||||
public sealed class StockMarketBalance
|
||||
|
||||
@@ -190,6 +190,15 @@ public static class DataValidator
|
||||
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames<CreditRating>(), errors);
|
||||
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
|
||||
Increasing("balance.json", "finance.ratingByScore (decrescente)", Enumerable.Reverse(b.Finance.RatingByScore), errors);
|
||||
if (b.Finance.IncomeMonths < 1 || b.Finance.IncomeMonths > 120) Err("balance.json", "finance.incomeMonths deve stare tra 1 e 120");
|
||||
if (b.Finance.IncomeYears < 1 || b.Finance.IncomeYears > 100) Err("balance.json", "finance.incomeYears deve stare tra 1 e 100");
|
||||
if (b.Finance.ProfitMarginWeight <= 0 || b.Finance.LeverageWeight <= 0) Err("balance.json", "finance.profitMarginWeight e finance.leverageWeight devono essere positivi");
|
||||
for (int i = 0; i < b.Finance.BankruptcyWarningDaysLeft.Length; i++)
|
||||
{
|
||||
if (b.Finance.BankruptcyWarningDaysLeft[i] < 1) Err("balance.json", "finance.bankruptcyWarningDaysLeft: i giorni devono essere almeno 1");
|
||||
if (i > 0 && b.Finance.BankruptcyWarningDaysLeft[i] >= b.Finance.BankruptcyWarningDaysLeft[i - 1])
|
||||
Err("balance.json", "finance.bankruptcyWarningDaysLeft deve essere strettamente decrescente");
|
||||
}
|
||||
RequireKeys("balance.json", "industryMaintenance.budgets", b.IndustryMaintenance.Budgets.Keys, ["none", "base", "high"], errors);
|
||||
if (b.IndustryMaintenance.BreakdownDays.Length != 2) Err("balance.json", "industryMaintenance.breakdownDays deve essere [min, max]");
|
||||
if (b.Growth.MaxLevel > 5 || b.Growth.MaxLevel < 1) Err("balance.json", "growth.maxLevel deve stare tra 1 e 5");
|
||||
|
||||
@@ -74,9 +74,9 @@ public enum IncomeLineKind : byte
|
||||
{
|
||||
/// <summary>Tariffe passeggeri e noli merci.</summary>
|
||||
Fares = 0,
|
||||
/// <summary>Commercio in proprio, contratti, industrie possedute, controllate.</summary>
|
||||
/// <summary>Commercio in proprio, contratti, industrie possedute, controllate, dividendi incassati.</summary>
|
||||
OtherIncome = 1,
|
||||
/// <summary>Costi d'esercizio, salari, penali.</summary>
|
||||
/// <summary>Costi d'esercizio (treni, stazioni e depositi), salari, penali, dazi, magazzini.</summary>
|
||||
OperatingCosts = 2,
|
||||
/// <summary>Manutenzione dei binari e della flotta.</summary>
|
||||
Maintenance = 3,
|
||||
@@ -258,8 +258,10 @@ public static class ClimbOutlook
|
||||
var lines = new List<IncomeLine>
|
||||
{
|
||||
new(IncomeLineKind.Fares, new Money(Sum(LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue))),
|
||||
new(IncomeLineKind.OtherIncome, new Money(Sum(LedgerEntry.Trading, LedgerEntry.Contracts, LedgerEntry.Industries, LedgerEntry.Subsidiaries))),
|
||||
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.Wages, LedgerEntry.Penalties))),
|
||||
new(IncomeLineKind.OtherIncome, new Money(Sum(LedgerEntry.Trading, LedgerEntry.Contracts, LedgerEntry.Industries, LedgerEntry.Subsidiaries,
|
||||
LedgerEntry.DividendsReceived))),
|
||||
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.StationUpkeep, LedgerEntry.Wages, LedgerEntry.Penalties,
|
||||
LedgerEntry.Duties, LedgerEntry.Storage))),
|
||||
new(IncomeLineKind.Maintenance, new Money(Sum(LedgerEntry.TrackMaintenance, LedgerEntry.FleetMaintenance))),
|
||||
new(IncomeLineKind.Interest, new Money(Sum(LedgerEntry.Interest))),
|
||||
};
|
||||
|
||||
@@ -29,6 +29,66 @@ public enum LedgerEntry : byte
|
||||
Industries = 19,
|
||||
/// <summary>Utili versati dalle compagnie controllate.</summary>
|
||||
Subsidiaries = 20,
|
||||
/// <summary>Esercizio dei binari di stazione e dei depositi (prima dentro <see cref="RunningCosts"/>, ADR 0019).</summary>
|
||||
StationUpkeep = 21,
|
||||
/// <summary>Giacenza della merce nei magazzini della compagnia (prima dentro <see cref="Trading"/>, ADR 0019).</summary>
|
||||
Storage = 22,
|
||||
/// <summary>Dazi sugli scambi in proprio con gli hub (prima dentro <see cref="Trading"/>, ADR 0019).</summary>
|
||||
Duties = 23,
|
||||
/// <summary>Dividendi incassati dalle azioni di altre compagnie (ADR 0019); <see cref="Dividends"/> resta per quelli pagati.</summary>
|
||||
DividendsReceived = 24,
|
||||
}
|
||||
|
||||
/// <summary>Sezione del conto economico di una voce del registro (ADR 0019).</summary>
|
||||
public enum IncomeSection : byte
|
||||
{
|
||||
/// <summary>Ricavi d'esercizio: entrano nell'utile operativo.</summary>
|
||||
Revenue = 0,
|
||||
/// <summary>Costi d'esercizio: entrano nell'utile operativo.</summary>
|
||||
Cost = 1,
|
||||
/// <summary>Investimenti e finanziamenti: muovono la cassa ma non l'utile operativo.</summary>
|
||||
Capital = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classificazione delle voci del registro (ADR 0019): unica fonte dell'utile operativo, dei ricavi del
|
||||
/// rating e delle righe del conto economico del pannello delle finanze.
|
||||
/// </summary>
|
||||
public static class LedgerEntries
|
||||
{
|
||||
/// <summary>Voci nell'ordine del conto economico: ricavi, costi, investimenti e finanziamenti.</summary>
|
||||
public static readonly LedgerEntry[] Ordered =
|
||||
[
|
||||
LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue, LedgerEntry.Trading, LedgerEntry.Contracts,
|
||||
LedgerEntry.Industries, LedgerEntry.Subsidiaries, LedgerEntry.DividendsReceived,
|
||||
LedgerEntry.RunningCosts, LedgerEntry.StationUpkeep, LedgerEntry.FleetMaintenance, LedgerEntry.TrackMaintenance,
|
||||
LedgerEntry.Wages, LedgerEntry.Interest, LedgerEntry.Duties, LedgerEntry.Storage, LedgerEntry.Penalties,
|
||||
LedgerEntry.Construction, LedgerEntry.VehiclePurchase, LedgerEntry.VehicleSale, LedgerEntry.IndustryPurchase,
|
||||
LedgerEntry.LoanTaken, LedgerEntry.LoanRepaid, LedgerEntry.Shares, LedgerEntry.Dividends, LedgerEntry.Other,
|
||||
];
|
||||
|
||||
public static IncomeSection Section(LedgerEntry e) => e switch
|
||||
{
|
||||
LedgerEntry.FreightRevenue or LedgerEntry.PassengerRevenue or LedgerEntry.Trading or LedgerEntry.Contracts
|
||||
or LedgerEntry.Industries or LedgerEntry.Subsidiaries or LedgerEntry.DividendsReceived => IncomeSection.Revenue,
|
||||
LedgerEntry.RunningCosts or LedgerEntry.StationUpkeep or LedgerEntry.FleetMaintenance or LedgerEntry.TrackMaintenance
|
||||
or LedgerEntry.Wages or LedgerEntry.Interest or LedgerEntry.Duties or LedgerEntry.Storage or LedgerEntry.Penalties => IncomeSection.Cost,
|
||||
_ => IncomeSection.Capital,
|
||||
};
|
||||
|
||||
/// <summary>Vero per le voci che entrano nell'utile operativo (ricavi e costi d'esercizio).</summary>
|
||||
public static bool Operating(LedgerEntry e) => Section(e) != IncomeSection.Capital;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Movimenti per voce di un mese o di un anno chiuso (ADR 0019): <see cref="Month"/> 1–12 per un mese,
|
||||
/// 0 per un anno intero.
|
||||
/// </summary>
|
||||
public sealed class IncomeRecord
|
||||
{
|
||||
public required int Year { get; init; }
|
||||
public required int Month { get; init; }
|
||||
public required long[] Entries { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Voci dello stato patrimoniale per gli attivi non monetari (ADR 0018).</summary>
|
||||
@@ -65,7 +125,7 @@ public sealed class Loan
|
||||
/// <summary>Compagnia ferroviaria (giocatore o IA).</summary>
|
||||
public sealed class Company
|
||||
{
|
||||
public const int EntryCount = 21;
|
||||
public const int EntryCount = 25;
|
||||
|
||||
public required CompanyId Id { get; init; }
|
||||
public required string Name { get; set; }
|
||||
@@ -97,6 +157,22 @@ public sealed class Company
|
||||
/// <summary>Movimenti dell'anno precedente per voce (per rating e borsa).</summary>
|
||||
public long[] LastYearEntries { get; } = new long[EntryCount];
|
||||
|
||||
/// <summary>Mesi chiusi per voce, dal più vecchio (al massimo finance.incomeMonths, ADR 0019).</summary>
|
||||
public List<IncomeRecord> IncomeMonths { get; } = [];
|
||||
|
||||
/// <summary>Anni chiusi per voce, dal più vecchio (al massimo finance.incomeYears, ADR 0019).</summary>
|
||||
public List<IncomeRecord> IncomeYears { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Misure dell'ultimo calcolo del rating (ADR 0019): margine = utile operativo / ricavi dei mesi della
|
||||
/// finestra, leva = debiti / patrimonio netto (+∞ con patrimonio non positivo e debiti), punteggio
|
||||
/// pesato e numero di mesi della finestra (0 prima del primo calcolo).
|
||||
/// </summary>
|
||||
public double RatingMargin { get; set; }
|
||||
public double RatingLeverage { get; set; }
|
||||
public double RatingScore { get; set; }
|
||||
public int RatingMonths { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi non monetari per voce (<see cref="AssetCategory"/>, centesimi),
|
||||
/// aggiornato ogni mese da <c>FinanceSystem.UpdateBookValues</c> (ADR 0018).
|
||||
@@ -204,20 +280,33 @@ public sealed class Company
|
||||
/// <summary>Capitalizzazione di borsa (centesimi).</summary>
|
||||
public double MarketCap => SharePrice * Shares.Outstanding;
|
||||
|
||||
/// <summary>Utile operativo dell'anno indicato (ricavi meno costi d'esercizio, esclusi prestiti e investimenti).</summary>
|
||||
/// <summary>
|
||||
/// Utile operativo dei movimenti indicati: somma delle voci di ricavo e di costo d'esercizio
|
||||
/// (<see cref="LedgerEntries.Operating"/>), esclusi prestiti, investimenti e capitale.
|
||||
/// </summary>
|
||||
public static long OperatingProfit(long[] entries)
|
||||
{
|
||||
long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
|
||||
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts]
|
||||
+ entries[(int)LedgerEntry.Industries] + entries[(int)LedgerEntry.Subsidiaries];
|
||||
long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance]
|
||||
+ entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages]
|
||||
+ entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties];
|
||||
return revenue + costs; // i costi sono già negativi
|
||||
long sum = 0;
|
||||
for (int i = 0; i < entries.Length && i < EntryCount; i++)
|
||||
{
|
||||
if (LedgerEntries.Operating((LedgerEntry)i)) sum += entries[i]; // i costi sono già negativi
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static long Revenue(long[] entries) =>
|
||||
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
|
||||
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts])
|
||||
+ Math.Max(0, entries[(int)LedgerEntry.Industries]) + Math.Max(0, entries[(int)LedgerEntry.Subsidiaries]);
|
||||
/// <summary>
|
||||
/// Ricavi d'esercizio: tariffe merci e passeggeri come sono, le altre voci di ricavo solo se positive
|
||||
/// (commercio, contratti, industrie, controllate, dividendi incassati).
|
||||
/// </summary>
|
||||
public static long Revenue(long[] entries)
|
||||
{
|
||||
long sum = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue];
|
||||
for (int i = 0; i < entries.Length && i < EntryCount; i++)
|
||||
{
|
||||
var e = (LedgerEntry)i;
|
||||
if (e is LedgerEntry.FreightRevenue or LedgerEntry.PassengerRevenue || LedgerEntries.Section(e) != IncomeSection.Revenue) continue;
|
||||
sum += Math.Max(0, entries[i]);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
using System.Globalization;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>Colonna del conto economico: mese in corso, mese chiuso, anno in corso o anno chiuso.</summary>
|
||||
public enum IncomeColumnKind : byte
|
||||
{
|
||||
CurrentMonth = 0,
|
||||
Month = 1,
|
||||
CurrentYear = 2,
|
||||
Year = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Movimenti per voce di un periodo (<see cref="Company.EntryCount"/> valori, indice = <see cref="LedgerEntry"/>),
|
||||
/// con l'utile operativo del motore e il flusso di cassa (somma di tutte le voci).
|
||||
/// </summary>
|
||||
public sealed class IncomeColumn
|
||||
{
|
||||
public required IncomeColumnKind Kind { get; init; }
|
||||
public required int Year { get; init; }
|
||||
/// <summary>Mese 1–12 per le colonne mensili, 0 per quelle annuali.</summary>
|
||||
public required int Month { get; init; }
|
||||
public required long[] Entries { get; init; }
|
||||
/// <summary>Utile operativo: <see cref="Company.OperatingProfit"/> sulle stesse voci.</summary>
|
||||
public required Money Profit { get; init; }
|
||||
/// <summary>Variazione della cassa nel periodo: somma di tutte le voci, investimenti e finanziamenti compresi.</summary>
|
||||
public required Money CashFlow { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Soglia di un rating: punteggio minimo e tasso di un nuovo prestito con quel rating.</summary>
|
||||
public readonly record struct RatingThreshold(CreditRating Rating, double MinScore, double LoanRate);
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione del rating (ADR 0019): le due misure conservate dal motore all'ultimo calcolo, le
|
||||
/// componenti e il punteggio, le soglie, e cosa servirebbe per il gradino sopra.
|
||||
/// </summary>
|
||||
public sealed class RatingExplanation
|
||||
{
|
||||
public required CreditRating Rating { get; init; }
|
||||
/// <summary>Vero prima del primo calcolo mensile: il rating è quello iniziale dei dati e le misure sono di oggi.</summary>
|
||||
public required bool Initial { get; init; }
|
||||
public required bool Bankrupt { get; init; }
|
||||
/// <summary>Mesi chiusi nella finestra del margine (fino a finance.incomeMonths).</summary>
|
||||
public required int Months { get; init; }
|
||||
public required double Margin { get; init; }
|
||||
/// <summary>Debiti / patrimonio netto (+∞ con patrimonio non positivo e debiti: <see cref="LeverageUnbounded"/>).</summary>
|
||||
public required double Leverage { get; init; }
|
||||
public bool LeverageUnbounded => double.IsPositiveInfinity(Leverage);
|
||||
public required double MarginWeight { get; init; }
|
||||
public required double LeverageWeight { get; init; }
|
||||
public required double MarginComponent { get; init; }
|
||||
public required double LeverageComponent { get; init; }
|
||||
public required double Score { get; init; }
|
||||
/// <summary>Soglie da AAA a C (sotto l'ultima è D).</summary>
|
||||
public required List<RatingThreshold> Thresholds { get; init; }
|
||||
/// <summary>Gradino sopra (null ad AAA) e punteggio che richiede.</summary>
|
||||
public required CreditRating? Next { get; init; }
|
||||
public required double NextThreshold { get; init; }
|
||||
/// <summary>Margine che basterebbe da solo, a leva invariata (se raggiungibile).</summary>
|
||||
public required double MarginNeeded { get; init; }
|
||||
public required bool MarginReachable { get; init; }
|
||||
/// <summary>Debiti/patrimonio massimo che basterebbe da solo, a margine invariato (se raggiungibile).</summary>
|
||||
public required double LeverageMax { get; init; }
|
||||
public required bool LeverageReachable { get; init; }
|
||||
/// <summary>Debiti da rimborsare oggi per scendere sotto <see cref="LeverageMax"/> (0 se già sotto o irraggiungibile).</summary>
|
||||
public required Money DebtToRepay { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Prestito in corso con rata e scadenza.</summary>
|
||||
public sealed class LoanDetail
|
||||
{
|
||||
public required LoanId Id { get; init; }
|
||||
public required Money Principal { get; init; }
|
||||
public required Money Remaining { get; init; }
|
||||
/// <summary>Tasso annuo fissato all'accensione.</summary>
|
||||
public required double AnnualRate { get; init; }
|
||||
public required int MonthsLeft { get; init; }
|
||||
/// <summary>Rata mensile costante sul residuo e i mesi restanti (alla francese).</summary>
|
||||
public required Money Payment { get; init; }
|
||||
/// <summary>Interessi della prossima rata.</summary>
|
||||
public required Money NextInterest { get; init; }
|
||||
/// <summary>Giorno dell'ultima rata (primo giorno del mese).</summary>
|
||||
public required long MaturityDay { get; init; }
|
||||
}
|
||||
|
||||
public sealed class FinanceOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required Money Cash { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
/// <summary>Residuo dei prestiti.</summary>
|
||||
public required Money Loans { get; init; }
|
||||
/// <summary>Cassa negativa (scoperto), tra i debiti del rating.</summary>
|
||||
public required Money Overdraft { get; init; }
|
||||
/// <summary>Voci del conto economico nell'ordine di presentazione, con la loro sezione.</summary>
|
||||
public required List<(LedgerEntry Entry, IncomeSection Section)> Lines { get; init; }
|
||||
/// <summary>Mese in corso, mesi chiusi dal più recente, anno in corso, anni chiusi dal più recente.</summary>
|
||||
public required List<IncomeColumn> Columns { get; init; }
|
||||
public required RatingExplanation Rating { get; init; }
|
||||
public required List<LoanDetail> LoanList { get; init; }
|
||||
public required Money MaxLoan { get; init; }
|
||||
public required Money LoanAvailable { get; init; }
|
||||
/// <summary>Tasso di un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public required double NewLoanRate { get; init; }
|
||||
public required double BaseRate { get; init; }
|
||||
public required double Spread { get; init; }
|
||||
public required int LoanTermMonths { get; init; }
|
||||
public required Money LoanStep { get; init; }
|
||||
public required bool LoansAllowed { get; init; }
|
||||
public required int NegativeCashDays { get; init; }
|
||||
/// <summary>Giorni di cassa negativa che portano alla bancarotta (difficulty.json, bankruptcyDays).</summary>
|
||||
public required int BankruptcyDays { get; init; }
|
||||
public required bool Bankrupt { get; init; }
|
||||
public required bool Receivership { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro delle finanze per il pannello «Finanze» (ADR 0019): pura funzione del mondo, come
|
||||
/// <see cref="ClimbOutlook"/>. Conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni
|
||||
/// chiusi) dalle stesse voci del registro che danno l'utile operativo, prestiti con rata e scadenza,
|
||||
/// spiegazione del rating dalle misure conservate dal motore, conto alla rovescia della bancarotta.
|
||||
/// </summary>
|
||||
public static class FinanceOutlook
|
||||
{
|
||||
public static FinanceOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var c = w.Company(company);
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var max = FinanceSystem.MaxLoan(w, c);
|
||||
return new FinanceOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Company = c.Id,
|
||||
Cash = c.Cash,
|
||||
NetWorth = c.NetWorth,
|
||||
Loans = c.Debt,
|
||||
Overdraft = Money.Max(Money.Zero, -c.Cash),
|
||||
Lines = LedgerEntries.Ordered.Select(e => (e, LedgerEntries.Section(e))).ToList(),
|
||||
Columns = Columns(w, c),
|
||||
Rating = Explain(w, c),
|
||||
LoanList = c.Loans.Select(l => Detail(w, l)).ToList(),
|
||||
MaxLoan = max,
|
||||
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
|
||||
NewLoanRate = FinanceSystem.LoanRate(w, c),
|
||||
BaseRate = w.Difficulty.BaseInterestRate,
|
||||
Spread = fb.RatingSpreads[c.Rating.ToString()],
|
||||
LoanTermMonths = fb.LoanTermMonths,
|
||||
LoanStep = new Money(fb.LoanStep),
|
||||
LoansAllowed = !c.Receivership && !c.Bankrupt,
|
||||
NegativeCashDays = c.NegativeCashDays,
|
||||
BankruptcyDays = w.Difficulty.BankruptcyDays,
|
||||
Bankrupt = c.Bankrupt,
|
||||
Receivership = c.Receivership,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Colonne del conto economico: mese in corso, mesi chiusi (dal più recente), anno in corso, anni chiusi.</summary>
|
||||
public static List<IncomeColumn> Columns(World w, Company c)
|
||||
{
|
||||
var today = w.Calendar.DateOfDay(w.Clock.Day);
|
||||
var list = new List<IncomeColumn> { Column(IncomeColumnKind.CurrentMonth, today.Year, today.Month, c.MonthEntries) };
|
||||
for (int i = c.IncomeMonths.Count - 1; i >= 0; i--)
|
||||
list.Add(Column(IncomeColumnKind.Month, c.IncomeMonths[i].Year, c.IncomeMonths[i].Month, c.IncomeMonths[i].Entries));
|
||||
list.Add(Column(IncomeColumnKind.CurrentYear, today.Year, 0, c.YearEntries));
|
||||
for (int i = c.IncomeYears.Count - 1; i >= 0; i--)
|
||||
list.Add(Column(IncomeColumnKind.Year, c.IncomeYears[i].Year, 0, c.IncomeYears[i].Entries));
|
||||
return list;
|
||||
}
|
||||
|
||||
private static IncomeColumn Column(IncomeColumnKind kind, int year, int month, long[] source)
|
||||
{
|
||||
var entries = new long[Company.EntryCount];
|
||||
Array.Copy(source, entries, Math.Min(source.Length, entries.Length));
|
||||
long flow = 0;
|
||||
foreach (long v in entries) flow += v;
|
||||
return new IncomeColumn
|
||||
{
|
||||
Kind = kind, Year = year, Month = month, Entries = entries,
|
||||
Profit = new Money(Company.OperatingProfit(entries)), CashFlow = new Money(flow),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Prestito con la rata sul residuo e la scadenza al primo giorno del mese dell'ultima rata.</summary>
|
||||
public static LoanDetail Detail(World w, Loan l)
|
||||
{
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
long monthStart = w.Clock.Day / dpm * dpm;
|
||||
return new LoanDetail
|
||||
{
|
||||
Id = l.Id, Principal = l.Principal, Remaining = l.Remaining, AnnualRate = l.AnnualRate, MonthsLeft = l.MonthsLeft,
|
||||
Payment = FinanceSystem.MonthlyPayment(l.Remaining, l.AnnualRate, l.MonthsLeft),
|
||||
NextInterest = Money.FromCentsRounded(l.Remaining.Cents * l.AnnualRate / 12),
|
||||
MaturityDay = monthStart + (long)Math.Max(0, l.MonthsLeft) * dpm,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione del rating con le misure dell'ultimo calcolo mensile (prima del primo calcolo, quelle di
|
||||
/// oggi). Per il gradino sopra: il margine che basterebbe a leva invariata, il debiti/patrimonio massimo
|
||||
/// a margine invariato e quanto debito rimborsare oggi per arrivarci (a patrimonio invariato: il
|
||||
/// rimborso toglie lo stesso importo da cassa e debiti).
|
||||
/// </summary>
|
||||
public static RatingExplanation Explain(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
bool initial = c.RatingMonths == 0;
|
||||
var live = FinanceSystem.Measures(c);
|
||||
double margin = initial ? live.Margin : c.RatingMargin;
|
||||
double leverage = initial ? live.Leverage : c.RatingLeverage;
|
||||
double cm = FinanceSystem.MarginComponent(margin), cl = FinanceSystem.LeverageComponent(leverage);
|
||||
double score = fb.ProfitMarginWeight * cm + fb.LeverageWeight * cl;
|
||||
var thresholds = new List<RatingThreshold>(fb.RatingByScore.Length);
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
thresholds.Add(new RatingThreshold((CreditRating)i, fb.RatingByScore[i], FinanceSystem.LoanRate(w, (CreditRating)i)));
|
||||
|
||||
CreditRating? next = c.Rating > CreditRating.AAA ? c.Rating - 1 : null;
|
||||
double target = next is { } n ? fb.RatingByScore[(int)n] : 0;
|
||||
double marginNeeded = 0, leverageMax = 0;
|
||||
bool marginOk = false, leverageOk = false;
|
||||
var repay = Money.Zero;
|
||||
if (next is not null && !c.Bankrupt)
|
||||
{
|
||||
// pesoMargine·clamp(0,5 + m) + pesoLeva·cl = soglia → m
|
||||
double needCm = (target - fb.LeverageWeight * cl) / fb.ProfitMarginWeight;
|
||||
marginOk = needCm <= 1;
|
||||
marginNeeded = Math.Max(-0.5, needCm - 0.5);
|
||||
// pesoMargine·cm + pesoLeva / (1 + ℓ) = soglia → ℓ
|
||||
double needCl = (target - fb.ProfitMarginWeight * cm) / fb.LeverageWeight;
|
||||
leverageOk = needCl <= 1;
|
||||
leverageMax = needCl <= 0 ? double.PositiveInfinity : leverageOk ? 1 / needCl - 1 : 0;
|
||||
if (leverageOk && live.Equity > 0 && needCl > 0)
|
||||
repay = new Money(Math.Max(0, live.Debt - (long)Math.Floor(leverageMax * live.Equity)));
|
||||
}
|
||||
return new RatingExplanation
|
||||
{
|
||||
Rating = c.Rating, Initial = initial, Bankrupt = c.Bankrupt,
|
||||
Months = initial ? live.Months : c.RatingMonths,
|
||||
Margin = margin, Leverage = leverage,
|
||||
MarginWeight = fb.ProfitMarginWeight, LeverageWeight = fb.LeverageWeight,
|
||||
MarginComponent = cm, LeverageComponent = cl, Score = score,
|
||||
Thresholds = thresholds, Next = next, NextThreshold = target,
|
||||
MarginNeeded = marginNeeded, MarginReachable = marginOk,
|
||||
LeverageMax = leverageMax, LeverageReachable = leverageOk, DebtToRepay = repay,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Tasso in percentuale all'italiana con un decimale («6,5%»).</summary>
|
||||
public static string Percent(double rate) =>
|
||||
(rate * 100).ToString("0.0", CultureInfo.InvariantCulture).Replace('.', ',') + "%";
|
||||
}
|
||||
@@ -26,11 +26,17 @@ public sealed class MoneyLedger(Func<CompanyId, Company> companies, Func<Industr
|
||||
/// <summary>Totale trasferito dall'inizio (statistica).</summary>
|
||||
public long TransfersCount { get; internal set; }
|
||||
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry entry)
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry entry) => Transfer(from, to, amount, entry, entry);
|
||||
|
||||
/// <summary>
|
||||
/// Trasferimento registrato su voci diverse per chi paga e chi incassa (per esempio dividendi pagati
|
||||
/// e dividendi incassati, ADR 0019): la somma dei saldi resta zero.
|
||||
/// </summary>
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry fromEntry, LedgerEntry toEntry)
|
||||
{
|
||||
if (amount.Cents == 0 || from == to) return;
|
||||
Adjust(from, -amount, entry);
|
||||
Adjust(to, amount, entry);
|
||||
Adjust(from, -amount, fromEntry);
|
||||
Adjust(to, amount, toEntry);
|
||||
TransfersCount++;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Conti delle compagnie (corpo del salvataggio dalla versione 7, ADR 0019): mesi e anni chiusi per voce
|
||||
/// del registro e misure dell'ultimo calcolo del rating. Entra nell'hash giornaliero con lo stato
|
||||
/// dinamico. Le versioni precedenti non hanno i mesi chiusi: <see cref="Migrate"/> parte da zero mesi
|
||||
/// e recupera l'ultimo anno chiuso.
|
||||
/// </summary>
|
||||
public static class FinanceSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
s.Write(w.Companies.Count);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
WriteRecords(c.IncomeMonths, s);
|
||||
WriteRecords(c.IncomeYears, s);
|
||||
s.Write(c.RatingMargin);
|
||||
s.Write(c.RatingLeverage);
|
||||
s.Write(c.RatingScore);
|
||||
s.Write(c.RatingMonths);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n != w.Companies.Count) throw new InvalidDataException($"Conti di {n} compagnie su {w.Companies.Count}");
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
ReadRecords(c.IncomeMonths, r);
|
||||
ReadRecords(c.IncomeYears, r);
|
||||
c.RatingMargin = r.ReadDouble();
|
||||
c.RatingLeverage = r.ReadDouble();
|
||||
c.RatingScore = r.ReadDouble();
|
||||
c.RatingMonths = r.ReadInt32();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrazione dalle versioni 1–6: nessun mese chiuso conservato (il conto economico mensile e la
|
||||
/// finestra del rating si riempiono dal mese dopo il caricamento); l'ultimo anno chiuso, se c'è, entra
|
||||
/// negli anni; il rating resta quello salvato e la sua spiegazione usa le misure del giorno fino al
|
||||
/// primo calcolo mensile (<see cref="Company.RatingMonths"/> = 0).
|
||||
/// </summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
c.IncomeMonths.Clear();
|
||||
c.IncomeYears.Clear();
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
bool closedYear = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
|
||||
if (closedYear && c.LastYearEntries.Any(v => v != 0))
|
||||
c.IncomeYears.Add(new IncomeRecord { Year = w.Clock.Year - 1, Month = 0, Entries = (long[])c.LastYearEntries.Clone() });
|
||||
c.RatingMargin = 0;
|
||||
c.RatingLeverage = 0;
|
||||
c.RatingScore = 0;
|
||||
c.RatingMonths = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteRecords(List<IncomeRecord> records, SaveWriter s)
|
||||
{
|
||||
s.Write(records.Count);
|
||||
foreach (var m in records)
|
||||
{
|
||||
s.Write(m.Year);
|
||||
s.Write(m.Month);
|
||||
s.Write(m.Entries);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReadRecords(List<IncomeRecord> into, SaveReader r)
|
||||
{
|
||||
into.Clear();
|
||||
int n = r.ReadInt32();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int year = r.ReadInt32();
|
||||
int month = r.ReadInt32();
|
||||
var source = r.ReadInt64Array();
|
||||
// le voci aggiunte dopo il salvataggio partono da zero
|
||||
var entries = new long[Company.EntryCount];
|
||||
Array.Copy(source, entries, Math.Min(source.Length, entries.Length));
|
||||
into.Add(new IncomeRecord { Year = year, Month = month, Entries = entries });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 6;
|
||||
public const int BodyVersion = 7;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
@@ -248,6 +248,7 @@ public static class WorldSerializer
|
||||
if (version >= 4) TradingSerializer.Write(w, s);
|
||||
if (version >= 5) EventSerializer.Write(w, s);
|
||||
if (version >= 6) BalanceSheetSerializer.Write(w, s);
|
||||
if (version >= 7) FinanceSerializer.Write(w, s);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -712,6 +713,9 @@ public static class WorldSerializer
|
||||
// versione 6 (F6): stato patrimoniale per voce e giorni dei livelli raggiunti
|
||||
if (version >= 6) BalanceSheetSerializer.Read(w, r);
|
||||
else BalanceSheetSerializer.Migrate(w);
|
||||
// versione 7 (F6): conto economico per mese e per anno, misure del rating (ADR 0019)
|
||||
if (version >= 7) FinanceSerializer.Read(w, r);
|
||||
else FinanceSerializer.Migrate(w);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -93,7 +93,10 @@ public static class CommandProcessor
|
||||
};
|
||||
company.Loans.Add(loan);
|
||||
w.Money.Transfer(Account.External, Account.Of(company.Id), c.Amount, LedgerEntry.LoanTaken);
|
||||
return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni");
|
||||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
return result(CommandError.None,
|
||||
$"Prestito di {c.Amount} al {FinanceOutlook.Percent(loan.AnnualRate)} fisso (base {FinanceOutlook.Percent(w.Difficulty.BaseInterestRate)} + rating {company.Rating}) " +
|
||||
$"per {loan.TermMonths / 12} anni: rata mensile {payment}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -114,10 +117,17 @@ public static class CommandProcessor
|
||||
if (loan is null) return result(CommandError.NotFound, "Prestito inesistente");
|
||||
if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido");
|
||||
var amount = Money.Min(c.Amount, loan.Remaining);
|
||||
if (company.Cash < amount) return result(CommandError.InsufficientFunds, "Cassa insufficiente");
|
||||
if (company.Cash < amount)
|
||||
return result(CommandError.InsufficientFunds, $"Cassa insufficiente: per rimborsare {amount} ci sono {Money.Max(Money.Zero, company.Cash)} in cassa");
|
||||
w.Money.Transfer(Account.Of(company.Id), Account.External, amount, LedgerEntry.LoanRepaid);
|
||||
loan.Remaining -= amount;
|
||||
if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan);
|
||||
return result(CommandError.None, $"Rimborsati {amount}");
|
||||
if (loan.Remaining.Cents <= 0)
|
||||
{
|
||||
company.Loans.Remove(loan);
|
||||
return result(CommandError.None, $"Rimborsati {amount}: prestito estinto");
|
||||
}
|
||||
// rimborso parziale: stessa durata e stesso tasso, la rata scende con il residuo
|
||||
return result(CommandError.None,
|
||||
$"Rimborsati {amount}: restano {loan.Remaining}, nuova rata mensile {FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft)}");
|
||||
}
|
||||
}
|
||||
@@ -5,62 +5,130 @@ using RailEnterprise.Core.Economy;
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Finanza delle compagnie: giorni di cassa negativa e bancarotta, rate mensili dei prestiti,
|
||||
/// rating di credito, chiusura dei conti mensili e annuali (guida 6.3).
|
||||
/// Finanza delle compagnie (guida 6.3, ADR 0019): costi d'esercizio e salari del personale dei depositi
|
||||
/// ogni giorno, giorni di cassa negativa con avvisi e bancarotta, rate mensili dei prestiti, chiusura dei
|
||||
/// conti mensili e annuali (conto economico per voce), rating di credito dagli ultimi mesi chiusi.
|
||||
/// </summary>
|
||||
public sealed class FinanceSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Finance";
|
||||
|
||||
private double[] _running = [];
|
||||
private double[] _upkeep = [];
|
||||
private double[] _wages = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
PayRunningCosts(w);
|
||||
PayDepotWages(w);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Defunct) continue;
|
||||
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
|
||||
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {c.NegativeCashDays} giorni di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
UpdateNegativeCash(ctx, c);
|
||||
}
|
||||
if (ctx.IsNewMonth && ctx.Day > 0)
|
||||
{
|
||||
UpdateBookValues(w);
|
||||
var closed = w.Calendar.DateOfDay(ctx.Day - 1);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Merged) continue;
|
||||
if (!c.Bankrupt) PayLoans(w, c);
|
||||
c.Rating = ComputeRating(w, c);
|
||||
CloseMonth(w, c, closed.Year, closed.Month);
|
||||
UpdateRating(w, c);
|
||||
if (!c.Bankrupt) Tiers.Evaluate(ctx, c);
|
||||
// utile del mese chiuso nell'anello dei 12 mesi (borsa, 12.2); il nuovo mese parte senza dividendi
|
||||
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
|
||||
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
|
||||
c.DividendRing[c.ProfitRingIndex] = 0;
|
||||
Array.Clear(c.MonthEntries);
|
||||
}
|
||||
}
|
||||
if (ctx.IsNewYear && ctx.Day > 0)
|
||||
{
|
||||
int year = w.Calendar.DateOfDay(ctx.Day - 1).Year;
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
Push(c.IncomeYears, new IncomeRecord { Year = year, Month = 0, Entries = (long[])c.YearEntries.Clone() }, w.Data.Balance.Finance.IncomeYears);
|
||||
Array.Copy(c.YearEntries, c.LastYearEntries, c.YearEntries.Length);
|
||||
Array.Clear(c.YearEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Costi d'esercizio giornalieri: veicoli posseduti, binari di stazione, depositi.</summary>
|
||||
/// <summary>
|
||||
/// Chiusura del mese: utile nell'anello dei 12 mesi della borsa (12.2) e movimenti per voce nel conto
|
||||
/// economico mensile (ADR 0019); il nuovo mese parte senza movimenti né dividendi.
|
||||
/// </summary>
|
||||
private static void CloseMonth(World w, Company c, int year, int month)
|
||||
{
|
||||
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
|
||||
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
|
||||
c.DividendRing[c.ProfitRingIndex] = 0;
|
||||
Push(c.IncomeMonths, new IncomeRecord { Year = year, Month = month, Entries = (long[])c.MonthEntries.Clone() }, w.Data.Balance.Finance.IncomeMonths);
|
||||
Array.Clear(c.MonthEntries);
|
||||
}
|
||||
|
||||
private static void Push(List<IncomeRecord> list, IncomeRecord record, int capacity)
|
||||
{
|
||||
list.Add(record);
|
||||
if (list.Count > capacity) list.RemoveRange(0, list.Count - capacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorni di cassa negativa (guida 6.3): avviso il primo giorno, poi quando mancano i giorni di
|
||||
/// finance.bankruptcyWarningDaysLeft; bancarotta al limite della difficoltà (difficulty.json,
|
||||
/// bankruptcyDays). Se la cassa torna positiva il conto alla rovescia si azzera con un avviso.
|
||||
/// </summary>
|
||||
private static void UpdateNegativeCash(WorldContext ctx, Company c)
|
||||
{
|
||||
var w = ctx.World;
|
||||
if (!c.Cash.IsNegative)
|
||||
{
|
||||
if (c.NegativeCashDays > 0)
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Info,
|
||||
$"{c.Name}: la cassa torna positiva dopo {Days(c.NegativeCashDays)} di scoperto, il conto alla rovescia della bancarotta si azzera",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
c.NegativeCashDays = 0;
|
||||
return;
|
||||
}
|
||||
c.NegativeCashDays++;
|
||||
int left = w.Difficulty.BankruptcyDays - c.NegativeCashDays;
|
||||
if (left <= 0)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {Days(c.NegativeCashDays)} di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
return;
|
||||
}
|
||||
var warnings = w.Data.Balance.Finance.BankruptcyWarningDaysLeft;
|
||||
if (c.NegativeCashDays == 1)
|
||||
{
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Warning,
|
||||
$"{c.Name}: cassa negativa ({c.Cash}); se non torna sopra zero la bancarotta arriva tra {Days(left)}",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
else if (Array.IndexOf(warnings, left) >= 0)
|
||||
{
|
||||
var severity = left == warnings[^1] ? EventSeverity.Critical : EventSeverity.Warning;
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, severity,
|
||||
$"{c.Name}: cassa negativa da {Days(c.NegativeCashDays)} ({c.Cash}), bancarotta tra {Days(left)}",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Days(int n) => n == 1 ? "1 giorno" : $"{n} giorni";
|
||||
|
||||
/// <summary>
|
||||
/// Costi d'esercizio giornalieri: veicoli posseduti (voce «Esercizio dei treni») e binari di stazione
|
||||
/// e depositi (voce «Stazioni e depositi», ADR 0019).
|
||||
/// </summary>
|
||||
private void PayRunningCosts(World w)
|
||||
{
|
||||
if (_running.Length < w.Companies.Count) _running = new double[w.Companies.Count];
|
||||
if (_running.Length < w.Companies.Count)
|
||||
{
|
||||
_running = new double[w.Companies.Count];
|
||||
_upkeep = new double[w.Companies.Count];
|
||||
}
|
||||
Array.Clear(_running);
|
||||
Array.Clear(_upkeep);
|
||||
double days = w.Calendar.DaysPerYear;
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
@@ -70,16 +138,41 @@ public sealed class FinanceSystem : ISimSystem
|
||||
var sp = w.Data.Construction.Stations;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _running[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _upkeep[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _running[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _upkeep[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
if (_running[i] <= 0 || w.Companies[i].Defunct) continue;
|
||||
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
|
||||
if (w.Companies[i].Defunct) continue;
|
||||
var account = Account.Of(w.Companies[i].Id);
|
||||
if (_running[i] > 0) w.Money.Transfer(account, Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
|
||||
if (_upkeep[i] > 0) w.Money.Transfer(account, Account.External, Money.FromCentsRounded(_upkeep[i]), LedgerEntry.StationUpkeep);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Salari giornalieri del personale presente nei depositi (operai e tecnici, sezione 9), alle paghe
|
||||
/// delle industrie (balance.json, industry.wagePerWorkerPerMonth e wagePerStaffPerMonth): la voce
|
||||
/// «Stipendi» della guida 6.3 (ADR 0019).
|
||||
/// </summary>
|
||||
private void PayDepotWages(World w)
|
||||
{
|
||||
if (_wages.Length < w.Companies.Count) _wages = new double[w.Companies.Count];
|
||||
Array.Clear(_wages);
|
||||
var ib = w.Data.Balance.Industry;
|
||||
double daysPerMonth = w.Calendar.DaysPerMonth;
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (!d.Owner.IsValid || d.Owner.Value >= _wages.Length || !w.Network.IsAlive(d)) continue;
|
||||
_wages[d.Owner.Value] += (d.WorkersPresent * ib.WagePerWorkerPerMonth + d.StaffPresent * ib.WagePerStaffPerMonth) / daysPerMonth;
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
if (_wages[i] <= 0 || w.Companies[i].Defunct) continue;
|
||||
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_wages[i]), LedgerEntry.Wages);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,31 +283,93 @@ public sealed class FinanceSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rating da margine operativo e leva: punteggio = pesoMargine·clamp(0,5 + margine) +
|
||||
/// pesoLeva·clamp(1 − debito/attivi), confrontato con le soglie di balance.json.
|
||||
/// Misure del rating (ADR 0019): margine = utile operativo / ricavi dei mesi chiusi conservati
|
||||
/// (finance.incomeMonths, 12), leva = debiti (prestiti e scoperto di cassa) / patrimonio netto
|
||||
/// (+∞ con patrimonio non positivo e debiti).
|
||||
/// </summary>
|
||||
public static RatingMeasures Measures(Company c)
|
||||
{
|
||||
long revenue = 0, profit = 0;
|
||||
foreach (var m in c.IncomeMonths)
|
||||
{
|
||||
revenue += Company.Revenue(m.Entries);
|
||||
profit += Company.OperatingProfit(m.Entries);
|
||||
}
|
||||
double margin = revenue > 0 ? (double)profit / revenue : 0;
|
||||
long debt = c.Debt.Cents + Math.Max(0, -c.Cash.Cents);
|
||||
long equity = c.NetWorth.Cents;
|
||||
double leverage = debt <= 0 ? 0 : equity <= 0 ? double.PositiveInfinity : (double)debt / equity;
|
||||
return new RatingMeasures(c.IncomeMonths.Count, revenue, profit, margin, debt, equity, leverage);
|
||||
}
|
||||
|
||||
/// <summary>Componente del margine nel punteggio: clamp(0,5 + margine, 0, 1).</summary>
|
||||
public static double MarginComponent(double margin) => DMath.Clamp(0.5 + margin, 0, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Componente della leva nel punteggio: 1 / (1 + debiti/patrimonio), cioè patrimonio / (debiti +
|
||||
/// patrimonio): 1 senza debiti, 0 con patrimonio non positivo e debiti.
|
||||
/// </summary>
|
||||
public static double LeverageComponent(double leverage) =>
|
||||
double.IsPositiveInfinity(leverage) ? 0 : DMath.Clamp(1 / (1 + Math.Max(0, leverage)), 0, 1);
|
||||
|
||||
/// <summary>Punteggio del rating (0–1): pesoMargine·componente del margine + pesoLeva·componente della leva.</summary>
|
||||
public static double Score(World w, double margin, double leverage)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
return fb.ProfitMarginWeight * MarginComponent(margin) + fb.LeverageWeight * LeverageComponent(leverage);
|
||||
}
|
||||
|
||||
/// <summary>Rating di un punteggio con le soglie di balance.json (finance.ratingByScore, da AAA a C; sotto è D).</summary>
|
||||
public static CreditRating RatingOf(World w, double score)
|
||||
{
|
||||
var thresholds = w.Data.Balance.Finance.RatingByScore;
|
||||
for (int i = 0; i < thresholds.Length; i++)
|
||||
{
|
||||
if (score >= thresholds[i]) return (CreditRating)i;
|
||||
}
|
||||
return CreditRating.D;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rating di credito (guida 6.3) dalle due misure di <see cref="Measures"/> confrontate con le soglie;
|
||||
/// D per una compagnia in bancarotta. Non scrive nulla.
|
||||
/// </summary>
|
||||
public static CreditRating ComputeRating(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
long[] entries = w.Clock.Day % w.Calendar.DaysPerYear < 90 ? c.LastYearEntries : c.YearEntries;
|
||||
long revenue = Company.Revenue(entries);
|
||||
long profit = Company.OperatingProfit(entries);
|
||||
double margin = revenue > 0 ? (double)profit / revenue : 0;
|
||||
double assets = Math.Max(1, c.Cash.Cents + c.AssetBookValue.Cents);
|
||||
double leverage = c.Debt.Cents / assets;
|
||||
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + margin, 0, 1) + fb.LeverageWeight * Math.Clamp(1 - leverage, 0, 1);
|
||||
if (c.Bankrupt) return CreditRating.D;
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
{
|
||||
if (score >= fb.RatingByScore[i]) return (CreditRating)i;
|
||||
}
|
||||
return CreditRating.D;
|
||||
var m = Measures(c);
|
||||
return c.Bankrupt ? CreditRating.D : RatingOf(w, Score(w, m.Margin, m.Leverage));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rating mensile, dopo la chiusura del mese: calcola il rating e conserva nella compagnia le misure
|
||||
/// usate (margine, leva, punteggio, mesi della finestra), così il quadro delle finanze lo spiega.
|
||||
/// </summary>
|
||||
public static void UpdateRating(World w, Company c)
|
||||
{
|
||||
var m = Measures(c);
|
||||
c.RatingMargin = m.Margin;
|
||||
c.RatingLeverage = m.Leverage;
|
||||
c.RatingScore = Score(w, m.Margin, m.Leverage);
|
||||
c.RatingMonths = m.Months;
|
||||
c.Rating = c.Bankrupt ? CreditRating.D : RatingOf(w, c.RatingScore);
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c) => Tiers.LoanLimit(c, Tiers.Def(w, c.Tier));
|
||||
|
||||
/// <summary>Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public static double LoanRate(World w, Company c) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[c.Rating.ToString()];
|
||||
/// <summary>
|
||||
/// Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating attuale. Il tasso resta
|
||||
/// fisso per tutta la durata del prestito (ADR 0019).
|
||||
/// </summary>
|
||||
public static double LoanRate(World w, Company c) => LoanRate(w, c.Rating);
|
||||
|
||||
/// <summary>Tasso annuo di un nuovo prestito con il rating indicato.</summary>
|
||||
public static double LoanRate(World w, CreditRating rating) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[rating.ToString()];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Misure del rating (ADR 0019): mesi della finestra, ricavi e utile operativo dei mesi, margine,
|
||||
/// debiti (prestiti e scoperto) e patrimonio netto in centesimi, leva = debiti / patrimonio.
|
||||
/// </summary>
|
||||
public readonly record struct RatingMeasures(int Months, long Revenue, long Profit, double Margin, long Debt, long Equity, double Leverage);
|
||||
@@ -414,7 +414,7 @@ public static class Dividends
|
||||
long held = shares.ByCompany[i];
|
||||
if (held <= 0 || i == payer.Id.Value) continue;
|
||||
var amount = Money.FromCentsRounded(held * perShare);
|
||||
w.Money.Transfer(Account.Of(payer.Id), Account.Of(new CompanyId(i)), amount, LedgerEntry.Dividends);
|
||||
w.Money.Transfer(Account.Of(payer.Id), Account.Of(new CompanyId(i)), amount, LedgerEntry.Dividends, LedgerEntry.DividendsReceived);
|
||||
paid += amount.Cents;
|
||||
}
|
||||
var rest = new Money(total.Cents - paid);
|
||||
|
||||
@@ -81,7 +81,10 @@ public static class TradingCommandHandlers
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ImportedThisMonth[good] += p.Units;
|
||||
w.Goods.Imported[good] += p.Units;
|
||||
w.Money.Transfer(from, Account.External, amount, LedgerEntry.Trading);
|
||||
// il prezzo d'importazione è Pg × (1 + dazio): il dazio va sulla sua voce (ADR 0019)
|
||||
var duty = Money.FromCentsRounded(p.Cents * hub.Duty / (1 + hub.Duty));
|
||||
w.Money.Transfer(from, Account.External, amount - duty, LedgerEntry.Trading);
|
||||
w.Money.Transfer(from, Account.External, duty, LedgerEntry.Duties);
|
||||
}
|
||||
}
|
||||
TradingMath.AddToWarehouse(s, good, bought, w.Data.GoodCount);
|
||||
@@ -143,7 +146,10 @@ public static class TradingCommandHandlers
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ExportedThisMonth[good] += p.Units;
|
||||
w.Goods.Exported[good] += p.Units;
|
||||
w.Money.Transfer(Account.External, to, amount, LedgerEntry.Trading);
|
||||
// il prezzo d'esportazione è Pg × (1 − dazio): si incassa il valore a Pg e si paga il dazio (ADR 0019)
|
||||
var duty = Money.FromCentsRounded(p.Cents * hub.Duty / (1 - hub.Duty));
|
||||
w.Money.Transfer(Account.External, to, amount + duty, LedgerEntry.Trading);
|
||||
w.Money.Transfer(to, Account.External, duty, LedgerEntry.Duties);
|
||||
}
|
||||
}
|
||||
s.Stock[good] -= sold;
|
||||
@@ -203,7 +209,7 @@ public static class TradingCommandHandlers
|
||||
|
||||
/// <summary>
|
||||
/// Costo di giacenza mensile (trading.storageCostPerUnitPerMonth) per ogni unità nei magazzini
|
||||
/// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Commercio».
|
||||
/// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Magazzini» (ADR 0019).
|
||||
/// </summary>
|
||||
public static void ChargeStorage(World w)
|
||||
{
|
||||
@@ -213,7 +219,7 @@ public static class TradingCommandHandlers
|
||||
{
|
||||
int units = s.StockTotal;
|
||||
if (units <= 0 || !s.Owner.IsValid || s.Owner.Value >= w.Companies.Count) continue;
|
||||
w.Money.Transfer(Account.Of(s.Owner), Account.External, new Money(perUnit * units), LedgerEntry.Trading);
|
||||
w.Money.Transfer(Account.Of(s.Owner), Account.External, new Money(perUnit * units), LedgerEntry.Storage);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -664,6 +664,9 @@ public sealed class GameHost : IDisposable
|
||||
case DetailKind.Climb:
|
||||
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Climb(w, s.Company));
|
||||
break;
|
||||
case DetailKind.Finance:
|
||||
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Finance(w, s.Company));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -589,6 +589,39 @@ public static class Projection
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Quadro delle finanze per la compagnia della sessione (FinanceOutlook, ADR 0019).</summary>
|
||||
public static FinanceReport Finance(World w, CompanyId company)
|
||||
{
|
||||
var report = FinanceOutlook.Build(w, company);
|
||||
var r = report.Rating;
|
||||
static float F(double v) => (float)Math.Clamp(v, float.MinValue, float.MaxValue);
|
||||
return new FinanceReport
|
||||
{
|
||||
Day = report.Day, Company = report.Company.Value, Cash = report.Cash, NetWorth = report.NetWorth, Loans = report.Loans, Overdraft = report.Overdraft,
|
||||
Lines = report.Lines.Select(l => new FinanceLineInfo { Kind = (byte)l.Entry, Section = (byte)l.Section }).ToList(),
|
||||
Columns = report.Columns.Select(c => new IncomeColumnInfo
|
||||
{
|
||||
Kind = (byte)c.Kind, Year = c.Year, Month = (byte)c.Month, Profit = c.Profit, CashFlow = c.CashFlow,
|
||||
Values = c.Entries.Select((v, i) => (v, i)).Where(x => x.v != 0).Select(x => new AmountInfo { Kind = (byte)x.i, Value = new Money(x.v) }).ToList(),
|
||||
}).ToList(),
|
||||
Rating = r.Rating.ToString(), RatingInitial = r.Initial, RatingMonths = (byte)Math.Clamp(r.Months, 0, 255),
|
||||
Margin = F(r.Margin), Leverage = r.LeverageUnbounded ? 0 : F(r.Leverage), LeverageUnbounded = r.LeverageUnbounded,
|
||||
MarginWeight = (float)r.MarginWeight, LeverageWeight = (float)r.LeverageWeight, MarginComponent = (float)r.MarginComponent,
|
||||
LeverageComponent = (float)r.LeverageComponent, Score = (float)r.Score,
|
||||
Thresholds = r.Thresholds.Select(t => new RatingThresholdInfo { Rating = t.Rating.ToString(), MinScore = (float)t.MinScore, LoanRate = (float)t.LoanRate }).ToList(),
|
||||
NextRating = r.Next?.ToString() ?? "", NextThreshold = (float)r.NextThreshold, MarginNeeded = F(r.MarginNeeded), MarginReachable = r.MarginReachable,
|
||||
LeverageMax = F(r.LeverageMax), LeverageReachable = r.LeverageReachable, DebtToRepay = r.DebtToRepay,
|
||||
LoanList = report.LoanList.Select(l => new FinanceLoanInfo
|
||||
{
|
||||
Loan = l.Id.Value, Principal = l.Principal, Remaining = l.Remaining, AnnualRate = (float)l.AnnualRate, MonthsLeft = l.MonthsLeft,
|
||||
Payment = l.Payment, NextInterest = l.NextInterest, MaturityDay = l.MaturityDay,
|
||||
}).ToList(),
|
||||
MaxLoan = report.MaxLoan, LoanAvailable = report.LoanAvailable, NewLoanRate = (float)report.NewLoanRate, BaseRate = (float)report.BaseRate,
|
||||
Spread = (float)report.Spread, LoanTermMonths = report.LoanTermMonths, LoanStep = report.LoanStep, LoansAllowed = report.LoansAllowed,
|
||||
NegativeCashDays = report.NegativeCashDays, BankruptcyDays = report.BankruptcyDays, Bankrupt = report.Bankrupt, Receivership = report.Receivership,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
|
||||
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user