The demo company gets a bank account with the capital paid in, collections and supplier payments (one customer pays only half), a RiBa remittance presented, credited and with one effect back unpaid, a draft remittance for the next weeks, a direct debit mandate, a CSV statement to reconcile with a rule for the bank fees, and a first reminder already sent. The seeder runs only when FIN is licensed and only once. The tests run the demo on a real instance: collections registered and cancelled, the CBI file written, the statement reconciled, reminders and cash flow, with the trial balance checked after every flow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
246 lines
14 KiB
C#
246 lines
14 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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<PaymentService>();
|
|
var remittances = app.Services.GetRequiredService<RemittanceService>();
|
|
var schedule = app.Services.GetRequiredService<ScheduleService>();
|
|
|
|
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<MandateService>().ListAsync(Root, company));
|
|
Assert.IsNotEmpty(await app.Services.GetRequiredService<DunningService>().HistoryAsync(Root, company));
|
|
Assert.IsNotEmpty(await app.Services.GetRequiredService<BankReconciliationService>().RulesAsync(Root, company));
|
|
await AssertBalancedAsync(app.Services, company);
|
|
|
|
// Run again, nothing changes.
|
|
await app.Services.GetRequiredService<DemoTreasurySeeder>().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<PaymentService>();
|
|
var schedule = app.Services.GetRequiredService<ScheduleService>();
|
|
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<ValidationFailedException>(() => 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<RemittanceService>();
|
|
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<BankReconciliationService>();
|
|
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<DunningService>();
|
|
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<CashFlowService>().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<long> BankAsync(IServiceProvider services, string company)
|
|
{
|
|
await using var uow = await services.GetRequiredService<IUnitOfWorkFactory>().CreateAsync(DatabaseScope.Company(company));
|
|
return (await uow.Repository<BankAccount, long>().FindAsync(Query.For<BankAccount>().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<ILicenseActivationService>().ActivateAsync(Root, "KH-TEST-ALL-0000-9999");
|
|
Assert.IsTrue(activation.Succeeded, activation.Outcome);
|
|
await services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
|
|
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
|
|
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, context);
|
|
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(company, context);
|
|
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(company, context);
|
|
await services.GetRequiredService<DemoTreasurySeeder>().SeedAsync(company, context);
|
|
}
|
|
|
|
private static async Task AssertBalancedAsync(IServiceProvider services, string company)
|
|
{
|
|
var today = DateOnly.FromDateTime(DateTime.Now);
|
|
var balance = await services.GetRequiredService<LedgerQueryService>().TrialBalanceAsync(Root, company, new DateOnly(today.Year, 1, 1), today.AddYears(1));
|
|
Assert.IsTrue(balance.Balanced, $"Debit {balance.TotalDebit} credit {balance.TotalCredit}");
|
|
}
|
|
}
|