Files
Khaemhat/tests/Khaemhat.Web.Tests/Parties/PartyServiceTests.cs
T
Alby96andClaude Opus 5.5 3401271483 feat: parties with radar, record, checks, VIES and demo data (#41)
Customers, suppliers, prospects and leads live in one parties archive
with a kind and a subject type (ADR 0029). A customer that also supplies
carries is_also_supplier, so it shows in both radars with one code.

- Three radars (/anagrafiche/clienti, /fornitori, /contatti) with search,
  quick filters and bulk disable/enable; the record has eight tabs
  (main data, addresses, contacts, terms, fiscal and SDI, banks, notes and
  attachments, history) on the MasterDataPage base.
- PartyService saves the whole record in one transaction, checks it with
  the fiscal pack (VAT number, tax code, recipient code, country), treats
  a duplicate VAT number or a consumer without tax code as warnings, fills
  the default recipient code, runs VIES after commit for EU companies, and
  converts prospects/leads (new customer code, old one kept as
  previous_code) and suppliers (become customers that also supply).
- Delete falls back to disable when the party is referenced.
- DemoPartiesSeeder adds 3 salespeople and 21 parties with fictitious but
  formally valid identifiers; SeedAsync now runs demo seeders when asked.
- Test host accepts service overrides so VIES can be stubbed.

Docs: ADR 0029, wiki Anagrafiche and demo data pages, regenerated data
model, CHANGELOG and STATUS.

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

252 lines
15 KiB
C#

using System.Globalization;
using System.Net;
using System.Text;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Http;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Parties;
/// <summary>The parties on a real instance (issue #41): codes, details, rules, conversion, delete, VIES.</summary>
[TestClass]
public sealed class PartyServiceTests
{
private const string ValidVat = "01234567897";
private const string OtherVat = "02345678904";
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
private static readonly int Year = DateTime.Now.Year;
[TestMethod]
public async Task Customer_GetsTheCustomerCode_AndItsDetailsAreSavedWithIt()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var parties = app.Services.GetRequiredService<PartyService>();
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
Assert.AreEqual("IT", record.Party.CountryCode);
record.Party.Name = " Rossi Impianti S.r.l. ";
record.Party.VatNumber = "IT " + ValidVat;
record.Party.City = "Torino";
record.Fiscal.RecipientCode = "abc1234";
record.Sales.Discount1 = 5;
record.Addresses.Add(new PartyAddress { Name = "Cantiere Lingotto", Kind = PartyAddressKind.Site, City = "Torino", Province = "to" });
record.Contacts.Add(new PartyContact { Name = "Mario Rossi", Role = "Acquisti", Email = "acquisti@rossi.example", IsDefault = true });
record.Contacts.Add(new PartyContact { Name = "Anna Bianchi", IsDefault = true });
record.BankAccounts.Add(new PartyBankAccount { Iban = "it60 x054 2811 1010 0000 0123 456" });
var saved = await parties.SaveAsync(Root, company, record);
Assert.AreEqual("C000001", saved.Party.Code);
Assert.AreEqual("Rossi Impianti S.r.l.", saved.Party.Name);
Assert.AreEqual(ValidVat, saved.Party.VatNumber);
Assert.AreEqual("ABC1234", saved.Fiscal.RecipientCode);
Assert.AreEqual(5m, saved.Sales.Discount1);
Assert.AreEqual("TO", saved.Addresses.Single().Province);
Assert.AreEqual(1, saved.Contacts.Count(c => c.IsDefault), "One main contact.");
Assert.AreEqual(("05428", "11101"), (saved.BankAccounts[0].BankCode, saved.BankAccounts[0].BranchCode));
// Changing the lists: a contact removed, one added; the party keeps its code.
saved.Contacts.RemoveAt(1);
saved.Contacts.Add(new PartyContact { Name = "Luca Verdi", Role = "Amministrazione" });
saved.Party.Phone = "011 123456";
var again = await parties.SaveAsync(Root, company, saved);
CollectionAssert.AreEqual(new[] { "Mario Rossi", "Luca Verdi" }, again.Contacts.Select(c => c.Name).ToArray());
Assert.AreEqual("C000001", again.Party.Code);
Assert.IsNotEmpty(await parties.HistoryAsync(Root, company, again.Party.Id));
var list = await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery { Search = "rossi" });
Assert.AreEqual("C000001", list.Items.Single().Code);
Assert.AreEqual(ValidVat, list.Items[0].Identifier);
Assert.IsEmpty((await parties.ListAsync(Root, company, PartyArchive.Suppliers, new ListQuery())).Items);
await app.StopAsync();
}
}
[TestMethod]
public async Task Save_RefusesWhatTheRulesDoNotAllow()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var parties = app.Services.GetRequiredService<PartyService>();
async Task<string[]> ErrorsAsync(Action<PartyRecord> fill, PartyKind kind = PartyKind.Customer)
{
var record = await parties.NewAsync(Root, company, kind);
record.Party.Name = "Prova";
fill(record);
var ex = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => parties.SaveAsync(Root, company, record));
return [.. ex.Errors];
}
CollectionAssert.AreEquivalent(new[] { "Name:" + PartyService.NameRequired, "VatNumber:" + PartyService.VatNumberRequired }, await ErrorsAsync(r => r.Party.Name = " "));
CollectionAssert.Contains(await ErrorsAsync(r => r.Party.VatNumber = "01234567890"), "VatNumber:" + TableCatalog.VatNumberInvalid);
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Fiscal.RecipientCode = "AB12"; }), "Fiscal.RecipientCode:fiscal.recipient.business-length");
CollectionAssert.Contains(
await ErrorsAsync(r => { r.Party.SubjectType = SubjectType.PublicAdministration; r.Party.TaxCode = "80012345678"; }),
"Fiscal.RecipientCode:fiscal.recipient.required");
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.SubjectType = SubjectType.Person; r.Party.TaxCode = "RSSMRA80A01L219X"; }), "TaxCode:" + PartyService.TaxCodeInvalid);
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.SubjectType = SubjectType.EuCompany; r.Party.VatNumber = "123456789"; }), "CountryCode:" + PartyService.CountryNotEu);
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Party.Email = "non-una-mail"; }), "Email:" + TableCatalog.EmailInvalid);
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Sales.Discount1 = 120; }), "Sales.Discount1:" + TableCatalog.PercentRange);
CollectionAssert.Contains(
await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.BankAccounts.Add(new PartyBankAccount { Iban = "IT00X0542811101000000123456" }); }),
"BankAccounts.0.Iban:" + TableCatalog.IbanInvalid);
CollectionAssert.Contains(
await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Fiscal.IntentActive = true; }),
"Fiscal.IntentNumber:" + PartyService.IntentIncomplete);
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = ValidVat; r.Contacts.Add(new PartyContact()); }), "Contacts.0.Name:" + PartyService.DetailRequired);
// A private customer: recipient code proposed, the missing tax code is only a warning.
var person = await parties.NewAsync(Root, company, PartyKind.Customer);
person.Party.SubjectType = SubjectType.Person;
person.Party.LastName = "Esposito";
person.Party.FirstName = "Mario";
var warnings = await parties.ValidateAsync(Root, company, person);
Assert.AreEqual(PartyService.TaxCodeMissing, warnings.Single().Code);
Assert.IsTrue(warnings[0].IsWarning);
var saved = await parties.SaveAsync(Root, company, person);
Assert.AreEqual("Esposito Mario", saved.Party.Name);
Assert.AreEqual("0000000", saved.Fiscal.RecipientCode);
// A lead needs nothing but a name; a manual code is refused when the mask does not allow it.
var lead = await parties.NewAsync(Root, company, PartyKind.Lead);
lead.Party.Name = "Contatto fiera";
Assert.AreEqual($"L{Year}-0001", (await parties.SaveAsync(Root, company, lead)).Party.Code);
await app.Services.GetRequiredService<CodeRuleService>().SaveAsync(Root, company, [new CodeRule("customers", "C{seq:000000}", AllowManual: false)]);
CollectionAssert.Contains(await ErrorsAsync(r => { r.Party.VatNumber = OtherVat; r.Party.Code = "MIO"; }), "Code:" + CodeRuleService.ManualNotAllowed);
await app.StopAsync();
}
}
[TestMethod]
public async Task Kinds_HaveTheirCodesAndArchives_AndLeadsBecomeCustomers()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var parties = app.Services.GetRequiredService<PartyService>();
var supplier = await NewAsync(parties, company, PartyKind.Supplier, "Metalli Nord S.p.A.", ValidVat);
Assert.AreEqual("F000001", supplier.Party.Code);
Assert.AreEqual(supplier.Party.Code, (await parties.SearchAsync(Root, company, PartyArchive.Suppliers, "metalli")).Single().Code);
var prospect = await NewAsync(parties, company, PartyKind.Prospect, "Hotel Belvedere", null);
Assert.AreEqual($"L{Year}-0001", prospect.Party.Code);
Assert.HasCount(1, (await parties.ListAsync(Root, company, PartyArchive.Contacts, new ListQuery())).Items);
var customer = await parties.ConvertToCustomerAsync(Root, company, prospect.Party.Id);
Assert.AreEqual(PartyKind.Customer, customer.Party.Kind);
Assert.AreEqual("C000001", customer.Party.Code);
Assert.AreEqual($"L{Year}-0001", customer.Party.PreviousCode);
Assert.IsEmpty((await parties.ListAsync(Root, company, PartyArchive.Contacts, new ListQuery())).Items);
var again = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => parties.ConvertToCustomerAsync(Root, company, customer.Party.Id));
Assert.AreEqual("Kind:" + PartyService.AlreadyCustomer, again.Errors.Single());
// A supplier that starts buying keeps its code and shows in both archives.
var both = await parties.ConvertToCustomerAsync(Root, company, supplier.Party.Id);
Assert.AreEqual("F000001", both.Party.Code);
Assert.IsTrue(both.Party.IsCustomer && both.Party.IsSupplier);
Assert.HasCount(2, (await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery())).Items);
Assert.HasCount(1, (await parties.ListAsync(Root, company, PartyArchive.Suppliers, new ListQuery())).Items);
// The same VAT number twice is allowed (branches), with a warning.
var twin = await parties.NewAsync(Root, company, PartyKind.Customer);
twin.Party.Name = "Metalli Nord - filiale";
twin.Party.VatNumber = ValidVat;
Assert.AreEqual(PartyService.VatNumberDuplicate, (await parties.ValidateAsync(Root, company, twin)).Single().Code);
await app.StopAsync();
}
}
[TestMethod]
public async Task Delete_RemovesAPartyNeverUsed_AndDisablingHidesIt()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var parties = app.Services.GetRequiredService<PartyService>();
var first = await NewAsync(parties, company, PartyKind.Customer, "Bianchi & Figli S.n.c.", ValidVat);
var second = await NewAsync(parties, company, PartyKind.Customer, "Gallo Ferramenta", OtherVat);
Assert.AreEqual(1, await parties.SetDisabledAsync(Root, company, [second.Party.Id, second.Party.Id], true));
Assert.IsEmpty(await parties.SearchAsync(Root, company, PartyArchive.Customers, "gallo"), "Disabled parties are not proposed.");
var active = await parties.ListAsync(Root, company, PartyArchive.Customers, new ListQuery { Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")] });
Assert.AreEqual(first.Party.Code, active.Items.Single().Code);
Assert.AreEqual(PartyDeleteOutcome.Deleted, await parties.DeleteAsync(Root, company, first.Party.Id));
Assert.IsNull(await parties.GetAsync(Root, company, first.Party.Id));
Assert.AreEqual("C000003", (await NewAsync(parties, company, PartyKind.Customer, "Nuovo", ValidVat)).Party.Code, "Codes are not reused.");
await app.StopAsync();
}
}
[TestMethod]
public async Task EuParty_IsCheckedOnVies_WhenSaved_AndTheOutcomeIsKept()
{
var handler = new ViesStub();
var (app, _, company) = await TestInstance.StartAsync(
services => services.AddHttpClient<ViesClient>().ConfigurePrimaryHttpMessageHandler(() => handler), CancellationToken.None);
await using (app)
{
var parties = app.Services.GetRequiredService<PartyService>();
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
record.Party.Name = "Alpenbau GmbH";
record.Party.SubjectType = SubjectType.EuCompany;
record.Party.CountryCode = "DE";
record.Party.VatNumber = "DE 123456789";
var saved = await parties.SaveAsync(Root, company, record);
Assert.AreEqual("123456789", saved.Party.VatNumber);
Assert.AreEqual("XXXXXXX", saved.Fiscal.RecipientCode);
Assert.AreEqual(VatCheckStatus.Valid, saved.Party.VatCheck);
Assert.IsNotNull(saved.Party.VatCheckedAt);
Assert.AreEqual("/taxation_customs/vies/rest-api/ms/DE/vat/123456789", handler.Paths.Single());
// Saved again without changes: no new call. With the option off nothing is asked.
await parties.SaveAsync(Root, company, saved);
Assert.HasCount(1, handler.Paths);
await app.Services.GetRequiredService<AutoFillService>().SaveOptionsAsync(Root, company, new Dictionary<string, bool> { [AutoFillService.Vies] = false });
var other = await parties.NewAsync(Root, company, PartyKind.Customer);
other.Party.Name = "Nordic Pipes";
other.Party.SubjectType = SubjectType.EuCompany;
other.Party.CountryCode = "FR";
other.Party.VatNumber = "12345678901";
Assert.AreEqual(VatCheckStatus.None, (await parties.SaveAsync(Root, company, other)).Party.VatCheck);
Assert.HasCount(1, handler.Paths);
// The action VIES asks anyway.
Assert.AreEqual(ViesStatus.Valid, (await parties.CheckVatAsync(Root, company, other.Party.Id))!.Status);
Assert.HasCount(2, handler.Paths);
await app.StopAsync();
}
}
private static async Task<PartyRecord> NewAsync(PartyService parties, string company, PartyKind kind, string name, string? vat)
{
var record = await parties.NewAsync(Root, company, kind);
record.Party.Name = name;
record.Party.VatNumber = vat;
return await parties.SaveAsync(Root, company, record);
}
private sealed class ViesStub : HttpMessageHandler
{
public List<string> Paths { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Paths.Add(request.RequestUri!.AbsolutePath);
var body = string.Create(CultureInfo.InvariantCulture, $$"""{"isValid":true,"requestDate":"2026-11-12T10:00:00.000Z","userError":"VALID","name":"---"}""");
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") });
}
}
}