La revisione ha trovato casi in cui la merce della compagnia, già pagata, poteva perdersi o restare bloccata, e il magazzino di destinazione restare prenotato per sempre. Le correzioni: - Il percorso della merce propria rispetta i flag carico e scarico delle fermate: LineGraph.From ha l'opzione stopFlags. ShipGoods rifiuta con Blocked la spedizione che esiste solo ignorando i flag. I pacchetti dei clienti non cambiano: l'accettazione F4 dà ancora 35/20 e 75/2. - La scadenza in stazione della merce propria riparte a ogni trasbordo. - La merce propria in attesa ricalcola ogni giorno il tratto sulle linee di quel giorno; se non c'è più un percorso torna nel magazzino. - La merce propria a bordo scende alla prima fermata quando il suo tratto non è più sulla linea del treno. Un treno che lascia la linea (riassegnato, al deposito, in riserva, fine copertura) la lascia alla stazione dove si trova o alla prossima fermata. - Una stazione con merce propria in partenza o in arrivo non si demolisce. - La merce propria, in magazzino e in viaggio, entra nel valore contabile al prezzo globale: un acquisto non abbassa più il patrimonio netto dell'intero importo. - Solo l'acquisto richiede lo sblocco del livello: la merce ereditata con una fusione si vende e si spedisce, e il riquadro del pannello compare. - Nel riquadro, la stazione di arrivo predefinita è diversa da quella di partenza. ADR 0016 e STATE aggiornati; sei test nuovi in TradingTests. Refs #31. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
618 lines
34 KiB
C#
618 lines
34 KiB
C#
using RailEnterprise.Core.Commands;
|
|
using RailEnterprise.Core.Common;
|
|
using RailEnterprise.Core.Economy;
|
|
using RailEnterprise.Core.Persistence;
|
|
using RailEnterprise.Core.Rail;
|
|
using RailEnterprise.Core.Simulation;
|
|
using RailEnterprise.Core.Simulation.Systems;
|
|
using RailEnterprise.Protocol;
|
|
using RailEnterprise.Protocol.Messages;
|
|
using RailEnterprise.Tests.Harness;
|
|
using RailEnterprise.Tests.Rail;
|
|
using static RailEnterprise.Tests.Rail.RailFixture;
|
|
|
|
namespace RailEnterprise.Tests.Economy;
|
|
|
|
/// <summary>Compravendita in proprio e spedizione della merce tra stazioni (F6, issue #31, ADR 0016).</summary>
|
|
public static class TradingTests
|
|
{
|
|
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
|
|
|
private static void AssertInvariants(World w, string when)
|
|
{
|
|
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}");
|
|
for (int g = 0; g < w.Data.GoodCount; g++)
|
|
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}");
|
|
}
|
|
|
|
/// <summary>Merce creata dal test nel magazzino di una stazione, contabilizzata come prodotta (ADR 0004 §4).</summary>
|
|
private static void Inject(World w, Station s, int good, int units)
|
|
{
|
|
TradingMath.AddToWarehouse(s, good, units, w.Data.GoodCount);
|
|
w.Goods.Produced[good] += units;
|
|
}
|
|
|
|
private static void Unlock(World w) => w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
|
|
|
|
/// <summary>Valdoria con le stazioni delle miniere, dell'acciaieria e del porto, senza binari.</summary>
|
|
private static (RailFixture F, Station Mine, Station Mill, Station Port) Stations()
|
|
{
|
|
var f = Valdoria();
|
|
int mine = f.Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
|
|
int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
|
|
int port = f.Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
|
var net = f.W.Network;
|
|
return (f, net.Stations[mine], net.Stations[mill], net.Stations[port]);
|
|
}
|
|
|
|
[Test(Description = "Compra dal produttore del bacino al prezzo locale marginale: prezzo, cassa, registro e giacenze esatti")]
|
|
public static void BuyFromProducerAtTheLocalPrice()
|
|
{
|
|
var (f, mine, _, _) = Stations();
|
|
var w = f.W;
|
|
Unlock(w);
|
|
int ore = GoodIndex(w, "iron_ore");
|
|
var producer = w.Industries.First(i => i.Def.Id == "iron_mine");
|
|
Assert.True(mine.Industries.Contains(producer.Id), "la miniera è nel bacino");
|
|
int cap = IndustryMath.OutputCapacity(producer, 0, w.Calendar.DaysPerMonth);
|
|
int start = cap / 2;
|
|
Assert.True(start > 60, $"capienza del minerale della miniera: {cap}");
|
|
w.Goods.Produced[ore] += start - producer.OutputStock[0];
|
|
producer.OutputStock[0] = start;
|
|
|
|
// prezzo atteso: ogni unità al prezzo locale con la giacenza che resta (Dl = spazio libero, Sl = giacenza)
|
|
const int units = 40;
|
|
double pg = w.Market.GlobalPrice[ore];
|
|
var lp = w.Data.Balance.LocalPrice;
|
|
double expected = 0;
|
|
for (int k = 0; k < units; k++) expected += Market.LocalPrice(pg, cap - (start - k), start - k, lp);
|
|
Assert.Approx(pg, Market.LocalPrice(pg, cap - start, start, lp), pg * 0.02, "a metà magazzino il prezzo è quello globale");
|
|
var cost = Money.FromCentsRounded(expected);
|
|
var cash = w.Player.Cash;
|
|
var industryCash = producer.Cash;
|
|
long trading = w.Player.MonthEntries[(int)LedgerEntry.Trading];
|
|
|
|
var r = f.Do(new BuyGoodsCommand(mine.Id, "iron_ore", units, Money.FromLire(1000)));
|
|
Assert.True(r.Ok, r.Message);
|
|
Assert.True(r.Message.Contains("Comprate 40 t", StringComparison.Ordinal), r.Message);
|
|
Assert.Equal(units, mine.StockOf(ore));
|
|
Assert.Equal(cash - cost, w.Player.Cash);
|
|
Assert.Equal(industryCash + cost, producer.Cash);
|
|
Assert.Equal(trading - cost.Cents, w.Player.MonthEntries[(int)LedgerEntry.Trading]);
|
|
Assert.True(producer.LastServedDay >= w.Clock.Day - 1, "la miniera è servita");
|
|
AssertInvariants(w, "dopo l'acquisto");
|
|
|
|
// il prezzo sale man mano che il produttore si svuota: con un tetto sotto il prossimo prezzo si compra meno
|
|
double next = Market.LocalPrice(pg, cap - (producer.OutputStock[0]), producer.OutputStock[0], lp);
|
|
var capped = f.Do(new BuyGoodsCommand(mine.Id, "iron_ore", 1000, Money.FromCentsRounded(next + 30)));
|
|
Assert.True(capped.Ok, capped.Message);
|
|
Assert.True(mine.StockOf(ore) > units && mine.StockOf(ore) < units + start - units, $"comprate {mine.StockOf(ore) - units} unità sotto il tetto");
|
|
Assert.True(capped.Message.Contains("tetto", StringComparison.Ordinal), capped.Message);
|
|
AssertInvariants(w, "dopo l'acquisto con il tetto");
|
|
}
|
|
|
|
[Test(Description = "Compra dall'hub del bacino al prezzo d'importazione: conta come importato e usa la capacità dell'hub")]
|
|
public static void BuyFromHubCountsAsImported()
|
|
{
|
|
var (f, _, _, port) = Stations();
|
|
var w = f.W;
|
|
Unlock(w);
|
|
int coal = GoodIndex(w, "coal");
|
|
var hub = w.Hubs[0];
|
|
Assert.True(port.Hubs.Contains(hub.Id), "il porto è nel bacino");
|
|
int imported = (int)w.Goods.Imported[coal];
|
|
int used = hub.UsedThisMonth;
|
|
double price = hub.SellPrice(w.Market.GlobalPrice[coal]);
|
|
var cash = w.Player.Cash;
|
|
var external = w.Money.External;
|
|
|
|
var r = f.Do(new BuyGoodsCommand(port.Id, "coal", 60, Money.FromCentsRounded(price + 1)));
|
|
Assert.True(r.Ok, r.Message);
|
|
Assert.Equal(60, port.StockOf(coal));
|
|
Assert.Equal(imported + 60L, w.Goods.Imported[coal]);
|
|
Assert.Equal(used + 60, hub.UsedThisMonth);
|
|
Assert.Approx(60 * price, (cash - w.Player.Cash).Cents, 1);
|
|
Assert.Equal(external + (cash - w.Player.Cash), w.Money.External);
|
|
AssertInvariants(w, "dopo l'importazione");
|
|
|
|
// il tetto sotto il prezzo dell'hub rifiuta senza cambiare nulla
|
|
var refused = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromCentsRounded(price - 100)));
|
|
Assert.Equal(CommandError.InvalidArgument, refused.Error);
|
|
Assert.Equal(60, port.StockOf(coal));
|
|
}
|
|
|
|
[Test(Description = "Vende al consumatore del bacino al prezzo locale (decrescente), entro spazio e cassa dell'industria")]
|
|
public static void SellToConsumerWithinSpaceAndCash()
|
|
{
|
|
var (f, _, mill, _) = Stations();
|
|
var w = f.W;
|
|
Unlock(w);
|
|
int ore = GoodIndex(w, "iron_ore");
|
|
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
|
int input = steel.InputIndexOf(ore);
|
|
int desired = IndustryMath.InputCapacity(steel, input, w.Calendar.DaysPerMonth);
|
|
Assert.True(mill.Industries.Contains(steel.Id) && desired > 10, $"acciaieria nel bacino, capienza {desired}");
|
|
w.Goods.Consumed[ore] += steel.InputStock[input];
|
|
steel.InputStock[input] = 0;
|
|
Inject(w, mill, ore, desired + 50);
|
|
// cassa dell'acciaieria abbondante
|
|
w.Money.Transfer(Account.External, Account.Of(steel.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
|
|
|
|
double pg = w.Market.GlobalPrice[ore];
|
|
var lp = w.Data.Balance.LocalPrice;
|
|
int units = desired / 2;
|
|
double expected = 0;
|
|
for (int k = 0; k < units; k++) expected += Market.LocalPrice(pg, desired, k, lp);
|
|
Assert.True(Market.LocalPrice(pg, desired, 0, lp) > pg * 1.3, "a magazzino vuoto il consumatore paga di più");
|
|
var cash = w.Player.Cash;
|
|
var r = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", units, Money.FromLire(1)));
|
|
Assert.True(r.Ok, r.Message);
|
|
Assert.Equal(units, steel.InputStock[input]);
|
|
Assert.Equal(desired + 50 - units, mill.StockOf(ore));
|
|
Assert.Equal(cash + Money.FromCentsRounded(expected), w.Player.Cash);
|
|
AssertInvariants(w, "dopo la vendita");
|
|
|
|
// il prezzo minimo sopra quello offerto rifiuta
|
|
var refused = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 5, Money.FromLire(10_000)));
|
|
Assert.Equal(CommandError.InvalidArgument, refused.Error);
|
|
|
|
// un'industria con poca cassa compra solo quanto può pagare
|
|
w.Money.Transfer(Account.Of(steel.Id), Account.External, steel.Cash, LedgerEntry.Other);
|
|
double one = Market.LocalPrice(pg, desired, steel.InputStock[input], lp);
|
|
w.Money.Transfer(Account.External, Account.Of(steel.Id), Money.FromCentsRounded(one * 3.5), LedgerEntry.Other);
|
|
var poor = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 20, Money.FromLire(1)));
|
|
Assert.True(poor.Ok, poor.Message);
|
|
Assert.Equal(units + 3, steel.InputStock[input]);
|
|
Assert.True(steel.Cash.Cents >= 0, "l'industria non va in rosso");
|
|
AssertInvariants(w, "dopo la vendita a credito limitato");
|
|
|
|
// senza cassa nessuna vendita
|
|
w.Money.Transfer(Account.Of(steel.Id), Account.External, steel.Cash, LedgerEntry.Other);
|
|
Assert.Equal(CommandError.InsufficientFunds, f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 5, Money.FromLire(1))).Error);
|
|
}
|
|
|
|
[Test(Description = "Vende all'hub del bacino al prezzo d'esportazione: conta come esportato")]
|
|
public static void SellToHubCountsAsExported()
|
|
{
|
|
var (f, _, _, port) = Stations();
|
|
var w = f.W;
|
|
Unlock(w);
|
|
int coal = GoodIndex(w, "coal");
|
|
var hub = w.Hubs[0];
|
|
Inject(w, port, coal, 40);
|
|
long exported = w.Goods.Exported[coal];
|
|
double price = hub.BuyPrice(w.Market.GlobalPrice[coal]);
|
|
var cash = w.Player.Cash;
|
|
var r = f.Do(new SellGoodsCommand(port.Id, "coal", 100, Money.FromCentsRounded(price - 1)));
|
|
Assert.True(r.Ok, r.Message);
|
|
Assert.Equal(0, port.StockOf(coal));
|
|
Assert.Equal(exported + 40, w.Goods.Exported[coal]);
|
|
Assert.Approx(40 * price, (w.Player.Cash - cash).Cents, 1);
|
|
AssertInvariants(w, "dopo l'esportazione");
|
|
Assert.Equal(CommandError.NotFound, f.Do(new SellGoodsCommand(port.Id, "coal", 1, Money.Zero)).Error);
|
|
}
|
|
|
|
[Test(Description = "Rifiuti: livello, stazione altrui o demolita, merce sconosciuta o dell'era futura, prezzo, cassa, magazzino pieno")]
|
|
public static void InvalidTradesAreRefusedWithoutEffects()
|
|
{
|
|
var (f, mine, mill, port) = Stations();
|
|
var w = f.W;
|
|
int coal = GoodIndex(w, "coal");
|
|
Assert.Equal(1, w.Player.Tier);
|
|
var locked = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)));
|
|
Assert.Equal(CommandError.TierLocked, locked.Error);
|
|
Assert.True(locked.Message.Contains("Compagnia regionale", StringComparison.Ordinal), locked.Message);
|
|
// senza lo sblocco la merce già in magazzino (per esempio ereditata da una fusione) si vende e si spedisce
|
|
Assert.Equal(CommandError.NotFound, f.Do(new ShipGoodsCommand(port.Id, mill.Id, "coal", 1)).Error, "magazzino vuoto, non livello");
|
|
Inject(w, port, coal, 5);
|
|
var inherited = f.Do(new SellGoodsCommand(port.Id, "coal", 5, Money.FromLire(1)));
|
|
Assert.True(inherited.Ok, inherited.Message);
|
|
Assert.Equal(0, port.StockOf(coal));
|
|
Unlock(w);
|
|
|
|
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(port.Id, "unobtainium", 10, Money.FromLire(1000))).Error);
|
|
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(new StationId(999), "coal", 10, Money.FromLire(1000))).Error);
|
|
Assert.Equal(CommandError.InvalidArgument, f.Do(new BuyGoodsCommand(port.Id, "coal", 0, Money.FromLire(1000))).Error);
|
|
var future = w.Data.Goods.First(g => g.Era > w.Clock.Year);
|
|
Assert.Equal(CommandError.EraLocked, f.Do(new BuyGoodsCommand(port.Id, future.Id, 10, Money.FromLire(1000))).Error);
|
|
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(mill.Id, "goods", 10, Money.FromLire(1000))).Error, "nessun venditore");
|
|
|
|
// stazione di un'altra compagnia
|
|
var owner = port.Owner;
|
|
port.Owner = new CompanyId(owner.Value + 1);
|
|
var foreign = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)));
|
|
Assert.Equal(CommandError.NotAllowed, foreign.Error);
|
|
port.Owner = owner;
|
|
|
|
// cassa insufficiente
|
|
var cash = w.Player.Cash;
|
|
w.Money.Transfer(Account.Of(f.Me), Account.External, cash, LedgerEntry.Other);
|
|
Assert.Equal(CommandError.InsufficientFunds, f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000))).Error);
|
|
w.Money.Transfer(Account.External, Account.Of(f.Me), cash, LedgerEntry.Other);
|
|
|
|
// magazzino pieno
|
|
int capacity = w.Data.Balance.Trading.WarehouseCapacity;
|
|
Inject(w, port, coal, capacity);
|
|
var full = f.Do(new BuyGoodsCommand(port.Id, "coal", 1, Money.FromLire(1000)));
|
|
Assert.Equal(CommandError.Blocked, full.Error);
|
|
Assert.Equal(capacity, port.StockOf(coal));
|
|
Assert.Equal(CommandError.NotFound, f.Do(new ShipGoodsCommand(port.Id, mine.Id, "coal", 10)).Error, "nessun percorso");
|
|
Assert.Equal(CommandError.InvalidArgument, f.Do(new ShipGoodsCommand(port.Id, port.Id, "coal", 10)).Error);
|
|
Assert.Equal(CommandError.NotFound, f.Do(new SellGoodsCommand(mine.Id, "coal", 10, Money.Zero)).Error, "magazzino vuoto");
|
|
|
|
// una stazione con merce in magazzino non si demolisce
|
|
var demolish = f.Do(new DemolishCommand(DemolishTarget.Station, port.Id.Value));
|
|
Assert.Equal(CommandError.NotAllowed, demolish.Error);
|
|
Assert.True(w.Network.IsAlive(port));
|
|
AssertInvariants(w, "dopo i rifiuti");
|
|
}
|
|
|
|
[Test(Description = "Una stazione con merce della compagnia in attesa di partire o in arrivo non si demolisce")]
|
|
public static void StationsWithOwnedGoodsInTransitAreNotDemolished()
|
|
{
|
|
var (f, mine, _, port) = Stations();
|
|
var w = f.W;
|
|
int coal = GoodIndex(w, "coal");
|
|
port.Waiting.Add(new Packet
|
|
{
|
|
Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = coal, Units = 30, Origin = port.Id, Destination = mine.Id,
|
|
HopLine = LineId.None, HopEnd = mine.Id, CreatedTick = w.Context.Tick, ExpiresTick = w.Context.Tick + w.Calendar.TicksPerDay * 30,
|
|
Contract = -1, Owned = true,
|
|
});
|
|
w.Goods.Produced[coal] += 30;
|
|
var leaving = f.Do(new DemolishCommand(DemolishTarget.Station, port.Id.Value));
|
|
Assert.Equal(CommandError.NotAllowed, leaving.Error, leaving.Message);
|
|
var arriving = f.Do(new DemolishCommand(DemolishTarget.Station, mine.Id.Value));
|
|
Assert.Equal(CommandError.NotAllowed, arriving.Error, arriving.Message);
|
|
Assert.True(w.Network.IsAlive(port) && w.Network.IsAlive(mine));
|
|
Assert.Equal(30, port.Waiting.Single(p => p.Owned).Units);
|
|
|
|
// senza linee il giorno dopo la merce torna nel magazzino della stazione, che resta da svuotare
|
|
w.RunDays(1);
|
|
Assert.False(port.Waiting.Any(p => p.Owned), "nessun pacchetto proprio in attesa");
|
|
Assert.Equal(30, port.StockOf(coal));
|
|
Assert.Equal(0, TradingMath.ReservedByStation(w)[mine.Id.Value]);
|
|
AssertInvariants(w, "dopo il rientro in magazzino");
|
|
}
|
|
|
|
[Test(Description = "La merce in magazzino e in viaggio entra nel valore contabile al prezzo globale")]
|
|
public static void OwnedGoodsCountInTheBookValue()
|
|
{
|
|
var (f, mine, _, port) = Stations();
|
|
var w = f.W;
|
|
int coal = GoodIndex(w, "coal");
|
|
int ore = GoodIndex(w, "iron_ore");
|
|
FinanceSystem.UpdateBookValues(w);
|
|
var before = w.Player.AssetBookValue;
|
|
Inject(w, port, coal, 100);
|
|
mine.Waiting.Add(new Packet
|
|
{
|
|
Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = ore, Units = 40, Origin = mine.Id, Destination = port.Id,
|
|
HopLine = LineId.None, HopEnd = port.Id, CreatedTick = 0, ExpiresTick = long.MaxValue, Contract = -1, Owned = true,
|
|
});
|
|
w.Goods.Produced[ore] += 40;
|
|
FinanceSystem.UpdateBookValues(w);
|
|
long expected = (long)(100 * w.Market.GlobalPrice[coal]) + (long)(40 * w.Market.GlobalPrice[ore]);
|
|
Assert.Equal(expected, (w.Player.AssetBookValue - before).Cents);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Rete merci di Valdoria con un treno di carri coperti tra le miniere e l'acciaieria: la linea non
|
|
/// porta minerale né acciaio, quindi le uniche merci a bordo sono quelle spedite dalla compagnia.
|
|
/// </summary>
|
|
private static (RailFixture F, Station Mine, Station Mill, Train Train) BoxLine()
|
|
{
|
|
var f = Valdoria();
|
|
var (mine, mill, depot) = f.BuildFreightNetwork();
|
|
int train = f.Train(depot, "Coperti 1", ("loco_steam_1850", 1), ("wagon_box", 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)));
|
|
Unlock(f.W);
|
|
return (f, f.W.Network.Stations[mine], f.W.Network.Stations[mill], f.W.Trains[train]);
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Spedizione tra due stazioni della compagnia: consegnata nel magazzino di destinazione, senza tariffa né consumatori")]
|
|
public static void ShippedGoodsReachTheDestinationWarehouseWithoutFare()
|
|
{
|
|
var (f, mine, mill, train) = BoxLine();
|
|
var w = f.W;
|
|
int goods = GoodIndex(w, "goods");
|
|
Inject(w, mine, goods, 50);
|
|
|
|
var r = f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 80));
|
|
Assert.True(r.Ok, r.Message);
|
|
Assert.Equal(1, r.Created.Length);
|
|
Assert.Equal(0, mine.StockOf(goods));
|
|
Assert.Equal(50, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
|
Assert.Equal(w.Data.Balance.Trading.WarehouseCapacity - 50, TradingMath.FreeSpace(w, mill, 50));
|
|
var packet = mine.Waiting.Single(p => p.Owned);
|
|
Assert.Equal(r.Created[0], packet.Id);
|
|
Assert.Equal(0, mill.Incoming[goods]);
|
|
AssertInvariants(w, "alla spedizione");
|
|
|
|
// ricavi merci giorno per giorno (le voci annuali si azzerano a capodanno)
|
|
long revenue = 0, before = w.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
|
int year = w.Clock.Year;
|
|
bool onBoard = false;
|
|
bool arrived = f.RunUntil(() =>
|
|
{
|
|
onBoard |= train.Cargo.Any(p => p.Owned);
|
|
long now = w.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
|
if (w.Clock.Year != year)
|
|
{
|
|
revenue += w.Player.LastYearEntries[(int)LedgerEntry.FreightRevenue] - before;
|
|
before = 0;
|
|
year = w.Clock.Year;
|
|
}
|
|
revenue += now - before;
|
|
before = now;
|
|
return mill.StockOf(goods) == 50;
|
|
}, 120);
|
|
Assert.True(arrived, "la merce arriva all'acciaieria");
|
|
Assert.True(onBoard, "la merce ha viaggiato sul treno");
|
|
Assert.Equal(0L, revenue, "nessuna tariffa per la merce propria");
|
|
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
|
Assert.False(mill.Waiting.Any(p => p.Owned) || train.Cargo.Any(p => p.Owned), "nessun pacchetto proprio rimasto");
|
|
AssertInvariants(w, "all'arrivo");
|
|
|
|
// il magazzino pieno a destinazione rifiuta la spedizione a priori
|
|
Inject(w, mine, goods, 10);
|
|
Inject(w, mill, goods, w.Data.Balance.Trading.WarehouseCapacity - 50);
|
|
Assert.Equal(CommandError.Blocked, f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 10)).Error);
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Non si spedisce dove la fermata di partenza non carica; una linea modificata riporta in magazzino la merce in attesa")]
|
|
public static void ShippingFollowsTheLoadAndUnloadFlagsOfTheStops()
|
|
{
|
|
var (f, mine, mill, train) = BoxLine();
|
|
var w = f.W;
|
|
int goods = GoodIndex(w, "goods");
|
|
var line = train.Line;
|
|
Inject(w, mine, goods, 60);
|
|
f.Ok(new EditLineCommand(line, new[] { new LineStop(mine.Id, Load: false), new LineStop(mill.Id) }));
|
|
var refused = f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 60));
|
|
Assert.Equal(CommandError.Blocked, refused.Error, refused.Message);
|
|
Assert.Equal(60, mine.StockOf(goods));
|
|
Assert.False(mine.Waiting.Any(p => p.Owned), "nessun pacchetto creato");
|
|
|
|
// spedita con la fermata che carica, poi la linea smette di caricare lì prima che passi il treno
|
|
f.Ok(new EditLineCommand(line, new[] { new LineStop(mine.Id), new LineStop(mill.Id) }));
|
|
Assert.True(f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 60)).Ok);
|
|
Assert.Equal(0, mine.StockOf(goods));
|
|
f.Ok(new EditLineCommand(line, new[] { new LineStop(mine.Id, Load: false), new LineStop(mill.Id) }));
|
|
w.RunDays(1);
|
|
Assert.False(mine.Waiting.Any(p => p.Owned) || train.Cargo.Any(p => p.Owned), "il pacchetto non aspetta più un treno che non lo carica");
|
|
Assert.Equal(60, mine.StockOf(goods));
|
|
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
|
AssertInvariants(w, "dopo il rientro in magazzino");
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Un treno che lascia la linea con merce propria a bordo la lascia in un magazzino e libera lo spazio prenotato")]
|
|
public static void OwnedCargoLeavesATrainTakenOffItsLine()
|
|
{
|
|
var (f, mine, mill, train) = BoxLine();
|
|
var w = f.W;
|
|
int goods = GoodIndex(w, "goods");
|
|
Inject(w, mine, goods, 50);
|
|
Assert.True(f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 50)).Ok);
|
|
Assert.True(f.RunUntil(() => train.Cargo.Any(p => p.Owned) && !train.AtNode.IsValid, 60), "la merce è a bordo e il treno in viaggio");
|
|
Assert.Equal(50, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
|
|
|
f.Ok(new AssignTrainCommand(train.Id, LineId.None));
|
|
Assert.False(train.Cargo.Any(p => p.Owned), "nessun pacchetto proprio a bordo");
|
|
Assert.True(train.Vehicles.All(v => w.Vehicles[v.Value].Load == 0), "carri vuoti");
|
|
// in viaggio verso l'acciaieria, che è la destinazione: la merce entra nel suo magazzino
|
|
Assert.Equal(50, mill.StockOf(goods));
|
|
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
|
AssertInvariants(w, "dopo il ritiro del treno");
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Una linea modificata con la merce propria a bordo: scende alla prima fermata e torna in magazzino")]
|
|
public static void OwnedCargoOffTheEditedLineIsUnloaded()
|
|
{
|
|
var (f, mine, mill, train) = BoxLine();
|
|
var w = f.W;
|
|
int goods = GoodIndex(w, "goods");
|
|
Inject(w, mine, goods, 50);
|
|
Assert.True(f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 50)).Ok);
|
|
Assert.True(f.RunUntil(() => train.Cargo.Any(p => p.Owned) && !train.AtNode.IsValid, 60), "la merce è a bordo e il treno in viaggio");
|
|
|
|
// la linea non arriva più all'acciaieria: il treno torna alle miniere
|
|
f.Ok(new EditLineCommand(train.Line, new[] { new LineStop(mine.Id), new LineStop(mine.Id) }));
|
|
Assert.True(f.RunUntil(() => !train.Cargo.Any(p => p.Owned), 60), "la merce scende dal treno");
|
|
Assert.Equal(50, mine.StockOf(goods));
|
|
Assert.Equal(0, mill.StockOf(goods));
|
|
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
|
AssertInvariants(w, "dopo lo scarico");
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Al trasbordo la scadenza in stazione della merce propria riparte da zero")]
|
|
public static void OwnedGoodsExpiryRestartsAtTransfer()
|
|
{
|
|
var (f, mine, mill, train) = BoxLine();
|
|
var w = f.W;
|
|
int goods = GoodIndex(w, "goods");
|
|
Assert.Equal(0, train.StopIndex);
|
|
// merce propria a bordo che scende alle miniere per proseguire verso l'acciaieria, con la scadenza già passata
|
|
int id = w.NextIds.Packet++;
|
|
train.Cargo.Add(new Packet
|
|
{
|
|
Id = id, Kind = PacketKind.Freight, Good = goods, Units = 20, Origin = mill.Id, Destination = mill.Id,
|
|
HopLine = train.Line, HopEnd = mine.Id, CreatedTick = 0, ExpiresTick = 0, Contract = -1, Owned = true,
|
|
});
|
|
var wagon = w.Vehicles[train.Vehicles.First(v => w.Vehicles[v.Value].Def.Kind == RailEnterprise.Core.Data.VehicleKind.Wagon).Value];
|
|
wagon.Good = goods;
|
|
wagon.Load = 20;
|
|
w.Goods.Produced[goods] += 20;
|
|
long decay = (long)w.Data.Goods[goods].DecayDaysAtStation * w.Calendar.TicksPerDay;
|
|
|
|
Packet? after = null;
|
|
Assert.True(f.RunUntil(() =>
|
|
{
|
|
foreach (var p in mine.Waiting.Concat(train.Cargo))
|
|
if (p.Id == id && p.ExpiresTick != 0) after = p;
|
|
return after is not null || mill.StockOf(goods) > 0;
|
|
}, 60), "il pacchetto passa dalle miniere");
|
|
Assert.True(after is { } a && a.ExpiresTick > w.Context.Tick - w.Calendar.TicksPerDay && a.ExpiresTick <= w.Context.Tick + decay,
|
|
$"scadenza rinnovata al trasbordo: {after?.ExpiresTick} al tick {w.Context.Tick}");
|
|
long decayed = w.Goods.Decayed[goods];
|
|
Assert.True(f.RunUntil(() => mill.StockOf(goods) == 20, 120), "la merce arriva all'acciaieria");
|
|
Assert.Equal(decayed, w.Goods.Decayed[goods], "niente merce deperita");
|
|
AssertInvariants(w, "all'arrivo");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Un anno di commercio sulla rete merci di Valdoria (treno a tramogge): ogni mese si compra
|
|
/// minerale dalla miniera, lo si spedisce all'acciaieria e si vende quello arrivato; restituisce il mondo.
|
|
/// </summary>
|
|
private static World TradingYear(Func<World, World>? midway = null, Action<string>? log = null)
|
|
{
|
|
var f = Valdoria();
|
|
var (mineId, millId, depot) = f.BuildFreightNetwork();
|
|
int portId = f.Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
|
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(mineId)), new LineStop(new StationId(millId)) }));
|
|
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
|
Unlock(f.W);
|
|
var w = f.W;
|
|
int dpm = w.Calendar.DaysPerMonth;
|
|
for (int month = 0; month < 12; month++)
|
|
{
|
|
var mine = w.Network.Stations[mineId];
|
|
var mill = w.Network.Stations[millId];
|
|
Enqueue(w, new BuyGoodsCommand(mine.Id, "iron_ore", 30, Money.FromLire(1000)));
|
|
Enqueue(w, new ShipGoodsCommand(mine.Id, mill.Id, "iron_ore", 30));
|
|
Enqueue(w, new SellGoodsCommand(mill.Id, "iron_ore", 25, Money.FromLire(1)));
|
|
Enqueue(w, new BuyGoodsCommand(mill.Id, "steel", 5, Money.FromLire(1000)));
|
|
// al porto: importazione e rivendita all'hub di metà del carbone comprato
|
|
var port = w.Network.Stations[portId];
|
|
Enqueue(w, new BuyGoodsCommand(port.Id, "coal", 40, Money.FromLire(1000)));
|
|
Enqueue(w, new SellGoodsCommand(port.Id, "coal", 20, Money.FromLire(1)));
|
|
if (month == 6 && midway is not null)
|
|
{
|
|
// salvataggio a due giorni dai comandi: la merce spedita è ancora in viaggio
|
|
w.RunDays(2);
|
|
foreach (var r in w.DrainResults()) log?.Invoke($"{r.Type}: {r.Error} {r.Message}");
|
|
w = midway(w);
|
|
w.RunDays(dpm - 2);
|
|
}
|
|
else
|
|
{
|
|
w.RunDays(dpm);
|
|
}
|
|
foreach (var r in w.DrainResults()) log?.Invoke($"{r.Type}: {r.Error} {r.Message}");
|
|
for (int g = 0; g < w.Data.GoodCount; g++)
|
|
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}");
|
|
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}");
|
|
}
|
|
return w;
|
|
}
|
|
|
|
private static void Enqueue(World w, GameCommand c) => w.Enqueue(c with { Issuer = w.Player.Id });
|
|
|
|
[Test(Slow = true, Description = "Un anno di compravendita e spedizioni: invarianti di denaro e merci sempre veri, giacenze addebitate")]
|
|
public static void InvariantsHoldThroughAYearOfTrading()
|
|
{
|
|
var lines = new List<string>();
|
|
var w = TradingYear(log: lines.Add);
|
|
int Ok(string type) => lines.Count(l => l.StartsWith(type + ": None", StringComparison.Ordinal));
|
|
Console.WriteLine($" riusciti: acquisti {Ok("BuyGoods")}, spedizioni {Ok("ShipGoods")}, vendite {Ok("SellGoods")} su {lines.Count} comandi");
|
|
Assert.True(Ok("BuyGoods") >= 12 && Ok("ShipGoods") >= 6 && Ok("SellGoods") >= 6, string.Join(Environment.NewLine, lines));
|
|
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Trading] != 0 || w.Player.LastYearEntries[(int)LedgerEntry.Trading] != 0, "voce «Commercio» movimentata");
|
|
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
|
Assert.True(steel.LastServedDay >= 0, "l'acciaieria è stata servita");
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Determinismo e salvataggi: stessi comandi di commercio → stesso hash, anche passando da un salvataggio con merce in magazzino e in viaggio")]
|
|
public static void TradingIsDeterministicAndSurvivesSaves()
|
|
{
|
|
bool sawStock = false, sawTransit = false;
|
|
World ThroughSave(World w)
|
|
{
|
|
sawStock = w.Network.Stations.Any(s => s.StockTotal > 0);
|
|
sawTransit = w.Network.Stations.Any(s => s.Waiting.Any(p => p.Owned)) || w.Trains.Any(t => t.Cargo.Any(p => p.Owned));
|
|
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
|
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "hash subito dopo il caricamento");
|
|
for (int i = 0; i < w.Network.Stations.Count; i++)
|
|
{
|
|
Assert.SequenceEqual(w.Network.Stations[i].Stock, loaded.Network.Stations[i].Stock, $"magazzino della stazione {i}");
|
|
Assert.SequenceEqual(w.Network.Stations[i].Waiting.Select(p => p.Owned), loaded.Network.Stations[i].Waiting.Select(p => p.Owned));
|
|
}
|
|
for (int i = 0; i < w.Trains.Count; i++)
|
|
Assert.SequenceEqual(w.Trains[i].Cargo.Select(p => p.Owned), loaded.Trains[i].Cargo.Select(p => p.Owned), $"carico del treno {i}");
|
|
return loaded;
|
|
}
|
|
var a = TradingYear();
|
|
var b = TradingYear();
|
|
var c = TradingYear(ThroughSave);
|
|
Assert.Equal(a.LastStateHash, b.LastStateHash, "stesso seme e stessi comandi");
|
|
Assert.True(sawStock, "il salvataggio contiene merce in magazzino");
|
|
Assert.True(sawTransit, "il salvataggio contiene merce in viaggio");
|
|
Assert.Equal(a.LastStateHash, c.LastStateHash, "salvare e ricaricare non cambia il futuro");
|
|
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
|
|
}
|
|
|
|
[Test(Description = "Un salvataggio della versione 3 (prima del commercio) si carica con i magazzini vuoti e lo stesso stato")]
|
|
public static void VersionThreeSavesLoadWithEmptyWarehouses()
|
|
{
|
|
var (f, _, _, port) = Stations();
|
|
var w = f.W;
|
|
w.RunDays(5);
|
|
var body = new SaveWriter(1 << 20);
|
|
WorldSerializer.Write(w, body, 3);
|
|
var loaded = WorldSerializer.Read(TestData.Data, new SaveReader(body.WrittenSpan.ToArray()));
|
|
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso stato dinamico");
|
|
Assert.True(loaded.Network.Stations.All(s => s.Stock.Length == TestData.Data.GoodCount && s.StockTotal == 0), "magazzini vuoti");
|
|
|
|
// la partita caricata commercia normalmente
|
|
Unlock(loaded);
|
|
loaded.Enqueue(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)) { Issuer = loaded.Player.Id });
|
|
loaded.RunTicks(1);
|
|
Assert.True(loaded.DrainResults().Last().Ok);
|
|
Assert.Equal(10, loaded.Network.Stations[port.Id.Value].StockOf(GoodIndex(loaded, "coal")));
|
|
Assert.Throws<ArgumentOutOfRangeException>(() => WorldSerializer.Write(w, new SaveWriter(16), WorldSerializer.BodyVersion + 1));
|
|
}
|
|
|
|
[Test(Description = "Il quadro del mercato porta al client i magazzini della compagnia con giacenze e prezzi locali")]
|
|
public static void MarketReportCarriesTheWarehouses()
|
|
{
|
|
var (f, mine, _, port) = Stations();
|
|
var w = f.W;
|
|
Unlock(w);
|
|
Assert.True(f.Do(new BuyGoodsCommand(port.Id, "coal", 25, Money.FromLire(1000))).Ok);
|
|
var report = RailEnterprise.Server.Projection.Market(w, f.Me);
|
|
Assert.Equal(3, report.Warehouses.Count);
|
|
var house = report.Warehouses.Single(h => h.Station == port.Id.Value);
|
|
Assert.Equal(w.Data.Balance.Trading.WarehouseCapacity, house.Capacity);
|
|
int coal = GoodIndex(w, "coal");
|
|
var g = house.Goods.Single(x => x.Good == coal);
|
|
Assert.Equal(25, g.Units);
|
|
Assert.Approx(w.Hubs[0].SellPrice(w.Market.GlobalPrice[coal]), g.BuyPrice, 1e-9);
|
|
Assert.Approx(w.Hubs[0].BuyPrice(w.Market.GlobalPrice[coal]), g.SellPrice, 1e-9);
|
|
var ore = report.Warehouses.Single(h => h.Station == mine.Id.Value).Goods.Single(x => x.Good == GoodIndex(w, "iron_ore"));
|
|
Assert.True(ore.BuyUnits > 0 && ore.BuyPrice > 0, "la miniera vende minerale");
|
|
|
|
// round-trip del blocco 1 di MarketReport
|
|
var decoded = (MarketReport)Frame.Decode(Frame.Encode(report));
|
|
Assert.Equal(report.Warehouses.Count, decoded.Warehouses.Count);
|
|
Assert.Equal(25, decoded.Warehouses.Single(h => h.Station == port.Id.Value).Goods.Single(x => x.Good == coal).Units);
|
|
// la merce in magazzino entra nelle scorte del mercato globale
|
|
Assert.Equal(MarketOutlook.StockUnits(w, coal), w.Industries.Where(i => !i.Closed && i.InputIndexOf(coal) >= 0).Sum(i => (double)i.InputStock[i.InputIndexOf(coal)])
|
|
+ w.Industries.Where(i => !i.Closed && i.OutputIndexOf(coal) >= 0).Sum(i => (double)i.OutputStock[i.OutputIndexOf(coal)])
|
|
+ w.Network.Stations.Where(s => w.Network.IsAlive(s)).Sum(s => s.Waiting.Where(p => p.Kind == PacketKind.Freight && p.Good == coal).Sum(p => (double)p.Units) + s.StockOf(coal)));
|
|
}
|
|
|
|
[Test(Description = "ShipGoods (comando 40) sopravvive al round-trip del protocollo con tutti i campi")]
|
|
public static void ShipGoodsRoundTrips()
|
|
{
|
|
var c = new ShipGoodsCommand(new StationId(3), new StationId(7), "iron_ore", 120);
|
|
var decoded = (ShipGoodsCommand)((CommandMessage)Frame.Decode(Frame.Encode(new CommandMessage { Seq = 5, Command = c }))).Command;
|
|
Assert.Equal((ushort)40, (ushort)decoded.Type);
|
|
Assert.Equal(c.From, decoded.From);
|
|
Assert.Equal(c.To, decoded.To);
|
|
Assert.Equal("iron_ore", decoded.Good);
|
|
Assert.Equal(120, decoded.Units);
|
|
Assert.Equal(5u, decoded.Seq);
|
|
}
|
|
}
|