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>
655 lines
37 KiB
C#
655 lines
37 KiB
C#
using RailEnterprise.Core.Commands;
|
||
using RailEnterprise.Core.Common;
|
||
using RailEnterprise.Core.Data;
|
||
using RailEnterprise.Core.Economy;
|
||
using RailEnterprise.Core.Persistence;
|
||
using RailEnterprise.Core.Rail;
|
||
using RailEnterprise.Core.Simulation;
|
||
using RailEnterprise.Core.Simulation.Systems;
|
||
using RailEnterprise.Server;
|
||
using RailEnterprise.Tests.Harness;
|
||
using RailEnterprise.Tests.Rail;
|
||
|
||
namespace RailEnterprise.Tests.Economy;
|
||
|
||
/// <summary>Finanza completa: prestiti per rating, conto economico per voce, rating spiegato, bancarotta (F6, ADR 0019).</summary>
|
||
public static class FinanceTests
|
||
{
|
||
private static CommandResult Do(World w, GameCommand c)
|
||
{
|
||
w.Enqueue(c with { Issuer = w.Player.Id });
|
||
w.RunTicks(1);
|
||
return w.DrainResults().Last();
|
||
}
|
||
|
||
private static void SetCash(World w, Company c, Money target)
|
||
{
|
||
var delta = target - c.Cash;
|
||
if (delta.IsPositive) w.Money.Transfer(Account.External, Account.Of(c.Id), delta, LedgerEntry.Other);
|
||
else if (delta.IsNegative) w.Money.Transfer(Account.Of(c.Id), Account.External, -delta, LedgerEntry.Other);
|
||
}
|
||
|
||
/// <summary>Valdoria con la rete merci, un treno sulla linea e i giorni di servizio indicati.</summary>
|
||
private static RailFixture ServedValdoria(int days)
|
||
{
|
||
var f = RailFixture.Valdoria();
|
||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
|
||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||
f.W.RunDays(days);
|
||
return f;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ prestiti
|
||
|
||
[Test(Description = "Il tasso di un prestito è base della difficoltà + spread del rating, fissato all'accensione")]
|
||
public static void LoanRateIsBasePlusRatingSpreadAndFixed()
|
||
{
|
||
var w = TestWorlds.NoAi(901);
|
||
var c = w.Player;
|
||
var fb = w.Data.Balance.Finance;
|
||
foreach (var rating in new[] { CreditRating.AAA, CreditRating.BBB, CreditRating.CCC })
|
||
{
|
||
c.Rating = rating;
|
||
var r = Do(w, new TakeLoanCommand(Money.FromLire(10_000)));
|
||
Assert.True(r.Ok, r.Message);
|
||
var loan = c.Loans[^1];
|
||
double expected = w.Difficulty.BaseInterestRate + fb.RatingSpreads[rating.ToString()];
|
||
Assert.Approx(expected, loan.AnnualRate, 1e-12, $"tasso con {rating}");
|
||
Assert.Approx(expected, FinanceSystem.LoanRate(w, c), 1e-12);
|
||
Assert.True(r.Message.Contains(FinanceOutlook.Percent(expected)) && r.Message.Contains("rata mensile"), r.Message);
|
||
}
|
||
// il rating cambia, i tassi dei prestiti già accesi no
|
||
var rates = c.Loans.Select(l => l.AnnualRate).ToList();
|
||
c.Rating = CreditRating.D;
|
||
w.RunDays(w.Calendar.DaysPerMonth + 1);
|
||
Assert.SequenceEqual(rates, c.Loans.Select(l => l.AnnualRate).ToList(), "tassi fissi");
|
||
Assert.True(FinanceSystem.LoanRate(w, w.Player) > rates.Min(), "un nuovo prestito costa secondo il rating nuovo");
|
||
// tassi crescenti al peggiorare del rating
|
||
for (int i = 1; i <= (int)CreditRating.D; i++)
|
||
Assert.True(FinanceSystem.LoanRate(w, (CreditRating)i) >= FinanceSystem.LoanRate(w, (CreditRating)(i - 1)), $"spread di {(CreditRating)i}");
|
||
}
|
||
|
||
[Test(Description = "Il fido è il fido iniziale per il fattore del livello; oltre si rifiuta con un messaggio chiaro e senza effetti")]
|
||
public static void CreditLimitComesFromTheTierFactor()
|
||
{
|
||
var w = TestWorlds.NoAi(902);
|
||
var c = w.Player;
|
||
var tiers = w.Data.Tiers.Tiers;
|
||
Assert.Equal(c.BaseCredit * tiers[0].Unlocks.MaxLoanFactor, FinanceSystem.MaxLoan(w, c));
|
||
Assert.True(Do(w, new TakeLoanCommand(FinanceSystem.MaxLoan(w, c))).Ok, "tutto il fido");
|
||
var (loans, debt, cashBefore) = (c.Loans.Count, c.Debt, c.Cash);
|
||
var refused = Do(w, new TakeLoanCommand(Money.FromLire(1)));
|
||
Assert.Equal(CommandError.CreditLimit, refused.Error);
|
||
Assert.True(refused.Message.StartsWith("Fido insufficiente: disponibili ₤ 0"), refused.Message);
|
||
Assert.Equal(CommandError.InvalidArgument, Do(w, new TakeLoanCommand(Money.Zero)).Error);
|
||
Assert.Equal((loans, debt), (c.Loans.Count, c.Debt), "i rifiuti non cambiano i prestiti");
|
||
Assert.True(c.Cash <= cashBefore, "nessun incasso dai rifiuti");
|
||
|
||
var higher = tiers.First(t => t.Unlocks.MaxLoanFactor > tiers[0].Unlocks.MaxLoanFactor);
|
||
c.Tier = higher.Level;
|
||
Assert.Equal(c.BaseCredit * higher.Unlocks.MaxLoanFactor, FinanceSystem.MaxLoan(w, c));
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(1))).Ok, "il livello alza il fido");
|
||
|
||
// in amministrazione controllata niente prestiti nuovi
|
||
c.Receivership = true;
|
||
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1))).Error);
|
||
Assert.False(FinanceOutlook.Build(w, c.Id).LoansAllowed, "il quadro lo dice");
|
||
}
|
||
|
||
[Test(Description = "Interessi e quota capitale si pagano ogni mese sul registro, alla francese, con il denaro che torna a zero")]
|
||
public static void MonthlyInterestIsBookedOnTheLedger()
|
||
{
|
||
var w = TestWorlds.NoAi(903);
|
||
var c = w.Player;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(120_000))).Ok);
|
||
var loan = c.Loans[0];
|
||
var interest = Money.FromCentsRounded(loan.Remaining.Cents * loan.AnnualRate / 12);
|
||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||
var remaining = loan.Remaining;
|
||
long interestBefore = c.MonthEntries[(int)LedgerEntry.Interest], repaidBefore = c.MonthEntries[(int)LedgerEntry.LoanRepaid];
|
||
// la rata si paga il primo giorno del mese e finisce nel mese che si chiude
|
||
w.RunDays(w.Calendar.DaysPerMonth - (int)(w.Clock.Day % w.Calendar.DaysPerMonth));
|
||
var closed = c.IncomeMonths[^1].Entries;
|
||
Assert.Equal(-interest.Cents, closed[(int)LedgerEntry.Interest] - interestBefore, "interessi del mese");
|
||
Assert.Equal(-(payment - interest).Cents, closed[(int)LedgerEntry.LoanRepaid] - repaidBefore, "quota capitale");
|
||
Assert.Equal(remaining - (payment - interest), loan.Remaining);
|
||
Assert.Equal(c.Loans[0].MonthsLeft, w.Data.Balance.Finance.LoanTermMonths - 1);
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
// il quadro mostra rata e scadenza coerenti
|
||
var detail = FinanceOutlook.Build(w, c.Id).LoanList[0];
|
||
Assert.Equal(FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft), detail.Payment);
|
||
Assert.Equal(w.Clock.Day / w.Calendar.DaysPerMonth * w.Calendar.DaysPerMonth + (long)loan.MonthsLeft * w.Calendar.DaysPerMonth, detail.MaturityDay);
|
||
}
|
||
|
||
[Test(Description = "Rimborso anticipato parziale (rata più bassa, stessa durata) e totale; cassa insufficiente e prestito inesistente rifiutati")]
|
||
public static void EarlyRepaymentPartialAndTotal()
|
||
{
|
||
var w = TestWorlds.NoAi(904);
|
||
var c = w.Player;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(100_000))).Ok);
|
||
var loan = c.Loans[0];
|
||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||
int months = loan.MonthsLeft;
|
||
|
||
var partial = Do(w, new RepayLoanCommand(loan.Id, Money.FromLire(40_000)));
|
||
Assert.True(partial.Ok, partial.Message);
|
||
Assert.Equal(Money.FromLire(60_000), loan.Remaining);
|
||
Assert.Equal(months, loan.MonthsLeft, "la durata non cambia");
|
||
var lower = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||
Assert.True(lower < payment, "la rata scende");
|
||
Assert.True(partial.Message.Contains($"nuova rata mensile {lower}"), partial.Message);
|
||
|
||
// cassa insufficiente: rifiuto con gli importi, nulla cambia
|
||
var cash = c.Cash;
|
||
SetCash(w, c, Money.FromLire(1_000));
|
||
var owed = loan.Remaining;
|
||
var poor = Do(w, new RepayLoanCommand(loan.Id, loan.Remaining));
|
||
Assert.Equal(CommandError.InsufficientFunds, poor.Error);
|
||
Assert.True(poor.Message.Contains("Cassa insufficiente") && poor.Message.Contains(loan.Remaining.ToString()), poor.Message);
|
||
Assert.Equal(owed, loan.Remaining, "il rifiuto non rimborsa nulla");
|
||
SetCash(w, c, cash);
|
||
|
||
Assert.Equal(CommandError.NotFound, Do(w, new RepayLoanCommand(new LoanId(999), Money.FromLire(1))).Error);
|
||
var total = Do(w, new RepayLoanCommand(loan.Id, Money.FromLire(1_000_000)));
|
||
Assert.True(total.Ok && total.Message.Contains("prestito estinto"), total.Message);
|
||
Assert.Equal(0, c.Loans.Count);
|
||
Assert.Equal(Money.Zero, c.Debt);
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
}
|
||
|
||
// ------------------------------------------------------------------ rating
|
||
|
||
/// <summary>Mese chiuso con i ricavi e i costi indicati (centesimi), per costruire la finestra del rating.</summary>
|
||
private static IncomeRecord Month(int year, int month, long revenue, long cost)
|
||
{
|
||
var e = new long[Company.EntryCount];
|
||
e[(int)LedgerEntry.FreightRevenue] = revenue;
|
||
e[(int)LedgerEntry.RunningCosts] = -cost;
|
||
return new IncomeRecord { Year = year, Month = month, Entries = e };
|
||
}
|
||
|
||
[Test(Description = "Il rating è funzione documentata di utile/ricavi (12 mesi) e debiti/patrimonio; le misure restano per spiegarlo")]
|
||
public static void RatingComesFromMarginAndLeverage()
|
||
{
|
||
var w = TestWorlds.NoAi(905);
|
||
var c = w.Player;
|
||
var fb = w.Data.Balance.Finance;
|
||
c.IncomeMonths.Clear();
|
||
for (int m = 1; m <= 12; m++) c.IncomeMonths.Add(Month(1850, m, 100_000_00, 80_000_00)); // margine 20 %
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.Approx(0.2, c.RatingMargin, 1e-12, "margine");
|
||
Assert.Equal(12, c.RatingMonths);
|
||
long debt = c.Debt.Cents + Math.Max(0, -c.Cash.Cents);
|
||
Assert.Approx(debt == 0 ? 0 : (double)debt / c.NetWorth.Cents, c.RatingLeverage, 1e-12, "leva");
|
||
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + 0.2, 0, 1) + fb.LeverageWeight * (1 / (1 + c.RatingLeverage));
|
||
Assert.Approx(score, c.RatingScore, 1e-12, "punteggio");
|
||
Assert.Equal(FinanceSystem.RatingOf(w, score), c.Rating);
|
||
var noDebt = c.Rating;
|
||
|
||
// più debito (stesso patrimonio): leva più alta, rating non migliore
|
||
Assert.True(Do(w, new TakeLoanCommand(FinanceSystem.MaxLoan(w, c))).Ok);
|
||
FinanceSystem.UpdateBookValues(w);
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.Approx((double)c.Debt.Cents / c.NetWorth.Cents, c.RatingLeverage, 1e-12, "debiti/patrimonio");
|
||
Assert.True(c.Rating >= noDebt, $"con debito {c.Rating}, senza {noDebt}");
|
||
|
||
// margine negativo: rating non migliore; margine alto: non peggiore
|
||
var leveraged = c.Rating;
|
||
for (int i = 0; i < 12; i++) c.IncomeMonths[i] = Month(1850, i + 1, 100_000_00, 150_000_00);
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.Approx(-0.5, c.RatingMargin, 1e-12);
|
||
Assert.True(c.Rating >= leveraged, "in perdita il rating non sale");
|
||
for (int i = 0; i < 12; i++) c.IncomeMonths[i] = Month(1850, i + 1, 100_000_00, 10_000_00);
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.True(c.Rating <= leveraged, "con il 90 % di margine il rating non scende");
|
||
|
||
// patrimonio negativo con debiti: leva infinita, componente nulla
|
||
SetCash(w, c, Money.FromLire(-10_000_000));
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.True(double.IsPositiveInfinity(c.RatingLeverage), "leva infinita");
|
||
Assert.Approx(fb.ProfitMarginWeight * 1.0, c.RatingScore, 1e-12);
|
||
c.Bankrupt = true;
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.Equal(CreditRating.D, c.Rating, "in bancarotta è D");
|
||
}
|
||
|
||
[Test(Description = "La spiegazione del rating dice cosa serve per salire: il margine o la leva indicati portano al gradino sopra")]
|
||
public static void RatingExplanationReachesTheNextNotch()
|
||
{
|
||
var w = TestWorlds.NoAi(906);
|
||
var c = w.Player;
|
||
var fb = w.Data.Balance.Finance;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(200_000))).Ok);
|
||
c.IncomeMonths.Clear();
|
||
for (int m = 1; m <= 12; m++) c.IncomeMonths.Add(Month(1850, m, 100_000_00, 95_000_00)); // margine 5 %
|
||
FinanceSystem.UpdateBookValues(w);
|
||
FinanceSystem.UpdateRating(w, c);
|
||
var e = FinanceOutlook.Explain(w, c);
|
||
Assert.False(e.Initial, "misure dell'ultimo calcolo");
|
||
Assert.Equal(c.Rating, e.Rating);
|
||
Assert.Approx(c.RatingScore, e.Score, 1e-12);
|
||
Assert.Equal(fb.RatingByScore.Length, e.Thresholds.Count);
|
||
Assert.True(e.Next is not null, "c'è un gradino sopra");
|
||
Assert.Approx(fb.RatingByScore[(int)e.Next!.Value], e.NextThreshold, 1e-12);
|
||
Assert.True(e.Score < e.NextThreshold && e.Score >= (c.Rating == CreditRating.D ? 0 : fb.RatingByScore[(int)c.Rating]), "punteggio tra le due soglie");
|
||
if (e.MarginReachable)
|
||
Assert.Equal(e.Next.Value, FinanceSystem.RatingOf(w, FinanceSystem.Score(w, e.MarginNeeded + 1e-9, c.RatingLeverage)), "con il margine indicato si sale");
|
||
if (e.LeverageReachable)
|
||
{
|
||
Assert.Equal(e.Next.Value, FinanceSystem.RatingOf(w, FinanceSystem.Score(w, c.RatingMargin, e.LeverageMax - 1e-9)), "con la leva indicata si sale");
|
||
// rimborsando il debito indicato la leva scende sotto il massimo (il patrimonio non cambia)
|
||
var live = FinanceSystem.Measures(w, c);
|
||
Assert.True((double)(live.Debt - e.DebtToRepay.Cents) / live.Equity <= e.LeverageMax + 1e-9, "debito da rimborsare");
|
||
Assert.True(e.RepayAffordable == (e.DebtToRepay <= Money.Min(c.Debt, Money.Max(Money.Zero, c.Cash))), "rimborso possibile con la cassa");
|
||
}
|
||
Assert.True(e.MarginReachable || e.LeverageReachable, "almeno una via per salire");
|
||
Assert.False(e.NextAlreadyMet, "il punteggio non basta ancora");
|
||
|
||
// pochi contanti e molti attivi non monetari: il rimborso che servirebbe supera la cassa, quindi oggi
|
||
// non è percorribile (si rimborsa con la cassa; lo scoperto non si rimborsa)
|
||
SetCash(w, c, Money.FromLire(10_000));
|
||
c.BookValues[(int)AssetCategory.Vehicles] += Money.FromLire(400_000).Cents;
|
||
var poor = FinanceOutlook.Explain(w, c);
|
||
Assert.True(poor.LeverageReachable && poor.DebtToRepay > c.Cash && !poor.RepayAffordable, $"rimborso {poor.DebtToRepay} con cassa {c.Cash}");
|
||
SetCash(w, c, Money.FromLire(-1));
|
||
Assert.False(FinanceOutlook.Explain(w, c).RepayAffordable, "con la cassa negativa nessun rimborso");
|
||
}
|
||
|
||
[Test(Description = "Se il punteggio basta già per il gradino sopra (rating iniziale o rimasto indietro) la spiegazione lo dice senza obiettivi né infiniti")]
|
||
public static void RatingExplanationWhenTheScoreAlreadyMeetsTheNextNotch()
|
||
{
|
||
var fb = TestData.Data.Balance.Finance;
|
||
// partita nuova: rating iniziale dei dati, misure di oggi (margine neutro, nessun debito)
|
||
var fresh = TestWorlds.NoAi(907);
|
||
var first = FinanceOutlook.Explain(fresh, fresh.Player);
|
||
Assert.True(first.Initial);
|
||
Assert.Equal(fb.StartingRating, first.Rating);
|
||
Assert.True(first.MarginNeutral, "nessun mese chiuso: margine neutro");
|
||
Assert.True(first.Score >= first.NextThreshold, $"con i dati attuali il punteggio iniziale {first.Score} supera la soglia {first.NextThreshold}");
|
||
Assert.True(first.NextAlreadyMet, "il punteggio basta già");
|
||
Assert.Equal(FinanceSystem.RatingOf(fresh, first.Score), first.ScoreRating);
|
||
Assert.False(first.MarginReachable || first.LeverageReachable, "nessun obiettivo da raggiungere");
|
||
Assert.Approx(0, first.MarginNeeded, 1e-12);
|
||
Assert.Approx(0, first.LeverageMax, 1e-12);
|
||
var message = Projection.Finance(fresh, fresh.Player.Id);
|
||
Assert.True(message.NextAlreadyMet && message.ScoreRating == first.ScoreRating.ToString(), "nel protocollo");
|
||
|
||
// rating rimasto a D dopo una bancarotta risolta, con un punteggio normale: niente leva infinita
|
||
var w = TestWorlds.NoAi(908);
|
||
var c = w.Player;
|
||
for (int m = 1; m <= 12; m++) c.IncomeMonths.Add(Month(1850, m, 100_000_00, 95_000_00));
|
||
FinanceSystem.UpdateRating(w, c);
|
||
c.Rating = CreditRating.D;
|
||
var e = FinanceOutlook.Explain(w, c);
|
||
Assert.True(e.NextAlreadyMet && e.Next == CreditRating.C, "il punteggio vale già più di C");
|
||
Assert.True(double.IsFinite(e.LeverageMax) && double.IsFinite(e.MarginNeeded), "nessun infinito");
|
||
var wire = Projection.Finance(w, c.Id);
|
||
Assert.True(wire.LeverageMax < 1e6 && wire.MarginNeeded > -0.5 - 1e-6, $"leva {wire.LeverageMax}, margine {wire.MarginNeeded}");
|
||
}
|
||
|
||
[Test(Description = "I primi incassi non fanno crollare il rating: il margine resta neutro finché la finestra non ha abbastanza mesi con ricavi")]
|
||
public static void FirstRevenueDoesNotSinkTheRating()
|
||
{
|
||
var w = TestWorlds.NoAi(909);
|
||
var c = w.Player;
|
||
var fb = w.Data.Balance.Finance;
|
||
Assert.True(fb.RatingMinRevenueMonths > 1 && fb.RatingMinRevenueMonths + 3 < fb.IncomeMonths, "parametri del test");
|
||
// tre mesi d'avvio con soli costi, poi il primo incasso piccolo (margine vero −90 %)
|
||
c.IncomeMonths.Clear();
|
||
for (int m = 1; m <= 3; m++) c.IncomeMonths.Add(Month(1850, m, 0, 50_000_00));
|
||
FinanceSystem.UpdateRating(w, c);
|
||
var start = c.Rating;
|
||
Assert.Approx(0, c.RatingMargin, 1e-12, "solo costi nell'avvio: margine neutro");
|
||
c.IncomeMonths.Add(Month(1850, 4, 10_000_00, 50_000_00));
|
||
FinanceSystem.UpdateRating(w, c);
|
||
var m4 = FinanceSystem.Measures(w, c);
|
||
Assert.True(m4.MarginNeutral && m4.RevenueMonths == 1, "un solo mese con ricavi");
|
||
Assert.Approx(0, c.RatingMargin, 1e-12, "margine ancora neutro");
|
||
Assert.True((int)c.Rating - (int)start <= 1, $"primo incasso: da {start} a {c.Rating}");
|
||
Assert.True(FinanceOutlook.Explain(w, c).MarginNeutral, "la spiegazione lo dice");
|
||
|
||
// con abbastanza mesi di ricavi il margine conta
|
||
for (int m = 5; c.IncomeMonths.Count(x => Company.Revenue(x.Entries) > 0) < fb.RatingMinRevenueMonths; m++)
|
||
c.IncomeMonths.Add(Month(1850, m, 40_000_00, 50_000_00));
|
||
FinanceSystem.UpdateRating(w, c);
|
||
var counted = FinanceSystem.Measures(w, c);
|
||
Assert.False(counted.MarginNeutral, "margine vero");
|
||
Assert.Approx((double)counted.Profit / counted.Revenue, c.RatingMargin, 1e-12);
|
||
Assert.True(c.RatingMargin < 0, "in perdita");
|
||
|
||
// finestra piena senza ricavi e in perdita: margine minimo, componente nulla
|
||
c.IncomeMonths.Clear();
|
||
for (int m = 1; m <= fb.IncomeMonths; m++) c.IncomeMonths.Add(Month(1850, m, 0, 50_000_00));
|
||
FinanceSystem.UpdateRating(w, c);
|
||
Assert.Approx(-1, c.RatingMargin, 1e-12, "margine minimo");
|
||
Assert.Approx(0, FinanceSystem.MarginComponent(c.RatingMargin), 1e-12);
|
||
}
|
||
|
||
[Test(Description = "Il rating si aggiorna ogni mese sulla finestra degli ultimi 12 mesi chiusi")]
|
||
public static void RatingUsesTheLastTwelveClosedMonths()
|
||
{
|
||
var f = ServedValdoria(0);
|
||
var w = f.W;
|
||
var c = w.Player;
|
||
int months = w.Data.Balance.Finance.IncomeMonths;
|
||
w.RunDays((months + 2) * w.Calendar.DaysPerMonth);
|
||
Assert.Equal(months, c.IncomeMonths.Count, "finestra piena e non oltre");
|
||
Assert.Equal(months, c.RatingMonths);
|
||
// i mesi sono consecutivi e finiscono col mese appena chiuso
|
||
var last = w.Calendar.DateOfDay(w.Clock.Day / w.Calendar.DaysPerMonth * w.Calendar.DaysPerMonth - 1);
|
||
Assert.Equal((last.Year, last.Month), (c.IncomeMonths[^1].Year, c.IncomeMonths[^1].Month));
|
||
// le misure conservate sono quelle della finestra (il rating si ricalcola solo a inizio mese)
|
||
long revenue = c.IncomeMonths.Sum(m => Company.Revenue(m.Entries));
|
||
long profit = c.IncomeMonths.Sum(m => Company.OperatingProfit(m.Entries));
|
||
Assert.Approx(revenue > 0 ? (double)profit / revenue : 0, c.RatingMargin, 1e-12);
|
||
Assert.True(revenue > 0, "la linea incassa");
|
||
// l'anello dell'utile della borsa e i mesi del conto economico hanno la stessa fonte
|
||
long ring = c.AnnualProfit;
|
||
Assert.Equal(c.IncomeMonths.Skip(months - 12).Sum(m => Company.OperatingProfit(m.Entries)), ring);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ conto economico
|
||
|
||
[Test(Description = "Il conto economico per voce somma esattamente all'utile operativo del motore in ogni colonna")]
|
||
public static void IncomeStatementSumsToOperatingProfit()
|
||
{
|
||
var f = ServedValdoria(0);
|
||
var w = f.W;
|
||
var c = w.Player;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(50_000))).Ok);
|
||
w.RunDays(w.Calendar.DaysPerYear + 3 * w.Calendar.DaysPerMonth);
|
||
var report = FinanceOutlook.Build(w, c.Id);
|
||
Assert.Equal(Company.EntryCount, report.Lines.Count);
|
||
Assert.Equal(Company.EntryCount, report.Lines.Select(l => l.Entry).Distinct().Count(), "ogni voce una volta");
|
||
Assert.True(report.Columns.Count >= 3, "mese, mesi chiusi, anno");
|
||
Assert.Equal(IncomeColumnKind.CurrentMonth, report.Columns[0].Kind);
|
||
Assert.True(report.Columns.Any(x => x.Kind == IncomeColumnKind.Year), "un anno chiuso");
|
||
foreach (var col in report.Columns)
|
||
{
|
||
long operating = report.Lines.Where(l => l.Section != IncomeSection.Capital).Sum(l => col.Entries[(int)l.Entry]);
|
||
long all = col.Entries.Sum();
|
||
Assert.Equal(col.Profit.Cents, operating, $"utile {col.Kind} {col.Month}/{col.Year}");
|
||
Assert.Equal(Company.OperatingProfit(col.Entries), col.Profit.Cents);
|
||
Assert.Equal(col.CashFlow.Cents, all, "flusso di cassa");
|
||
}
|
||
Assert.Equal(Company.OperatingProfit(c.MonthEntries), report.Columns[0].Profit.Cents, "mese in corso dal registro");
|
||
var year = report.Columns.First(x => x.Kind == IncomeColumnKind.Year);
|
||
Assert.SequenceEqual(c.LastYearEntries, year.Entries, "anno chiuso = registro dell'anno precedente");
|
||
// la scalata mostra lo stesso utile dell'ultimo anno chiuso
|
||
Assert.Equal(ClimbOutlook.Income(w, c).Profit, year.Profit);
|
||
// voci vive: tariffe, esercizio dei treni, stazioni e depositi, interessi
|
||
Assert.True(year.Entries[(int)LedgerEntry.FreightRevenue] > 0, "noli");
|
||
Assert.True(year.Entries[(int)LedgerEntry.RunningCosts] < 0, "esercizio dei treni");
|
||
Assert.True(year.Entries[(int)LedgerEntry.StationUpkeep] < 0, "stazioni e depositi");
|
||
Assert.True(year.Entries[(int)LedgerEntry.Interest] < 0, "interessi");
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
}
|
||
|
||
[Test(Description = "Il personale presente nei depositi riceve gli stipendi alle paghe delle industrie, sulla voce «Stipendi»")]
|
||
public static void DepotStaffIsPaidWages()
|
||
{
|
||
var f = RailFixture.Valdoria();
|
||
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 0);
|
||
var w = f.W;
|
||
var depot = w.Network.Depots[net.Officina];
|
||
w.RunDays(w.Calendar.DaysPerMonth + 1);
|
||
Assert.True(depot.StaffPresent > 0 && depot.WorkersPresent > 0, $"personale presente: {depot.StaffPresent} tecnici, {depot.WorkersPresent} operai");
|
||
long before = w.Player.YearEntries[(int)LedgerEntry.Wages];
|
||
w.RunDays(1);
|
||
var ib = w.Data.Balance.Industry;
|
||
double expected = 0;
|
||
foreach (var d in w.Network.Depots)
|
||
{
|
||
if (d.Owner == w.Player.Id && w.Network.IsAlive(d))
|
||
expected += (d.WorkersPresent * ib.WagePerWorkerPerMonth + d.StaffPresent * ib.WagePerStaffPerMonth) / w.Calendar.DaysPerMonth;
|
||
}
|
||
Assert.Equal(-Money.FromCentsRounded(expected).Cents, w.Player.YearEntries[(int)LedgerEntry.Wages] - before, "stipendi del giorno");
|
||
Assert.True(Company.OperatingProfit(w.Player.YearEntries) < Company.OperatingProfit(w.Player.YearEntries) - w.Player.YearEntries[(int)LedgerEntry.Wages],
|
||
"gli stipendi riducono l'utile operativo");
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
}
|
||
|
||
[Test(Description = "Dazi degli hub e giacenze dei magazzini sulle loro voci, con lo stesso netto per la cassa")]
|
||
public static void DutiesAndStorageHaveTheirOwnEntries()
|
||
{
|
||
var f = RailFixture.Valdoria();
|
||
var w = f.W;
|
||
w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
|
||
int port = f.Ok(new BuildStationCommand(RailFixture.K(14.5, 6.3), 2, "Porto di Levante"));
|
||
var hub = w.Hubs[0];
|
||
int coal = w.Data.Goods.First(g => g.Id == "coal").Index;
|
||
double price = hub.SellPrice(w.Market.GlobalPrice[coal]);
|
||
var cash = w.Player.Cash;
|
||
long trading = w.Player.YearEntries[(int)LedgerEntry.Trading], duties = w.Player.YearEntries[(int)LedgerEntry.Duties];
|
||
var r = f.Do(new BuyGoodsCommand(new StationId(port), "coal", 60, Money.FromCentsRounded(price + 1)));
|
||
Assert.True(r.Ok, r.Message);
|
||
long paid = (cash - w.Player.Cash).Cents;
|
||
long duty = -(w.Player.YearEntries[(int)LedgerEntry.Duties] - duties);
|
||
Assert.Approx(60 * price * hub.Duty / (1 + hub.Duty), duty, 1, "dazio d'importazione");
|
||
Assert.Equal(-(paid - duty), w.Player.YearEntries[(int)LedgerEntry.Trading] - trading, "il resto è commercio");
|
||
|
||
// vendita all'hub: incasso a Pg e dazio a parte, netto = prezzo d'esportazione
|
||
cash = w.Player.Cash;
|
||
duties = w.Player.YearEntries[(int)LedgerEntry.Duties];
|
||
double sell = hub.BuyPrice(w.Market.GlobalPrice[coal]);
|
||
var s = f.Do(new SellGoodsCommand(new StationId(port), "coal", 20, Money.Zero));
|
||
Assert.True(s.Ok, s.Message);
|
||
Assert.Approx(20 * sell, (w.Player.Cash - cash).Cents, 1, "incasso netto");
|
||
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Duties] < duties, "dazio d'esportazione");
|
||
|
||
// giacenza mensile sulla voce «Magazzini»
|
||
long storage = w.Player.YearEntries[(int)LedgerEntry.Storage];
|
||
f.W.RunDays(w.Calendar.DaysPerMonth + 1);
|
||
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Storage] < storage || w.Player.LastYearEntries[(int)LedgerEntry.Storage] < 0, "giacenza addebitata");
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
}
|
||
|
||
// ------------------------------------------------------------------ bancarotta
|
||
|
||
[Test(Slow = true, Description = "Cassa negativa: avviso subito e alle scadenze fisse, bancarotta esattamente ai giorni di difficulty.json per ogni preset")]
|
||
public static void BankruptcyFollowsTheDifficultyDays()
|
||
{
|
||
var fb = TestData.Data.Balance.Finance;
|
||
foreach (var preset in TestData.Data.Difficulty.Presets)
|
||
{
|
||
var w = TestWorlds.NoAi(910, preset.Id);
|
||
var c = w.Player;
|
||
Assert.Equal(preset.BankruptcyDays, w.Difficulty.BankruptcyDays, preset.Id);
|
||
SetCash(w, c, Money.FromLire(-1_000_000));
|
||
w.Events.Drain();
|
||
var warnings = new List<(int Day, GameEvent Event)>();
|
||
int days = 0;
|
||
while (!c.Bankrupt && days < preset.BankruptcyDays + 5)
|
||
{
|
||
w.RunDays(1);
|
||
days++;
|
||
foreach (var e in w.Events.Drain())
|
||
{
|
||
if (e.Kind == EventKind.Finance && e.Company == c.Id) warnings.Add((c.NegativeCashDays, e));
|
||
}
|
||
}
|
||
Assert.True(c.Bankrupt, $"{preset.Id}: bancarotta");
|
||
Assert.Equal(preset.BankruptcyDays, c.NegativeCashDays, $"{preset.Id}: giorni di cassa negativa");
|
||
Assert.Equal(preset.BankruptcyDays, days, $"{preset.Id}: giorni trascorsi");
|
||
int notice = fb.NegativeCashNoticeDays;
|
||
Assert.True(warnings[0].Day == notice && warnings[0].Event.Text.Contains($"bancarotta arriva tra {preset.BankruptcyDays - notice} giorni"),
|
||
$"{preset.Id}: {warnings[0].Event.Text}");
|
||
foreach (int left in fb.BankruptcyWarningDaysLeft.Where(l => l < preset.BankruptcyDays - notice))
|
||
{
|
||
Assert.True(warnings.Any(x => x.Day == preset.BankruptcyDays - left && x.Event.Text.Contains($"bancarotta tra {(left == 1 ? "1 giorno" : $"{left} giorni")}")),
|
||
$"{preset.Id}: avviso a {left} giorni");
|
||
}
|
||
var last = warnings[^1].Event;
|
||
Assert.True(last.Severity == EventSeverity.Critical && last.Text.Contains("dichiarata la bancarotta"), last.Text);
|
||
// l'esito segue la regola della difficoltà (ADR 0012): senza IA che la rilevino la partita finisce
|
||
w.RunDays(1);
|
||
Assert.True(w.GameOver is not null, $"{preset.Id}: fine partita");
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
}
|
||
}
|
||
|
||
[Test(Description = "Se la cassa torna positiva il conto alla rovescia si azzera con un avviso; una cassa che oscilla intorno a zero non genera notizie")]
|
||
public static void PositiveCashResetsTheCountdown()
|
||
{
|
||
var w = TestWorlds.NoAi(911);
|
||
var c = w.Player;
|
||
var cash = c.Cash;
|
||
int notice = w.Data.Balance.Finance.NegativeCashNoticeDays;
|
||
Assert.True(notice > 1 && notice < 5, "parametri del test");
|
||
// oscillazioni più brevi del primo avviso: il contatore riparte, nessuna notizia
|
||
w.Events.Drain();
|
||
for (int i = 0; i < 4; i++)
|
||
{
|
||
SetCash(w, c, Money.FromLire(-50));
|
||
w.RunDays(notice - 1);
|
||
Assert.Equal(notice - 1, c.NegativeCashDays);
|
||
SetCash(w, c, cash);
|
||
w.RunDays(1);
|
||
Assert.Equal(0, c.NegativeCashDays, "il conto alla rovescia si azzera");
|
||
}
|
||
Assert.False(w.Events.Drain().Any(e => e.Company == c.Id && e.Kind == EventKind.Finance), "nessun avviso per le oscillazioni");
|
||
|
||
SetCash(w, c, Money.FromLire(-1_000));
|
||
w.RunDays(5);
|
||
Assert.Equal(5, c.NegativeCashDays);
|
||
var report = FinanceOutlook.Build(w, c.Id);
|
||
Assert.Equal(5, report.NegativeCashDays);
|
||
Assert.Equal(w.Difficulty.BankruptcyDays, report.BankruptcyDays);
|
||
Assert.Equal(Money.FromLire(1_000), report.Overdraft);
|
||
w.Events.Drain();
|
||
SetCash(w, c, cash);
|
||
w.RunDays(1);
|
||
Assert.Equal(0, c.NegativeCashDays);
|
||
Assert.True(w.Events.Drain().Any(e => e.Company == c.Id && e.Kind == EventKind.Finance && e.Text.Contains("torna positiva")), "avviso di rientro");
|
||
}
|
||
|
||
// ------------------------------------------------------------------ salvataggi e determinismo
|
||
|
||
[Test(Description = "Mesi e anni chiusi e misure del rating nel salvataggio (versione 7) e nell'hash; la versione 6 si migra")]
|
||
public static void FinanceStateSurvivesSavesAndMigrates()
|
||
{
|
||
var f = ServedValdoria(0);
|
||
var w = f.W;
|
||
var c = w.Player;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(30_000))).Ok);
|
||
w.RunDays(w.Calendar.DaysPerYear + 2 * w.Calendar.DaysPerMonth);
|
||
Assert.True(c.IncomeMonths.Count > 0 && c.IncomeYears.Count > 0 && c.RatingMonths > 0, "stato da salvare");
|
||
|
||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||
var lc = loaded.Player;
|
||
Assert.Equal(c.IncomeMonths.Count, lc.IncomeMonths.Count);
|
||
for (int i = 0; i < c.IncomeMonths.Count; i++)
|
||
{
|
||
Assert.Equal((c.IncomeMonths[i].Year, c.IncomeMonths[i].Month), (lc.IncomeMonths[i].Year, lc.IncomeMonths[i].Month));
|
||
Assert.SequenceEqual(c.IncomeMonths[i].Entries, lc.IncomeMonths[i].Entries);
|
||
}
|
||
Assert.SequenceEqual(c.IncomeYears[0].Entries, lc.IncomeYears[0].Entries);
|
||
Assert.Equal(c.RatingScore, lc.RatingScore);
|
||
Assert.Equal(c.RatingMargin, lc.RatingMargin);
|
||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
|
||
|
||
// i mesi entrano nell'hash
|
||
ulong hash = StateHasher.Compute(w);
|
||
c.IncomeMonths[0].Entries[(int)LedgerEntry.Wages]--;
|
||
Assert.NotEqual(hash, StateHasher.Compute(w), "un mese chiuso cambia l'hash");
|
||
c.IncomeMonths[0].Entries[(int)LedgerEntry.Wages]++;
|
||
|
||
// stesso futuro dopo il caricamento
|
||
w.RunDays(40);
|
||
loaded.RunDays(40);
|
||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso futuro");
|
||
|
||
// versione 6: nessun mese conservato, l'anno chiuso dal registro, il rating resta
|
||
var v6 = new SaveWriter(1 << 20);
|
||
WorldSerializer.Write(w, v6, 6);
|
||
var migrated = WorldSerializer.Read(TestData.Data, new SaveReader(v6.WrittenSpan.ToArray()));
|
||
var mc = migrated.Player;
|
||
Assert.Equal(0, mc.IncomeMonths.Count);
|
||
Assert.Equal(0, mc.RatingMonths);
|
||
Assert.Equal(c.Rating, mc.Rating);
|
||
Assert.Equal(1, mc.IncomeYears.Count);
|
||
Assert.SequenceEqual(c.LastYearEntries, mc.IncomeYears[0].Entries);
|
||
Assert.True(FinanceOutlook.Explain(migrated, mc).Initial, "spiegazione con le misure di oggi fino al primo calcolo");
|
||
migrated.RunDays(w.Calendar.DaysPerMonth);
|
||
Assert.Equal(1, mc.IncomeMonths.Count);
|
||
Assert.Equal(1, mc.RatingMonths);
|
||
Assert.Equal(0L, migrated.MoneyBalanceSum());
|
||
}
|
||
|
||
[Test(Description = "Stesso seme e stessi comandi finanziari danno lo stesso hash; denaro e merci restano in equilibrio")]
|
||
public static void FinanceIsDeterministicAndKeepsInvariants()
|
||
{
|
||
ulong Run()
|
||
{
|
||
var f = ServedValdoria(0);
|
||
var w = f.W;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(40_000))).Ok);
|
||
w.RunDays(200);
|
||
Assert.True(Do(w, new RepayLoanCommand(w.Player.Loans[0].Id, Money.FromLire(10_000))).Ok);
|
||
w.RunDays(200);
|
||
Assert.Equal(0L, w.MoneyBalanceSum(), "denaro");
|
||
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
|
||
return StateHasher.Compute(w);
|
||
}
|
||
Assert.Equal(Run(), Run());
|
||
}
|
||
|
||
[Test(Description = "Il quadro delle finanze si proietta nel protocollo con le stesse somme del motore")]
|
||
public static void ProjectionMatchesTheEngine()
|
||
{
|
||
var f = ServedValdoria(2 * 30);
|
||
var w = f.W;
|
||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(20_000))).Ok);
|
||
ulong hash = StateHasher.Compute(w);
|
||
var report = FinanceOutlook.Build(w, w.Player.Id);
|
||
var message = Projection.Finance(w, w.Player.Id);
|
||
Assert.Equal(hash, StateHasher.Compute(w), "il quadro non cambia il mondo");
|
||
Assert.Equal(report.Columns.Count, message.Columns.Count);
|
||
for (int i = 0; i < report.Columns.Count; i++)
|
||
{
|
||
Assert.Equal(report.Columns[i].Profit, message.Columns[i].Profit);
|
||
foreach (var line in message.Lines) Assert.Equal(report.Columns[i].Entries[line.Kind], message.Columns[i].Value(line.Kind).Cents);
|
||
}
|
||
Assert.Equal(w.Player.Rating.ToString(), message.Rating);
|
||
Assert.Equal(1, message.LoanList.Count);
|
||
Assert.Equal(report.LoanList[0].Payment, message.LoanList[0].Payment);
|
||
Assert.Equal(w.Difficulty.BankruptcyDays, message.BankruptcyDays);
|
||
}
|
||
|
||
[Test(Description = "I dividendi tra compagnie escono come dividendi pagati (fuori dall'utile) ed entrano come dividendi incassati (nell'utile)")]
|
||
public static void DividendsReceivedCountInOperatingProfit()
|
||
{
|
||
var w = TestWorlds.Small(912);
|
||
var payer = w.Companies.First(c => !c.Id.Equals(w.Player.Id));
|
||
var me = w.Player;
|
||
long profitBefore = Company.OperatingProfit(me.YearEntries), payerProfit = Company.OperatingProfit(payer.YearEntries);
|
||
var amount = Money.FromLire(2_500);
|
||
w.Money.Transfer(Account.Of(payer.Id), Account.Of(me.Id), amount, LedgerEntry.Dividends, LedgerEntry.DividendsReceived);
|
||
Assert.Equal(amount.Cents, me.YearEntries[(int)LedgerEntry.DividendsReceived], "incassati");
|
||
Assert.Equal(-amount.Cents, payer.YearEntries[(int)LedgerEntry.Dividends], "pagati");
|
||
Assert.Equal(profitBefore + amount.Cents, Company.OperatingProfit(me.YearEntries), "nell'utile di chi incassa");
|
||
Assert.Equal(payerProfit, Company.OperatingProfit(payer.YearEntries), "fuori dall'utile di chi paga");
|
||
Assert.Equal(IncomeSection.Revenue, LedgerEntries.Section(LedgerEntry.DividendsReceived));
|
||
Assert.Equal(IncomeSection.Capital, LedgerEntries.Section(LedgerEntry.Dividends));
|
||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||
}
|
||
|
||
[Test(Description = "La quota dei trasporti dei nuovi concorrenti conta solo tariffe, noli e contratti, non dividendi né commercio")]
|
||
public static void TransportShareIgnoresDividendsAndTrading()
|
||
{
|
||
var e = new long[Company.EntryCount];
|
||
e[(int)LedgerEntry.FreightRevenue] = 1_000;
|
||
e[(int)LedgerEntry.PassengerRevenue] = 500;
|
||
e[(int)LedgerEntry.Contracts] = 200;
|
||
long transport = Company.TransportRevenue(e);
|
||
Assert.Equal(1_700L, transport);
|
||
e[(int)LedgerEntry.DividendsReceived] = 1_000_000;
|
||
e[(int)LedgerEntry.Trading] = 50_000;
|
||
e[(int)LedgerEntry.Subsidiaries] = 7_000;
|
||
Assert.Equal(transport, Company.TransportRevenue(e), "dividendi, commercio e controllate fuori dalla quota");
|
||
Assert.True(Company.Revenue(e) > transport, "restano nei ricavi del rating");
|
||
}
|
||
}
|