Files
Khaemhat/tests/Khaemhat.Web.Tests/Tables/CompanyTablesTests.cs
T
Alby96andClaude Opus 5.5 321aae7e81 feat: provinces and municipalities from the ISTAT list in the base data (#45)
New companies now get the 110 provinces and 7,894 municipalities in force
(ISTAT list of 26/02/2026, CC BY 4.0), so the tax code calculation and the
municipality lookups work without loading anything. The list lives in the
Italian pack behind a new IPlaceDirectory feature and is added by the base
seeder like the rest of the base data: missing codes only, never touching
existing rows. The pack data version moves to IT 2026.3 so existing
companies receive the lists at the next start.

Postal codes are left out: the only candidate source (comuni-json) has no
licence for them and stops at 2020 (ADR 0028).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:07:12 +01:00

233 lines
14 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Tables;
/// <summary>Company tables, profile, fiscal years and base data on a real instance (issues #38, #39, #45).</summary>
[TestClass]
public sealed class CompanyTablesTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task BaseData_IsLoadedAtStart_AndRunningItAgainAddsNothing()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var services = app.Services;
var tables = services.GetRequiredService<TableService>();
var pack = services.GetRequiredService<FiscalPackCatalog>().ForCountry("IT");
var taxCodes = await tables.AllAsync<TaxCode>(Root, company);
Assert.HasCount(pack.TaxCodes.BaseCodes.Count, taxCodes);
var reverseCharge = taxCodes.Single(t => t.Code == "RC17");
Assert.AreEqual((TaxCodeKind.ReverseCharge, "N6.9"), (reverseCharge.Kind, reverseCharge.Nature));
var countries = await tables.AllAsync<Country>(Root, company);
Assert.AreEqual(27, countries.Count(c => c.EuMember && c.Code != "XI"), "The 27 member states.");
Assert.AreEqual("EL", countries.Single(c => c.Code == "GR").VatPrefix);
Assert.AreEqual("EUR", countries.Single(c => c.Code == "BG").CurrencyCode);
var invoice = (await tables.AllAsync<DocumentType>(Root, company)).Single(d => d.Code == "FI");
var numerators = await tables.AllAsync<DocumentNumerator>(Root, company);
Assert.AreEqual(("TD01", "FAT"), (invoice.EInvoiceType, numerators.Single(n => n.Id == invoice.NumeratorId).Code));
Assert.IsFalse(numerators.Single(n => n.Code == "FAT").GapsAllowed);
await using (var uow = await services.GetRequiredService<IUnitOfWorkFactory>().CreateAsync(DatabaseScope.Company(company)))
{
var terms = (await uow.Repository<PaymentTerm, long>().FindAsync(Query.For<PaymentTerm>().Where(t => t.Code == "RB306090")))!;
var lines = (await uow.Repository<PaymentTermLine, long>().ListAsync(Query.For<PaymentTermLine>().Where(l => l.PaymentTermId == terms.Id))).Items;
Assert.HasCount(3, lines);
Assert.AreEqual(100m, lines.Sum(l => l.Percent));
}
var years = await services.GetRequiredService<FiscalYearService>().ListAsync(Root, company);
Assert.HasCount(1, years);
Assert.HasCount(12, years[0].Periods);
var runner = services.GetRequiredService<SeedRunner>();
Assert.AreEqual("IT 2026.3", await runner.VersionAsync(company));
var again = await runner.UpdateBaseAsync(Root, company);
Assert.AreEqual(0, again.Total, string.Join(", ", again.Added.Select(a => a.Key + "=" + a.Value)));
await app.StopAsync();
}
}
[TestMethod]
public async Task Save_AppliesTheRulesOfTheTableAndOfTheFiscalPack()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var tables = app.Services.GetRequiredService<TableService>();
var noNature = new TaxCode { Code = "zero", Description = "Senza natura", Rate = 0 };
var problems = await tables.ValidateAsync(Root, company, noNature);
Assert.AreEqual("ZERO", noNature.Code, "Codes are upper case.");
Assert.IsTrue(problems.Any(p => p is { Field: "Nature", Code: "fiscal.tax.nature-required", IsWarning: false }));
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => tables.SaveAsync(Root, company, noNature));
CollectionAssert.Contains(refused.Errors.ToList(), "Nature:fiscal.tax.nature-required");
var duplicate = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => tables.SaveAsync(Root, company, new TaxCode { Code = "22", Description = "Doppio", Rate = 22 }));
CollectionAssert.Contains(duplicate.Errors.ToList(), "Code:" + TableService.CodeDuplicate);
var exempt = await tables.SaveAsync(Root, company, new TaxCode { Code = "ESE10B", Description = "Esente art. 10 n. 1", Rate = 0, Nature = "n4", LegalReference = "Art. 10 DPR 633/72" });
Assert.AreEqual((TaxCodeKind.Exempt, "N4"), (exempt.Kind, exempt.Nature));
var page = await tables.ListAsync<TaxCode>(Root, company, new ListQuery { Search = "ESE10B" });
Assert.AreEqual(1, page.Total, "The cache is refreshed after a save.");
var badIban = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => tables.SaveAsync(Root, company, new BankAccount { Code = "B1", Description = "Banca", Iban = "IT00X0000000000000000000000" }));
CollectionAssert.Contains(badIban.Errors.ToList(), "Iban:" + TableCatalog.IbanInvalid);
var account = await tables.SaveAsync(Root, company, new BankAccount { Code = "B1", Description = "Banca", Iban = "it60 x054 2811 1010 0000 0123 456", IsDefault = true });
var second = await tables.SaveAsync(Root, company, new BankAccount { Code = "B2", Description = "Altra banca", IsDefault = true });
var accounts = await tables.AllAsync<BankAccount>(Root, company);
Assert.AreEqual("IT60X0542811101000000123456", account.Iban);
Assert.AreEqual(second.Id, accounts.Single(a => a.IsDefault).Id, "Only one default account.");
var numerator = new DocumentNumerator { Code = "FAT", Description = "Fatture anno prossimo", Kind = NumeratorKind.SalesInvoice, Year = 2099, Format = "{number}/{year}", GapsAllowed = true };
await tables.SaveAsync(Root, company, numerator);
Assert.IsFalse(numerator.GapsAllowed, "Invoices are numbered without gaps.");
await app.StopAsync();
}
}
[TestMethod]
public async Task Delete_DisablesRowsInUse_AndCsvRoundTrips()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var tables = app.Services.GetRequiredService<TableService>();
var transfer = (await tables.AllAsync<PaymentMethod>(Root, company)).Single(m => m.Code == "BON");
Assert.AreEqual(TableDeleteOutcome.Disabled, await tables.DeleteAsync<PaymentMethod>(Root, company, transfer.Id), "Payment terms use it.");
Assert.IsTrue((await tables.GetAsync<PaymentMethod>(Root, company, transfer.Id))!.Disabled);
Assert.IsFalse((await tables.ActiveAsync<PaymentMethod>(Root, company)).Any(m => m.Code == "BON"));
var pagopa = (await tables.AllAsync<PaymentMethod>(Root, company)).Single(m => m.Code == "PAGOPA");
Assert.AreEqual(TableDeleteOutcome.Deleted, await tables.DeleteAsync<PaymentMethod>(Root, company, pagopa.Id));
using var export = new MemoryStream();
var written = await tables.ExportCsvAsync<UnitOfMeasure>(Root, company, export);
var exported = Encoding.UTF8.GetString(export.ToArray()).TrimStart('');
var header = exported[..exported.IndexOf('\r', StringComparison.Ordinal)].Split(';');
var box = string.Join(';', header.Select(h => h switch { "code" => "BOX", "description" => "Scatoloni", _ => string.Empty }));
var csv = exported.Replace("Chilogrammi", "Chili", StringComparison.Ordinal) + box + "\r\n";
using var import = new MemoryStream(Encoding.UTF8.GetBytes(csv));
var result = await tables.ImportCsvAsync<UnitOfMeasure>(Root, company, import);
Assert.IsTrue(result.Succeeded, string.Join(", ", result.Errors));
Assert.AreEqual((1, written), (result.Inserted, result.Updated));
var units = await tables.AllAsync<UnitOfMeasure>(Root, company);
Assert.AreEqual("Chili", units.Single(u => u.Code == "KG").Description);
Assert.AreEqual(3, units.Single(u => u.Code == "KG").Decimals);
using var bad = new MemoryStream(Encoding.UTF8.GetBytes("code;description;decimals\nX;Ics;tre\nY;;0\n"));
var refused = await tables.ImportCsvAsync<UnitOfMeasure>(Root, company, bad);
Assert.IsFalse(refused.Succeeded);
CollectionAssert.AreEquivalent(
new[] { new TableImportError(2, "decimals", TableService.CsvBadValue), new TableImportError(3, "description", TableService.DescriptionRequired) },
refused.Errors.ToArray());
Assert.IsFalse((await tables.AllAsync<UnitOfMeasure>(Root, company)).Any(u => u.Code == "Y"), "Nothing is saved when a row is wrong.");
await app.StopAsync();
}
}
[TestMethod]
public async Task LockedMonths_RefuseDates_AndTheNextYearFollowsTheLast()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var years = app.Services.GetRequiredService<FiscalYearService>();
var current = (await years.ListAsync(Root, company)).Single();
var first = current.Periods[0];
Assert.AreEqual(PeriodState.Open, await years.CheckAsync(company, first.StartDate, PeriodUse.Vat));
await years.SetLockedAsync(Root, company, first.Id, locked: true);
Assert.AreEqual(PeriodState.Locked, await years.CheckAsync(company, first.EndDate, PeriodUse.NoVat));
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => years.DemandOpenAsync(company, first.StartDate, PeriodUse.NoVat));
CollectionAssert.Contains(refused.Errors.ToList(), "fiscal.date.locked");
await years.SetLockedAsync(Root, company, first.Id, locked: false);
Assert.AreEqual(PeriodState.Open, await years.CheckAsync(company, first.StartDate, PeriodUse.Vat));
var next = await years.CreateNextAsync(Root, company, current.Year.StartDate);
Assert.AreEqual(current.Year.EndDate.AddDays(1), next.Year.StartDate);
Assert.AreEqual(PeriodState.NoYear, await years.CheckAsync(company, next.Year.EndDate.AddDays(1), PeriodUse.NoVat));
await app.StopAsync();
}
}
[TestMethod]
public async Task Profile_StartsFromTheInstanceDefaults_AndChecksTheItalianIdentifiers()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var profiles = app.Services.GetRequiredService<CompanyProfileService>();
var profile = await profiles.GetAsync(Root, company);
Assert.AreEqual((0L, "IT", "RF01", VatPeriodicity.Monthly), (profile.Id, profile.Country, profile.TaxRegime, profile.VatPeriodicity));
profile.LegalName = "Prova S.r.l.";
profile.VatNumber = "01234567890";
profile.RecipientCode = "abc";
profile.ProvinceCode = "milano";
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => profiles.SaveAsync(Root, company, profile));
CollectionAssert.IsSubsetOf(
new[] { "VatNumber:" + TableCatalog.VatNumberInvalid, "RecipientCode:" + CompanyProfileService.RecipientCodeInvalid, "ProvinceCode:" + CompanyProfileService.TwoLettersRequired },
refused.Errors.ToList());
profile.VatNumber = "IT 01234567897";
profile.RecipientCode = "abc1234";
profile.ProvinceCode = "mi";
var saved = await profiles.SaveAsync(Root, company, profile);
Assert.AreNotEqual(0L, saved.Id);
Assert.AreEqual(("01234567897", "ABC1234", "MI"), (saved.VatNumber, saved.RecipientCode, saved.ProvinceCode));
saved.Country = "ZZ";
var unknown = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => profiles.SaveAsync(Root, company, saved));
CollectionAssert.Contains(unknown.Errors.ToList(), "Country:" + CompanyProfileService.CountryUnknown);
await app.StopAsync();
}
}
[TestMethod]
public async Task PaymentTermLines_AreReplacedTogether_OrNotAtAll()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var tables = app.Services.GetRequiredService<TableService>();
var terms = app.Services.GetRequiredService<PaymentTermService>();
var term = (await tables.AllAsync<PaymentTerm>(Root, company)).Single(t => t.Code == "RB3060FM");
Assert.HasCount(2, await terms.LinesAsync(Root, company, term.Id));
var saved = await terms.SaveLinesAsync(Root, company, term.Id,
[
new() { Days = 30, EndOfMonth = true, Percent = 40m },
new() { Days = 60, EndOfMonth = true, Percent = 30m },
new() { Days = 90, EndOfMonth = true, Percent = 30m },
]);
CollectionAssert.AreEqual(new[] { 1, 2, 3 }, saved.Select(l => l.Number).ToArray());
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
terms.SaveLinesAsync(Root, company, term.Id, [new() { Days = 30, Percent = 90m }]));
CollectionAssert.Contains(refused.Errors.ToList(), PaymentTermService.LinesField + ":" + PaymentTermService.PercentTotal);
Assert.HasCount(3, await terms.LinesAsync(Root, company, term.Id), "Nothing changed.");
}
}
}