diff --git a/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs
new file mode 100644
index 0000000..bc950ab
--- /dev/null
+++ b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs
@@ -0,0 +1,374 @@
+using System.Globalization;
+using System.Numerics;
+using System.Text;
+using Khaemhat.Application.Instance;
+using Khaemhat.Application.Ledger;
+using Khaemhat.Application.Licensing;
+using Khaemhat.Application.Modules;
+using Khaemhat.Application.Security;
+using Khaemhat.Application.Treasury;
+using Khaemhat.Core.Accounting;
+using Khaemhat.Core.Parties;
+using Khaemhat.Core.Tables;
+using Khaemhat.Core.Treasury;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+
+namespace Khaemhat.Application.Seeding;
+
+///
+/// The demo treasury (SPEC §14, issues #69-#72): the bank account of the company, the collections of the invoices
+/// paid by transfer (one only in part), the payments to the suppliers, a RiBa remittance presented and credited with an
+/// unpaid effect, a direct debit mandate, a bank statement still to reconcile with a saved rule for the fees, and the
+/// first reminder already sent to a customer. It runs after the demo ledger, only when the treasury (FIN) is licensed and only once: when the company has
+/// collections or remittances it adds nothing.
+///
+/// Collections and payments.
+/// The remittances.
+/// The mandates.
+/// The bank statements.
+/// Reads and writes the company.
+/// Whether the treasury is licensed.
+/// Today.
+public sealed class DemoTreasurySeeder(
+ PaymentService payments, RemittanceService remittances, MandateService mandates, BankReconciliationService reconciliation, IUnitOfWorkFactory factory,
+ ILicenseGate licenses, TimeProvider clock)
+ : ICompanySeeder
+{
+ /// The code of the demo bank account.
+ public const string BankCode = "BPD";
+
+ /// The capital paid into the bank on the first day of the year.
+ public const decimal OpeningBalance = 25000m;
+
+ /// The account of the capital paid in by the shareholders.
+ public const string CapitalAccount = "10.01.004";
+
+ /// The fees of the unpaid effect.
+ public const decimal UnpaidFees = 6.50m;
+
+ /// The monthly fee of the bank account, matched by a saved rule.
+ public const decimal AccountFee = 12.50m;
+
+ private static readonly Actor Seed = Actor.System;
+
+ ///
+ public int Order => 50;
+
+ /// An Italian IBAN with its check digits computed from ABI, CAB and account.
+ /// The CIN letter.
+ /// The ABI code.
+ /// The CAB code.
+ /// The account number (12 characters).
+ /// The IBAN.
+ public static string Iban(char cin, string abi, string cab, string account)
+ {
+ ArgumentNullException.ThrowIfNull(abi);
+ ArgumentNullException.ThrowIfNull(cab);
+ ArgumentNullException.ThrowIfNull(account);
+ var bban = cin + abi + cab + account;
+ var digits = new StringBuilder();
+ foreach (var c in bban + "IT00")
+ {
+ digits.Append(char.IsLetter(c) ? (c - 'A' + 10).ToString(CultureInfo.InvariantCulture) : c.ToString());
+ }
+
+ var check = 98 - (int)(BigInteger.Parse(digits.ToString(), CultureInfo.InvariantCulture) % 97);
+ return "IT" + check.ToString("00", CultureInfo.InvariantCulture) + bban;
+ }
+
+ ///
+ public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.Finance))
+ {
+ return;
+ }
+
+ var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
+ long bankId;
+ await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
+ {
+ if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0
+ || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0
+ || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0)
+ {
+ return;
+ }
+
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ bankId = await BankAsync(uow, cancellationToken).ConfigureAwait(false);
+ await OpeningAsync(uow, new DateOnly(today.Year, 1, 1), cancellationToken).ConfigureAwait(false);
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ await CollectionsAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false);
+ await RibaAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false);
+ await MandateAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
+ await StatementAsync(companyCode, bankId, today, cancellationToken).ConfigureAwait(false);
+ await RemindersAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
+ }
+
+ private static async Task BankAsync(IUnitOfWork uow, CancellationToken cancellationToken)
+ {
+ var banks = uow.Repository();
+ var bank = await banks.FindAsync(Query.For().Where(b => b.Code == BankCode), cancellationToken).ConfigureAwait(false);
+ if (bank is null)
+ {
+ bank = new BankAccount
+ {
+ Code = BankCode,
+ Description = "Conto corrente ordinario",
+ BankName = "Banca Popolare Dimostrativa",
+ Iban = Iban('X', "05034", "01000", "000000012345"),
+ Bic = "DEMOITM1XXX",
+ SiaCode = "A1B2C",
+ CucCode = "DEMO1234",
+ CreditorId = "IT66ZZZ00000000000000000",
+ AccountCode = DemoLedgerSeeder.BankAccount,
+ IsDefault = true,
+ IsDemo = true,
+ };
+ bank.Id = await banks.InsertAsync(bank, cancellationToken).ConfigureAwait(false);
+ }
+
+ var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false);
+ if (profile is not null && profile.DefaultBankAccountId is null)
+ {
+ profile.DefaultBankAccountId = bank.Id;
+ await uow.Repository().UpdateAsync(profile, cancellationToken).ConfigureAwait(false);
+ }
+
+ await CustomerBanksAsync(uow, cancellationToken).ConfigureAwait(false);
+ return bank.Id;
+ }
+
+ // The shareholders paid the capital into the bank on the first day of the year, so the account starts in credit.
+ private static async Task OpeningAsync(IUnitOfWork uow, DateOnly day, CancellationToken cancellationToken)
+ {
+ var bank = await LedgerStore.AccountAsync(uow, DemoLedgerSeeder.BankAccount, cancellationToken).ConfigureAwait(false);
+ var capital = await LedgerStore.AccountAsync(uow, CapitalAccount, cancellationToken).ConfigureAwait(false);
+ if (bank is null || capital is null)
+ {
+ return;
+ }
+
+ await TreasuryStore.PostAsync(uow, "GIRO", day, "Versamento soci in conto capitale", null,
+ [new PaymentPostedLine(bank.Id, null, null, null, OpeningBalance, 0m), new PaymentPostedLine(capital.Id, null, null, null, 0m, OpeningBalance)], true, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ // The customers who pay by RiBa or direct debit need the coordinates of their bank: the demo parties that have none
+ // get one, so the remittances are complete.
+ private static async Task CustomerBanksAsync(IUnitOfWork uow, CancellationToken cancellationToken)
+ {
+ var collected = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items
+ .Where(m => m.Code is "RIBA" or "SDD" or "SDDB").Select(m => (long?)m.Id).ToList();
+ var receivable = OpenItemDirection.Receivable;
+ var parties = (await uow.Repository().ListAsync(
+ Query.For().Where(o => o.Direction == receivable && !o.Closed && collected.Contains(o.PaymentMethodId)), cancellationToken).ConfigureAwait(false)).Items
+ .Select(o => o.PartyId).Distinct().Order().ToList();
+ (string Abi, string Cab, string Name)[] branches = [("03069", "01000", "Banca del Territorio"), ("02008", "30330", "Banca Subalpina"), ("05696", "11000", "Credito Cooperativo Demo")];
+ var n = 0;
+ foreach (var partyId in parties)
+ {
+ var accounts = uow.Repository();
+ if (await accounts.CountAsync(Query.For().Where(a => a.PartyId == partyId), cancellationToken).ConfigureAwait(false) > 0)
+ {
+ continue;
+ }
+
+ var branch = branches[n++ % branches.Length];
+ await accounts.InsertAsync(new PartyBankAccount
+ {
+ PartyId = partyId,
+ Iban = Iban('K', branch.Abi, branch.Cab, (100000 + partyId).ToString("000000000000", CultureInfo.InvariantCulture)),
+ BankName = branch.Name,
+ BankCode = branch.Abi,
+ BranchCode = branch.Cab,
+ IsDefault = true,
+ }, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ // The invoices paid by transfer or on the spot are collected on their due date when it is more than three weeks
+ // ago; the oldest of one customer only in half, so the schedule shows a partial item. The suppliers, RiBa included,
+ // are paid on their due date when it is more than a week ago.
+ private async Task CollectionsAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken)
+ {
+ List items;
+ Dictionary methods;
+ await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
+ {
+ var limit = today.AddDays(-7);
+ var customers = today.AddDays(-21);
+ items = [.. (await uow.Repository().ListAsync(
+ Query.For().Where(o => !o.Closed && o.DueDate <= limit).OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items
+ .Where(o => o.Direction == OpenItemDirection.Payable || o.DueDate <= customers)];
+ methods = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
+ }
+
+ var partialDone = false;
+ foreach (var item in items.Where(i => i.Residual > 0m))
+ {
+ var method = item.PaymentMethodId is { } m ? methods.GetValueOrDefault(m) : null;
+ var receivable = item.Direction == OpenItemDirection.Receivable;
+ if (receivable && method?.Code is "RIBA" or "SDD" or "SDDB")
+ {
+ continue;
+ }
+
+ var amount = item.Residual;
+ if (receivable && !partialDone && method?.Code == "BON")
+ {
+ // The first transfer collected only in half: the rest stays overdue for the reminders.
+ amount = Math.Round(item.Residual / 2m, 2, MidpointRounding.AwayFromZero);
+ partialDone = true;
+ }
+
+ await payments.RegisterAsync(Seed, companyCode, new PaymentInput(
+ receivable ? PaymentDirection.Receipt : PaymentDirection.Disbursement, item.PartyId, item.DueDate, item.PaymentMethodId, bankId,
+ receivable ? 0m : 1.50m, "CRO " + item.Id.ToString("000000", CultureInfo.InvariantCulture), null,
+ [new PaymentLineInput(item.Id, amount)]), cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ // The RiBa due before today in a remittance presented and credited, the effect of one customer back unpaid;
+ // those due in the next 45 days in a draft remittance ready for the file.
+ private async Task RibaAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken)
+ {
+ var due = (await remittances.CandidatesAsync(Seed, companyCode, RemittanceKind.Riba, today.AddDays(-1), cancellationToken).ConfigureAwait(false))
+ .Where(c => c.Ready).ToList();
+ if (due.Count > 0)
+ {
+ var presentation = due.Min(c => c.Row.Item.DueDate).AddDays(-20);
+ var remittance = await remittances.CreateAsync(Seed, companyCode, new RemittanceInput(
+ RemittanceKind.Riba, bankId, presentation, today.AddDays(-1), false, "Distinta dimostrativa", [.. due.Select(c => c.Row.Item.Id)]), cancellationToken).ConfigureAwait(false);
+ await remittances.PresentAsync(Seed, companyCode, remittance.Id, cancellationToken).ConfigureAwait(false);
+ var latest = due.Max(c => c.Row.Item.DueDate);
+ await remittances.CreditAsync(Seed, companyCode, remittance.Id, latest, cancellationToken).ConfigureAwait(false);
+ var lines = (await remittances.GetAsync(Seed, companyCode, remittance.Id, cancellationToken).ConfigureAwait(false))!.Value.Lines;
+ var unpaid = lines.OrderByDescending(l => l.Line.DueDate).First();
+ var day = unpaid.Line.DueDate.AddDays(5);
+ await remittances.UnpaidAsync(Seed, companyCode, unpaid.Line.Id, day > today ? today : day, UnpaidFees, cancellationToken).ConfigureAwait(false);
+ }
+
+ var next = (await remittances.CandidatesAsync(Seed, companyCode, RemittanceKind.Riba, today.AddDays(45), cancellationToken).ConfigureAwait(false))
+ .Where(c => c.Ready && c.Row.Item.DueDate >= today && c.Row.Item.Status != OpenItemStatus.Unpaid).ToList();
+ if (next.Count > 0)
+ {
+ await remittances.CreateAsync(Seed, companyCode, new RemittanceInput(
+ RemittanceKind.Riba, bankId, today, today.AddDays(45), true, "Da presentare con anticipo s.b.f.", [.. next.Select(c => c.Row.Item.Id)]), cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private async Task MandateAsync(string companyCode, DateOnly today, CancellationToken cancellationToken)
+ {
+ await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
+ var party = await uow.Repository().FindAsync(Query.For().Where(p => p.Name == "Idrotermica Piemonte S.r.l."), cancellationToken).ConfigureAwait(false);
+ if (party is null)
+ {
+ return;
+ }
+
+ var account = await uow.Repository().FindAsync(Query.For().Where(a => a.PartyId == party.Id), cancellationToken).ConfigureAwait(false);
+ await mandates.SaveAsync(Seed, companyCode, new MandateInput(
+ null, party.Id, "KH-MND-" + party.Code, new DateOnly(today.Year, 1, 15), SddScheme.Core, account?.Iban ?? Iban('A', "06230", "10000", "000046012345"), null, false,
+ "Mandato firmato in sede"), cancellationToken).ConfigureAwait(false);
+ }
+
+ // A statement of the last days in CSV: a transfer received for an open invoice, a transfer to a supplier
+ // already recorded, the monthly fee of the account (matched by a saved rule) and a movement nobody knows yet.
+ private async Task StatementAsync(string companyCode, long bankId, DateOnly today, CancellationToken cancellationToken)
+ {
+ OpenItem? open;
+ Payment? paid;
+ string? openParty;
+ long? feeAccount;
+ await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
+ {
+ var receivable = OpenItemDirection.Receivable;
+ // The customer who paid half pays the rest: the movement matches the item, which names the invoice.
+ open = (await uow.Repository().ListAsync(
+ Query.For().Where(o => o.Direction == receivable && !o.Closed && (o.Status == OpenItemStatus.Partial || o.Status == OpenItemStatus.Open)).OrderBy(o => o.DueDate),
+ cancellationToken).ConfigureAwait(false)).Items
+ .Where(o => o.Residual > 0m && o.DocumentNumber is not null && o.DueDate <= today)
+ .OrderByDescending(o => o.Status == OpenItemStatus.Partial).FirstOrDefault();
+ openParty = open is null ? null : (await uow.Repository().GetAsync(open.PartyId, cancellationToken).ConfigureAwait(false))?.Name;
+ paid = await uow.Repository().FindAsync(
+ Query.For().Where(p => p.Direction == PaymentDirection.Disbursement).OrderByDescending(p => p.PaymentDate), cancellationToken).ConfigureAwait(false);
+ feeAccount = (await uow.Repository().FindAsync(Query.For().Where(a => a.Code == "21.03.011"), cancellationToken).ConfigureAwait(false))?.Id;
+ }
+
+ if (feeAccount is { } fees)
+ {
+ await reconciliation.SaveRuleAsync(Seed, companyCode, new BankRuleInput(null, "Canone e commissioni", "COMMISSIONI", BankRuleDirection.Out, fees, "Canone mensile conto corrente", false), cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ var culture = CultureInfo.GetCultureInfo("it-IT");
+ var csv = new StringBuilder("Data contabile;Data valuta;Descrizione;Importo\r\n");
+ void Row(DateOnly day, string text, decimal amount) =>
+ csv.Append(day.ToString("dd/MM/yyyy", culture)).Append(';').Append(day.ToString("dd/MM/yyyy", culture)).Append(';').Append(text).Append(';')
+ .Append(amount.ToString("0.00", culture)).Append("\r\n");
+ if (open is not null)
+ {
+ Row(today.AddDays(-4), "BONIFICO A VOSTRO FAVORE DA " + (openParty ?? string.Empty).ToUpperInvariant() + " SALDO FT " + open.DocumentNumber, open.Residual);
+ }
+
+ if (paid is not null)
+ {
+ Row(paid.PaymentDate, "BONIFICO SEPA " + paid.Reference, -(paid.Amount + paid.Fees));
+ }
+
+ Row(today.AddDays(-3), "COMMISSIONI E CANONE MENSILE CONTO", -AccountFee);
+ Row(today.AddDays(-2), "PAGAMENTO POS CARBURANTE", -64.20m);
+ await reconciliation.ImportAsync(Seed, companyCode, bankId, "estratto-demo.csv", Encoding.UTF8.GetBytes(csv.ToString()), cancellationToken).ConfigureAwait(false);
+ }
+
+ // The first reminder already sent ten days ago to the customer with the oldest overdue item.
+ private async Task RemindersAsync(string companyCode, DateOnly today, CancellationToken cancellationToken)
+ {
+ await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
+ await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
+ var receivable = OpenItemDirection.Receivable;
+ var limit = today.AddDays(-20);
+ var overdue = (await uow.Repository().ListAsync(
+ Query.For().Where(o => o.Direction == receivable && !o.Closed && o.DueDate <= limit && o.Status != OpenItemStatus.InRemittance).OrderBy(o => o.DueDate), cancellationToken)
+ .ConfigureAwait(false)).Items.Where(o => o.Residual > 0m).ToList();
+ var parties = await TreasuryStore.PartiesAsync(uow, overdue.Select(o => o.PartyId), cancellationToken).ConfigureAwait(false);
+ var first = overdue.FirstOrDefault(o => parties.TryGetValue(o.PartyId, out var p) && p.SubjectType != SubjectType.PublicAdministration);
+ if (first is null)
+ {
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ return;
+ }
+
+ var party = parties[first.PartyId];
+ var items = overdue.Where(o => o.PartyId == first.PartyId).ToList();
+ var sent = today.AddDays(-10);
+ await uow.Repository().InsertAsync(new DunningLetter
+ {
+ PartyId = party.Id,
+ Level = 1,
+ SentOn = sent,
+ Channel = DunningChannel.Email,
+ Recipients = party.Email,
+ Subject = "Promemoria scadenze",
+ ItemCount = items.Count,
+ OverdueAmount = items.Sum(i => i.Residual),
+ Status = DunningLetterStatus.Sent,
+ SentBy = "demo",
+ IsDemo = true,
+ }, cancellationToken).ConfigureAwait(false);
+ foreach (var item in items)
+ {
+ item.DunningLevel = 1;
+ item.LastDunningDate = sent;
+ await uow.Repository().UpdateAsync(item, cancellationToken).ConfigureAwait(false);
+ }
+
+ await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs
index de8acff..c8d74a9 100644
--- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs
+++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs
@@ -209,6 +209,8 @@ internal static class KhaemhatServices
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
+ services.AddSingleton();
+ services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
services.AddSingleton();
services.AddScoped();
diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs
index 4dbd532..a9c1922 100644
--- a/src/Khaemhat.Web/Hosting/SeedCommand.cs
+++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs
@@ -134,6 +134,7 @@ public static class SeedCommand
await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
+ await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
diff --git a/tests/Khaemhat.Web.Tests/Treasury/TreasuryTests.cs b/tests/Khaemhat.Web.Tests/Treasury/TreasuryTests.cs
new file mode 100644
index 0000000..74e30a2
--- /dev/null
+++ b/tests/Khaemhat.Web.Tests/Treasury/TreasuryTests.cs
@@ -0,0 +1,245 @@
+using System.Globalization;
+using System.Text;
+using Khaemhat.Application.Instance;
+using Khaemhat.Application.Ledger;
+using Khaemhat.Application.Licensing;
+using Khaemhat.Application.Security;
+using Khaemhat.Application.Seeding;
+using Khaemhat.Application.Treasury;
+using Khaemhat.Core.Accounting;
+using Khaemhat.Core.Security;
+using Khaemhat.Core.Tables;
+using Khaemhat.Core.Treasury;
+using Khaemhat.Data;
+using Khaemhat.Data.Querying;
+using Khaemhat.Web.Tests.Hosting;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Khaemhat.Web.Tests.Treasury;
+
+///
+/// The schedule and the treasury on a real instance (issues #69-#72): the demo treasury seeded on top of the demo
+/// ledger, a collection registered and cancelled, the RiBa remittance written to a file, the bank statement reconciled,
+/// the reminders proposed and the cash flow forecast. After every flow the trial balance still balances.
+///
+[TestClass]
+public sealed class TreasuryTests
+{
+ private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
+
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task DemoTreasury_IsSeededOnce_AndKeepsTheLedgerBalanced()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ await SeedAsync(app.Services, company);
+ var today = DateOnly.FromDateTime(DateTime.Now);
+ var payments = app.Services.GetRequiredService();
+ var remittances = app.Services.GetRequiredService();
+ var schedule = app.Services.GetRequiredService();
+
+ var collected = await payments.ListAsync(Root, company, PaymentDirection.Receipt, Year, Next);
+ var paid = await payments.ListAsync(Root, company, PaymentDirection.Disbursement, Year, Next);
+ TestContext.WriteLine($"Collections {collected.Count}, payments {paid.Count}");
+ Assert.IsNotEmpty(collected);
+ Assert.IsNotEmpty(paid);
+ Assert.IsTrue(collected.All(p => p.EntryNumber is not null), "Every collection has its entry.");
+
+ // A partial collection leaves a partial item; the RiBa back unpaid reopens its item.
+ var receivables = await schedule.ItemsAsync(Root, company, new ScheduleFilter(OpenItemDirection.Receivable, ScheduleView.All));
+ Assert.IsTrue(receivables.Rows.Any(r => r.Item.Status == OpenItemStatus.Partial));
+ var list = await remittances.ListAsync(Root, company, today.Year);
+ if (list.Any(r => r.Remittance.Status == RemittanceStatus.Closed))
+ {
+ Assert.IsTrue(receivables.Rows.Any(r => r.Item.Status == OpenItemStatus.Unpaid && r.Item.UnpaidCount == 1));
+ Assert.IsTrue(receivables.Rows.Any(r => r.Item.ParentId is not null && r.Item.Amount == DemoTreasurySeeder.UnpaidFees), "The fees of the unpaid effect are charged.");
+ }
+
+ Assert.IsNotEmpty(await app.Services.GetRequiredService().ListAsync(Root, company));
+ Assert.IsNotEmpty(await app.Services.GetRequiredService().HistoryAsync(Root, company));
+ Assert.IsNotEmpty(await app.Services.GetRequiredService().RulesAsync(Root, company));
+ await AssertBalancedAsync(app.Services, company);
+
+ // Run again, nothing changes.
+ await app.Services.GetRequiredService().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true));
+ Assert.HasCount(collected.Count, await payments.ListAsync(Root, company, PaymentDirection.Receipt, Year, Next));
+ Assert.HasCount(list.Count, await remittances.ListAsync(Root, company, today.Year));
+ await app.StopAsync();
+ }
+ }
+
+ [TestMethod]
+ public async Task ACollection_SettlesTheItems_AndIsCancelled()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ await SeedAsync(app.Services, company);
+ var payments = app.Services.GetRequiredService();
+ var schedule = app.Services.GetRequiredService();
+ var open = (await schedule.ItemsAsync(Root, company, new ScheduleFilter(OpenItemDirection.Receivable))).Rows
+ .First(r => r.Item.Status == OpenItemStatus.Open && r.Item.Residual > 10m).Item;
+ var day = DateOnly.FromDateTime(DateTime.Now);
+
+ // More than the residual is refused.
+ await Assert.ThrowsExactlyAsync(() => payments.RegisterAsync(Root, company, new PaymentInput(
+ PaymentDirection.Receipt, open.PartyId, day, null, null, 0m, null, null, [new PaymentLineInput(open.Id, open.Residual + 1m)])));
+
+ // Half, then the rest: the item is partial, then closed.
+ var half = Math.Round(open.Residual / 2m, 2);
+ var first = await payments.RegisterAsync(Root, company, new PaymentInput(
+ PaymentDirection.Receipt, open.PartyId, day, null, null, 0m, "CRO TEST1", null, [new PaymentLineInput(open.Id, half)]));
+ Assert.AreEqual(OpenItemStatus.Partial, (await schedule.ItemAsync(Root, company, open.Id))!.Item.Status);
+ var second = await payments.RegisterAsync(Root, company, new PaymentInput(
+ PaymentDirection.Receipt, open.PartyId, day, null, null, 0m, "CRO TEST2", null, [new PaymentLineInput(open.Id, open.Residual - half)]));
+ var closed = (await schedule.ItemAsync(Root, company, open.Id))!.Item;
+ Assert.AreEqual(OpenItemStatus.Closed, closed.Status);
+ Assert.AreEqual(0m, closed.Residual);
+ Assert.IsNotNull(first.GlEntryId);
+ await AssertBalancedAsync(app.Services, company);
+
+ // Cancelling both gives the item back as it was, and the entries go away.
+ await payments.CancelAsync(Root, company, second.Id);
+ await payments.CancelAsync(Root, company, first.Id);
+ var back = (await schedule.ItemAsync(Root, company, open.Id))!.Item;
+ Assert.AreEqual(OpenItemStatus.Open, back.Status);
+ Assert.AreEqual(open.Residual, back.Residual);
+ Assert.IsNull(await payments.GetAsync(Root, company, first.Id));
+ await AssertBalancedAsync(app.Services, company);
+ await app.StopAsync();
+ }
+ }
+
+ [TestMethod]
+ public async Task TheRibaRemittance_IsWrittenToAFile()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ await SeedAsync(app.Services, company);
+ var remittances = app.Services.GetRequiredService();
+ var today = DateOnly.FromDateTime(DateTime.Now);
+ var draft = (await remittances.ListAsync(Root, company, today.Year)).FirstOrDefault(r => r.Remittance.Status == RemittanceStatus.Draft);
+ if (draft is null)
+ {
+ Assert.Inconclusive("No RiBa due in the next weeks in the demo data of today.");
+ }
+
+ var file = await remittances.FileAsync(Root, company, draft.Remittance.Id);
+ var text = Encoding.Latin1.GetString(file.Content);
+ var records = text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
+ TestContext.WriteLine(file.FileName);
+ Assert.StartsWith(" IB", records[0]);
+ Assert.StartsWith(" EF", records[^1]);
+ Assert.IsTrue(records.All(r => r.Length == 120), "Every CBI record is 120 characters.");
+ Assert.AreEqual(RemittanceStatus.Generated, (await remittances.GetAsync(Root, company, draft.Remittance.Id))!.Value.Row.Remittance.Status);
+
+ // Presented: the effects leave the customers for the bank, the entry balances.
+ await remittances.PresentAsync(Root, company, draft.Remittance.Id);
+ var presented = (await remittances.GetAsync(Root, company, draft.Remittance.Id))!.Value;
+ Assert.AreEqual(RemittanceStatus.Presented, presented.Row.Remittance.Status);
+ Assert.IsNotNull(presented.Row.Remittance.GlEntryId);
+ await AssertBalancedAsync(app.Services, company);
+ await app.StopAsync();
+ }
+ }
+
+ [TestMethod]
+ public async Task TheBankStatement_IsReconciled()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ await SeedAsync(app.Services, company);
+ var reconciliation = app.Services.GetRequiredService();
+ var bank = await BankAsync(app.Services, company);
+ var lines = await reconciliation.LinesAsync(Root, company, bank, onlyOpen: true);
+ foreach (var l in lines)
+ {
+ TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{l.Line.BookingDate:dd/MM} {l.Line.Amount,10:0.00} {l.Line.Status} {l.Line.MatchKind} {l.Line.Confidence} {l.Line.Description}"));
+ }
+
+ Assert.IsTrue(lines.Any(l => l.Line.MatchKind == StatementMatchKind.Rule && l.Line.Amount == -DemoTreasurySeeder.AccountFee));
+ Assert.IsTrue(lines.Any(l => l.Line.Status == StatementLineStatus.ToMatch), "The movement nobody knows stays to match.");
+
+ // The same file again adds nothing.
+ var again = await reconciliation.StatementsAsync(Root, company, bank);
+ Assert.HasCount(1, again);
+
+ // Confirming the suggestions posts the fee and matches the rest; the unknown movement stays.
+ var confirmed = await reconciliation.ConfirmAllAsync(Root, company, bank);
+ Assert.IsGreaterThan(0, confirmed);
+ var left = await reconciliation.LinesAsync(Root, company, bank, onlyOpen: true);
+ Assert.IsTrue(left.All(l => l.Line.Status != StatementLineStatus.Matched));
+ var unknown = left.First(l => l.Line.Status == StatementLineStatus.ToMatch);
+ await reconciliation.IgnoreAsync(Root, company, unknown.Line.Id);
+ var position = await reconciliation.PositionAsync(Root, company, bank);
+ TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"Book {position.BookBalance:0.00}, to match {position.ToMatch}"));
+ Assert.AreEqual(0, position.ToMatch);
+ Assert.IsGreaterThan(0m, position.BookBalance, "The demo bank starts with the capital paid in.");
+ await AssertBalancedAsync(app.Services, company);
+ await app.StopAsync();
+ }
+ }
+
+ [TestMethod]
+ public async Task Reminders_AndCashFlow_AreComputed()
+ {
+ var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
+ await using (app)
+ {
+ await SeedAsync(app.Services, company);
+ var dunning = app.Services.GetRequiredService();
+ Assert.HasCount(3, await dunning.LevelsAsync(Root, company));
+ var proposal = await dunning.ProposalAsync(Root, company);
+ foreach (var p in proposal)
+ {
+ TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{p.PartyName}: {p.Items.Count} items {p.Overdue:0.00} level {p.Level?.Level} ({p.MaxDays} days)"));
+ }
+
+ Assert.IsNotEmpty(proposal);
+ var pdf = await dunning.PreviewAsync(Root, company, proposal[0].PartyId);
+ Assert.StartsWith("%PDF", Encoding.ASCII.GetString(pdf.Content, 0, 4));
+
+ var forecast = await app.Services.GetRequiredService().ForecastAsync(Root, company);
+ Assert.IsNotEmpty(forecast.Accounts);
+ Assert.IsGreaterThanOrEqualTo(13, forecast.Periods.Count);
+ var last = forecast.Periods[^1];
+ Assert.AreEqual(forecast.Opening + forecast.Periods.Sum(p => p.In - p.Out), last.Balance);
+ await app.StopAsync();
+ }
+ }
+
+ private static DateOnly Year => new(DateTime.Now.Year - 1, 1, 1);
+
+ private static DateOnly Next => DateOnly.FromDateTime(DateTime.Now).AddYears(1);
+
+ private static async Task BankAsync(IServiceProvider services, string company)
+ {
+ await using var uow = await services.GetRequiredService().CreateAsync(DatabaseScope.Company(company));
+ return (await uow.Repository().FindAsync(Query.For().Where(b => b.Code == DemoTreasurySeeder.BankCode)))!.Id;
+ }
+
+ private static async Task SeedAsync(IServiceProvider services, string company)
+ {
+ // The treasury is not in the trial: the tests use the code of every module (SPEC §8.3).
+ var activation = await services.GetRequiredService().ActivateAsync(Root, "KH-TEST-ALL-0000-9999");
+ Assert.IsTrue(activation.Succeeded, activation.Outcome);
+ await services.GetRequiredService().RunAsync(company, SeedKind.Demo);
+ var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
+ await services.GetRequiredService().SeedAsync(company, context);
+ await services.GetRequiredService().SeedAsync(company, context);
+ await services.GetRequiredService().SeedAsync(company, context);
+ await services.GetRequiredService().SeedAsync(company, context);
+ }
+
+ private static async Task AssertBalancedAsync(IServiceProvider services, string company)
+ {
+ var today = DateOnly.FromDateTime(DateTime.Now);
+ var balance = await services.GetRequiredService().TrialBalanceAsync(Root, company, new DateOnly(today.Year, 1, 1), today.AddYears(1));
+ Assert.IsTrue(balance.Balanced, $"Debit {balance.TotalDebit} credit {balance.TotalCredit}");
+ }
+}