using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Core.Economy; using RailEnterprise.Core.Rail; using RailEnterprise.Core.Simulation.Systems; namespace RailEnterprise.Core.Simulation; /// /// Compravendita in proprio (F6, ADR 0016): comprare dai produttori e dagli hub del bacino di una /// stazione al prezzo locale, rivendere ai consumatori e agli hub, spedire la merce tra i magazzini /// della compagnia sulle sue linee. Ogni comando valida tutto prima di cambiare il mondo; il denaro /// passa dal registro e la merce resta sempre in un magazzino tracciato. /// public static class TradingCommandHandlers { public static CommandResult Buy(World w, Company company, BuyGoodsCommand c, RailCommandHandlers.Reply reply) { if (!Check(w, company, c.Station, c.Good, c.Units, true, out var s, out int good, out var error)) return reply(error.Error, error.Message); if (!MarketOutlook.IsAvailable(w, good)) return reply(CommandError.EraLocked, $"{GoodName(w, good)} non è ancora disponibile (dal {w.Data.Goods[good].Era})"); int free = TradingMath.FreeSpace(w, s, TradingMath.ReservedByStation(w)[s.Id.Value]); if (free <= 0) return reply(CommandError.Blocked, $"Magazzino di {s.Name} pieno ({w.Data.Balance.Trading.WarehouseCapacity} unità comprese le spedizioni in arrivo)"); var sellers = TradingMath.Sellers(w, s, good); if (TradingMath.CheapestSeller(w, sellers, good, out double first) is null) return reply(CommandError.NotFound, $"Nessun produttore né hub nel bacino di {s.Name} vende {GoodName(w, good)}"); if (first > c.MaxUnitPrice.Cents) return reply(CommandError.InvalidArgument, $"Il prezzo più basso è {PerUnit(w, good, first)}, oltre il tetto di {PerUnit(w, good, c.MaxUnitPrice.Cents)}"); int want = Math.Min(c.Units, free); int bought = 0; long committed = 0; bool shortOfCash = false; string stop = want < c.Units ? "magazzino pieno" : ""; while (bought < want) { var best = TradingMath.CheapestSeller(w, sellers, good, out double price); if (best is null) { stop = "esaurita la merce in vendita nel bacino"; break; } if (price > c.MaxUnitPrice.Cents) { stop = "nessun'altra unità sotto il tetto di prezzo"; break; } long next = committed - Rounded(best.Cents) + Rounded(best.Cents + price); if (next > company.Cash.Cents) { shortOfCash = true; stop = "cassa esaurita"; break; } committed = next; best.Units++; best.Cents += price; bought++; } if (bought == 0) return reply(CommandError.InsufficientFunds, shortOfCash ? $"Cassa insufficiente: un'unità costa {PerUnit(w, good, first)}" : "Nessuna unità acquistabile"); var from = Account.Of(company.Id); foreach (var p in sellers) { if (p.Units == 0) continue; var amount = Money.FromCentsRounded(p.Cents); if (p.Kind == TradePartyKind.Industry) { var ind = w.Industries[p.Target]; ind.OutputStock[p.Slot] -= p.Units; w.Money.Transfer(from, Account.Of(ind.Id), amount, LedgerEntry.Trading); ind.SalesToday += amount.Cents; if (p.Slot == 0) ind.ShippedToday += p.Units; ind.LastServedDay = w.Clock.Day; } else { var hub = w.Hubs[p.Target]; hub.UsedThisMonth += p.Units; hub.ImportedThisMonth[good] += p.Units; w.Goods.Imported[good] += p.Units; w.Money.Transfer(from, Account.External, amount, LedgerEntry.Trading); } } TradingMath.AddToWarehouse(s, good, bought, w.Data.GoodCount); var total = new Money(committed); string limit = bought < c.Units ? $" ({stop})" : ""; return reply(CommandError.None, $"Comprate {bought} {Unit(w, good)} di {GoodName(w, good)} a {s.Name} per {total} (in media {PerUnit(w, good, (double)committed / bought)}){limit}"); } public static CommandResult Sell(World w, Company company, SellGoodsCommand c, RailCommandHandlers.Reply reply) { if (!Check(w, company, c.Station, c.Good, c.Units, false, out var s, out int good, out var error)) return reply(error.Error, error.Message); int stock = s.StockOf(good); if (stock <= 0) return reply(CommandError.NotFound, $"Nel magazzino di {s.Name} non c'è {GoodName(w, good)}"); var buyers = TradingMath.Buyers(w, s, good); if (buyers.Count == 0) { bool consumers = s.Industries.Any(id => w.Industries[id.Value] is { Closed: false } ind && ind.Level > 0 && ind.InputIndexOf(good) >= 0); return reply(CommandError.NotFound, consumers ? $"I consumatori di {GoodName(w, good)} nel bacino di {s.Name} hanno il magazzino pieno" : $"Nessun consumatore né hub nel bacino di {s.Name} compra {GoodName(w, good)}"); } var top = TradingMath.BestBuyer(w, buyers, good, out double first); if (top is null) return reply(CommandError.InsufficientFunds, $"Le industrie del bacino di {s.Name} non hanno cassa per pagare {GoodName(w, good)}"); if (first < c.MinUnitPrice.Cents) return reply(CommandError.InvalidArgument, $"Il prezzo più alto è {PerUnit(w, good, first)}, sotto il minimo di {PerUnit(w, good, c.MinUnitPrice.Cents)}"); int want = Math.Min(c.Units, stock); int sold = 0; double cents = 0; while (sold < want) { var best = TradingMath.BestBuyer(w, buyers, good, out double price); if (best is null || price < c.MinUnitPrice.Cents) break; best.Units++; best.Cents += price; cents += price; sold++; } var to = Account.Of(company.Id); long received = 0; foreach (var p in buyers) { if (p.Units == 0) continue; var amount = Money.FromCentsRounded(p.Cents); received += amount.Cents; if (p.Kind == TradePartyKind.Industry) { var ind = w.Industries[p.Target]; ind.InputStock[p.Slot] += p.Units; w.Money.Transfer(Account.Of(ind.Id), to, amount, LedgerEntry.Trading); ind.PurchasesToday += amount.Cents; ind.LastServedDay = w.Clock.Day; } else { var hub = w.Hubs[p.Target]; hub.UsedThisMonth += p.Units; hub.ExportedThisMonth[good] += p.Units; w.Goods.Exported[good] += p.Units; w.Money.Transfer(Account.External, to, amount, LedgerEntry.Trading); } } s.Stock[good] -= sold; string rest = sold < c.Units ? $" ({(sold < stock ? "i compratori del bacino non ne prendono altre a questo prezzo" : "tutto il magazzino")})" : ""; return reply(CommandError.None, $"Vendute {sold} {Unit(w, good)} di {GoodName(w, good)} a {s.Name} per {new Money(received)} (in media {PerUnit(w, good, cents / sold)}){rest}"); } public static CommandResult Ship(World w, Company company, ShipGoodsCommand c, WorldContext ctx, RailCommandHandlers.Reply reply) { if (!Check(w, company, c.From, c.Good, c.Units, false, out var from, out int good, out var error)) return reply(error.Error, error.Message); if (!TryOwnStation(w, company, c.To, out var to, out error)) return reply(error.Error, error.Message); if (to.Id == from.Id) return reply(CommandError.InvalidArgument, "La stazione di partenza e quella di arrivo coincidono"); int stock = from.StockOf(good); if (stock <= 0) return reply(CommandError.NotFound, $"Nel magazzino di {from.Name} non c'è {GoodName(w, good)}"); // percorso con i flag delle fermate: si carica alla partenza e si scarica a ogni cambio var graph = w.LineGraphs.For(w, company.Id); var cargo = LineGraph.GoodCargo(good); if (!graph.From(from.Id, cargo, stopFlags: true).TryGetValue(to.Id.Value, out var conn)) { return graph.From(from.Id, cargo).ContainsKey(to.Id.Value) ? reply(CommandError.Blocked, $"Le linee da {from.Name} a {to.Name} non caricano la merce a {from.Name} o non la scaricano ai cambi: controlla carico e scarico delle fermate") : reply(CommandError.NotFound, $"Nessuna linea della compagnia porta {GoodName(w, good)} da {from.Name} a {to.Name}"); } int free = TradingMath.FreeSpace(w, to, TradingMath.ReservedByStation(w)[to.Id.Value]); if (free <= 0) return reply(CommandError.Blocked, $"Magazzino di {to.Name} pieno ({w.Data.Balance.Trading.WarehouseCapacity} unità comprese le spedizioni in arrivo)"); int units = Math.Min(Math.Min(c.Units, stock), free); var packet = new Packet { Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = good, Units = units, Origin = from.Id, Destination = to.Id, HopLine = conn.First.Line, HopEnd = conn.First.To, CreatedTick = ctx.Tick, ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay, ExpectedDays = w.Calendar.TrainMinutesToDays(conn.Minutes), Contract = -1, Owned = true, }; from.Stock[good] -= units; from.Waiting.Add(packet); string limit = units < c.Units ? $" ({(units == stock ? "tutta la giacenza" : $"limitate dallo spazio libero a {to.Name}")})" : ""; return reply(CommandError.None, $"Spedite {units} {Unit(w, good)} di {GoodName(w, good)} da {from.Name} a {to.Name}, circa {packet.ExpectedDays:0.#} giorni di viaggio{limit}", packet.Id); } /// Merce della compagnia arrivata a destinazione o senza più un percorso: entra nel magazzino della stazione. public static void Store(World w, Station s, Packet p) => TradingMath.AddToWarehouse(s, p.Good, p.Units, w.Data.GoodCount); /// /// Costo di giacenza mensile (trading.storageCostPerUnitPerMonth) per ogni unità nei magazzini /// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Commercio». /// public static void ChargeStorage(World w) { long perUnit = w.Data.Balance.Trading.StorageCostPerUnitPerMonth; if (perUnit <= 0) return; foreach (var s in w.Network.Stations) { 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); } } // ------------------------------------------------------------------ validazione /// /// Validazione comune. Lo sblocco del livello serve solo per comprare (): /// la merce già in magazzino, per esempio ereditata con una fusione, si vende e si spedisce sempre. /// private static bool Check(World w, Company company, StationId station, string goodId, int units, bool needsUnlock, out Station s, out int good, out (CommandError Error, string Message) error) { good = -1; s = null!; if (needsUnlock && !Tiers.Unlocks(w, company).Trading) { var tier = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.Trading); error = (CommandError.TierLocked, tier is null ? "La compravendita in proprio non è disponibile" : $"La compravendita in proprio si sblocca al livello «{tier.NameIt}»"); return false; } if (!TryOwnStation(w, company, station, out s, out error)) return false; if (!w.Data.TryGoodIndex(goodId ?? "", out good)) { error = (CommandError.NotFound, $"Merce sconosciuta: {goodId}"); return false; } if (units <= 0) { error = (CommandError.InvalidArgument, "Quantità non valida"); return false; } return true; } private static bool TryOwnStation(World w, Company company, StationId id, out Station s, out (CommandError Error, string Message) error) { s = null!; error = default; if (!id.IsValid || id.Value >= w.Network.Stations.Count || !w.Network.IsAlive(w.Network.Stations[id.Value])) { error = (CommandError.NotFound, "Stazione inesistente o demolita"); return false; } s = w.Network.Stations[id.Value]; if (s.Owner != company.Id) { error = (CommandError.NotAllowed, $"{s.Name} non è una stazione della compagnia"); return false; } return true; } private static long Rounded(double cents) => Money.FromCentsRounded(cents).Cents; private static string GoodName(World w, int good) => w.Data.Goods[good].NameIt.ToLowerInvariant(); private static string Unit(World w, int good) => w.Data.Goods[good].Unit; private static string PerUnit(World w, int good, double cents) => $"{Money.FromCentsRounded(cents)}/{Unit(w, good)}"; }