using RailEnterprise.Core.Common; namespace RailEnterprise.Core.Economy; /// Titolare di un conto nel registro a partita doppia. public enum AccountKind : byte { External = 0, Company = 1, Industry = 2 } /// Conto: il resto del mondo, una compagnia o un'industria. public readonly record struct Account(AccountKind Kind, int Index) { public static readonly Account External = new(AccountKind.External, 0); public static Account Of(CompanyId id) => new(AccountKind.Company, id.Value); public static Account Of(IndustryId id) => new(AccountKind.Industry, id.Value); } /// /// Registro a partita doppia: ogni movimento è un trasferimento tra due conti, quindi la /// somma di tutti i saldi (compagnie, industrie e conto Esterno) resta sempre zero. /// Il conto Esterno rappresenta salari pagati alle famiglie, clienti delle tariffe e mercato mondiale. /// public sealed class MoneyLedger(Func companies, Func industries) { /// Saldo del conto Esterno. public Money External { get; set; } /// Totale trasferito dall'inizio (statistica). public long TransfersCount { get; internal set; } public void Transfer(Account from, Account to, Money amount, LedgerEntry entry) => Transfer(from, to, amount, entry, entry); /// /// Trasferimento registrato su voci diverse per chi paga e chi incassa (per esempio dividendi pagati /// e dividendi incassati, ADR 0019): la somma dei saldi resta zero. /// public void Transfer(Account from, Account to, Money amount, LedgerEntry fromEntry, LedgerEntry toEntry) { if (amount.Cents == 0 || from == to) return; Adjust(from, -amount, fromEntry); Adjust(to, amount, toEntry); TransfersCount++; } private void Adjust(Account account, Money delta, LedgerEntry entry) { switch (account.Kind) { case AccountKind.External: External += delta; break; case AccountKind.Company: var c = companies(new CompanyId(account.Index)); c.Cash += delta; c.MonthEntries[(int)entry] += delta.Cents; c.YearEntries[(int)entry] += delta.Cents; break; case AccountKind.Industry: var i = industries(new IndustryId(account.Index)); i.Cash += delta; break; } } } /// /// Contatori dei flussi di merci per bene: la giacenza totale nel mondo deve valere /// prodotto + importato − consumato − deperito − esportato (invariante «nessun bene dal nulla»). /// public sealed class GoodsCounters(int goodCount) { public long[] Produced { get; } = new long[goodCount]; public long[] Consumed { get; } = new long[goodCount]; public long[] Decayed { get; } = new long[goodCount]; public long[] Imported { get; } = new long[goodCount]; public long[] Exported { get; } = new long[goodCount]; public long ExpectedStock(int good) => Produced[good] + Imported[good] - Consumed[good] - Decayed[good] - Exported[good]; }