Corregge i rilievi della revisione della finanza completa (ADR 0019). - Rating: il margine resta neutro finché la finestra non è piena e ha meno di finance.ratingMinRevenueMonths (3) mesi con ricavi, così il primo incasso piccolo dopo mesi di soli costi non fa perdere tre o quattro gradini (e non fissa uno spread pessimo per dieci anni); senza ricavi e in perdita il margine è il minimo. Corretta l'affermazione dell'ADR. - Avvisi di cassa negativa dopo finance.negativeCashNoticeDays (3) giorni di fila e notizia di rientro solo dopo quel primo avviso: una cassa che oscilla intorno a zero non riempie le notizie. - Spiegazione del rating: se il punteggio vale già il gradino sopra lo dice (NextAlreadyMet, ScoreRating) senza obiettivi negativi né leve infinite sul filo; il rimborso indicato è segnato come non possibile oggi se supera la cassa o il residuo dei prestiti (RepayAffordable). - Nuovi concorrenti: la quota dei trasporti usa Company.TransportRevenue (tariffe, noli, contratti), non dividendi incassati né commercio. - Client: barra del conto alla rovescia solo con lo scoperto, frasi intere con segnaposto in strings.csv, testo distinto per bancarotta e amministrazione controllata; ClimbOutlook.LoansAllowed allineato. - PROTOCOL.md: tabella dei valori di LedgerEntry e campi nuovi di FinanceReport; ServerTests non dipende più dal cambio di mese. Refs #39. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
390 lines
18 KiB
C#
390 lines
18 KiB
C#
using RailEnterprise.Core.Common;
|
||
using RailEnterprise.Core.Data;
|
||
using RailEnterprise.Core.Economy;
|
||
|
||
namespace RailEnterprise.Core.Simulation.Systems;
|
||
|
||
/// <summary>
|
||
/// 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;
|
||
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);
|
||
CloseMonth(w, c, closed.Year, closed.Month);
|
||
UpdateRating(w, c);
|
||
if (!c.Bankrupt) Tiers.Evaluate(ctx, c);
|
||
}
|
||
}
|
||
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>
|
||
/// 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): primo avviso dopo finance.negativeCashNoticeDays giorni di
|
||
/// fila, 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 solo se era durato almeno i giorni del primo avviso: una cassa che oscilla
|
||
/// intorno a zero non riempie le notizie.
|
||
/// </summary>
|
||
private static void UpdateNegativeCash(WorldContext ctx, Company c)
|
||
{
|
||
var w = ctx.World;
|
||
int notice = w.Data.Balance.Finance.NegativeCashNoticeDays;
|
||
if (!c.Cash.IsNegative)
|
||
{
|
||
if (c.NegativeCashDays >= notice)
|
||
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 == notice)
|
||
{
|
||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Warning,
|
||
$"{c.Name}: cassa negativa da {Days(c.NegativeCashDays)} ({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];
|
||
_upkeep = new double[w.Companies.Count];
|
||
}
|
||
Array.Clear(_running);
|
||
Array.Clear(_upkeep);
|
||
double days = w.Calendar.DaysPerYear;
|
||
foreach (var v in w.Vehicles)
|
||
{
|
||
// il motore usurato consuma di più (10.1)
|
||
if (!v.Sold) _running[v.Owner.Value] += v.Def.RunningCostPerYear / days * Fleet.FuelFactor(w, v);
|
||
}
|
||
var sp = w.Data.Construction.Stations;
|
||
foreach (var s in w.Network.Stations)
|
||
{
|
||
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) _upkeep[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||
}
|
||
for (int i = 0; i < w.Companies.Count; i++)
|
||
{
|
||
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);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo,
|
||
/// industrie possedute (impianti e cassa dell'impresa, ADR 0018), merce della compagnia
|
||
/// (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016). Scrive le voci in
|
||
/// <see cref="Company.BookValues"/>: il patrimonio netto le somma.
|
||
/// </summary>
|
||
public static void UpdateBookValues(World w)
|
||
{
|
||
var values = BookValues(w);
|
||
for (int i = 0; i < w.Companies.Count; i++) Array.Copy(values[i], w.Companies[i].BookValues, AssetCategories.Count);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Stato patrimoniale degli attivi non monetari di ogni compagnia, per voce
|
||
/// (<see cref="AssetCategory"/>), calcolato al giorno corrente. Unica fonte del valore contabile.
|
||
/// </summary>
|
||
public static long[][] BookValues(World w)
|
||
{
|
||
var fb = w.Data.Balance.Finance;
|
||
var values = new long[w.Companies.Count][];
|
||
for (int i = 0; i < values.Length; i++) values[i] = new long[AssetCategories.Count];
|
||
const int track = (int)AssetCategory.Track, stations = (int)AssetCategory.Stations, vehicles = (int)AssetCategory.Vehicles,
|
||
industries = (int)AssetCategory.Industries, goods = (int)AssetCategory.Goods;
|
||
double daysPerYear = w.Calendar.DaysPerYear;
|
||
long today = w.Clock.Day;
|
||
foreach (var e in w.Network.Edges)
|
||
{
|
||
if (e.State == Rail.EdgeState.Demolished) continue;
|
||
double age = (today - e.BuiltDay) / daysPerYear;
|
||
values[e.Owner.Value][track] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||
}
|
||
foreach (var s in w.Network.Stations)
|
||
{
|
||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value][stations] += s.BuildCostCents;
|
||
}
|
||
foreach (var d in w.Network.Depots)
|
||
{
|
||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value][stations] += d.BuildCostCents;
|
||
}
|
||
foreach (var v in w.Vehicles)
|
||
{
|
||
if (v.Sold) continue;
|
||
double age = (today - v.BoughtDay) / daysPerYear;
|
||
values[v.Owner.Value][vehicles] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||
}
|
||
foreach (var ind in w.Industries)
|
||
{
|
||
if (ind.Closed || !ind.Owner.IsValid || ind.Owner.Value >= values.Length) continue;
|
||
values[ind.Owner.Value][industries] += IndustryMath.BookValue(w, ind).Cents;
|
||
}
|
||
var prices = w.Market.GlobalPrice;
|
||
foreach (var s in w.Network.Stations)
|
||
{
|
||
if (!s.Owner.IsValid || s.Owner.Value >= values.Length) continue;
|
||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value][goods] += (long)(s.Stock[g] * prices[g]);
|
||
values[s.Owner.Value][goods] += OwnedGoodsValue(s.Waiting, prices);
|
||
}
|
||
foreach (var t in w.Trains)
|
||
{
|
||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value][goods] += OwnedGoodsValue(t.Cargo, prices);
|
||
}
|
||
return values;
|
||
}
|
||
|
||
private static long OwnedGoodsValue(List<Rail.Packet> packets, double[] prices)
|
||
{
|
||
long value = 0;
|
||
foreach (var p in packets)
|
||
{
|
||
if (p.Owned && p.Kind == Rail.PacketKind.Freight) value += (long)(p.Units * prices[p.Good]);
|
||
}
|
||
return value;
|
||
}
|
||
|
||
/// <summary>Rata mensile costante (alla francese) per il residuo e i mesi restanti.</summary>
|
||
public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft)
|
||
{
|
||
if (monthsLeft <= 0) return remaining;
|
||
double r = annualRate / 12;
|
||
if (r <= 0) return Money.FromCentsRounded((double)remaining.Cents / monthsLeft);
|
||
double factor = r / (1 - DMath.Pow(1 + r, -monthsLeft));
|
||
return Money.FromCentsRounded(remaining.Cents * factor);
|
||
}
|
||
|
||
private static void PayLoans(World w, Company c)
|
||
{
|
||
for (int i = c.Loans.Count - 1; i >= 0; i--)
|
||
{
|
||
var loan = c.Loans[i];
|
||
var interest = Money.FromCentsRounded(loan.Remaining.Cents * loan.AnnualRate / 12);
|
||
var payment = MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||
var principal = Money.Min(loan.Remaining, payment - interest);
|
||
if (principal.IsNegative) principal = Money.Zero;
|
||
w.Money.Transfer(Account.Of(c.Id), Account.External, interest, LedgerEntry.Interest);
|
||
w.Money.Transfer(Account.Of(c.Id), Account.External, principal, LedgerEntry.LoanRepaid);
|
||
loan.Remaining -= principal;
|
||
loan.MonthsLeft--;
|
||
if (loan.Remaining.Cents <= 0 || loan.MonthsLeft <= 0)
|
||
{
|
||
if (loan.Remaining.IsPositive)
|
||
w.Money.Transfer(Account.Of(c.Id), Account.External, loan.Remaining, LedgerEntry.LoanRepaid);
|
||
c.Loans.RemoveAt(i);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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).
|
||
/// Il margine è neutro (0) finché la finestra non è piena e ha meno di finance.ratingMinRevenueMonths
|
||
/// mesi con ricavi: i primi incassi, piccoli rispetto ai costi dei mesi d'avvio, non fanno crollare il
|
||
/// rating per poi farlo risalire il mese dopo. Con la finestra piena (o con abbastanza mesi di ricavi)
|
||
/// conta il margine vero; senza ricavi e in perdita è il minimo (−100 %, componente nulla).
|
||
/// </summary>
|
||
public static RatingMeasures Measures(World w, Company c)
|
||
{
|
||
var fb = w.Data.Balance.Finance;
|
||
long revenue = 0, profit = 0;
|
||
int revenueMonths = 0;
|
||
foreach (var m in c.IncomeMonths)
|
||
{
|
||
long r = Company.Revenue(m.Entries);
|
||
revenue += r;
|
||
profit += Company.OperatingProfit(m.Entries);
|
||
if (r > 0) revenueMonths++;
|
||
}
|
||
bool neutral = revenueMonths < fb.RatingMinRevenueMonths && c.IncomeMonths.Count < fb.IncomeMonths;
|
||
double margin = neutral ? 0 : revenue > 0 ? (double)profit / revenue : profit < 0 ? -1 : 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, revenueMonths, neutral, 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 m = Measures(w, 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(w, 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 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 e quanti con ricavi, margine neutro (avvio), 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, int RevenueMonths, bool MarginNeutral, long Revenue, long Profit, double Margin,
|
||
long Debt, long Equity, double Leverage);
|