Files
Khaemhat/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs
T
Alby96andClaude Opus 5.5 f8b72f4d17 feat: purchase and warehouse documents on the document screens (#55 #56 #58)
The document radars and records now serve /acquisti and /magazzino too:
supplier orders, receipts, supplier invoices and credit notes, self-invoices
and warehouse movements, with the supplier in place of the customer, the
supplier's number and date, the protocol and VAT date of registered invoices,
and reason and warehouses of a movement. Supplier invoices take their
protocol from the purchase numbering, refuse a second document with the same
supplier number in the same year and show price differences against their
order or receipt. The Italian pack advises the self-invoice a received
invoice needs (TD16-TD19, TD28) with its deadline, and the purchase service
drafts it with the ordinary rate. A credit note of an invoice now moves its
goods back instead of being skipped as already moved.

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

149 lines
9.4 KiB
C#

using Khaemhat.Application.Documents;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Purchases;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Fiscal.Italy;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Inventory;
/// <summary>
/// The purchases on a real instance (issues #55, #56, #58): order, receipt and invoice with protocol and VAT date,
/// the duplicate check, the price differences, the cost of the receipt corrected by the invoice, the self-invoice.
/// </summary>
[TestClass]
public sealed class PurchaseFlowTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
[TestMethod]
public async Task Invoice_GetsItsProtocol_RefusesDuplicates_AndCorrectsTheCostOfTheReceipt()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService<DocumentEngine>();
var copies = app.Services.GetRequiredService<DocumentCopyService>();
var purchases = app.Services.GetRequiredService<PurchaseService>();
var stock = app.Services.GetRequiredService<InventoryService>();
var vat22 = (await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(Root, company)).Single(t => t.Code == "22").Id;
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
var item = await InventoryFlowTests.ItemAsync(app, company, "RACC-20", "Raccordo 20 mm", null);
var day = new DateOnly(DateTime.Now.Year, 4, 1);
var order = await engine.NewAsync(Root, company, "OF");
order.Header.PartyId = supplier;
order.Header.DocumentDate = day;
order.Lines.Add(new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Raccordo", Quantity = 10m, Price = 2m, TaxCodeId = vat22 });
order = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, (await engine.SaveAsync(Root, company, order)).Header.Id);
Assert.IsNotNull(order.Header.DocumentNumber, "Supplier orders are numbered.");
var receipt = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseOrder, [order.Header.Id], "DDTF", day.AddDays(3));
receipt.Header.ExternalReference = "DDT 77";
receipt = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, receipt)).Header.Id);
Assert.AreEqual(2m, (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item).AverageCost);
// The invoice of the receipt costs 2.50 a piece: the difference shows, and the receipt takes its cost.
var invoice = await copies.MergeAsync(Root, company, DocumentFamily.PurchaseDocument, [receipt.Header.Id], "FF", day.AddDays(10));
var line = invoice.Lines.Single(l => l.Kind == DocumentLineKind.Item);
line.Price = 2.5m;
invoice = await engine.SaveAsync(Root, company, invoice);
var differences = await purchases.PriceDifferencesAsync(Root, company, invoice);
Assert.AreEqual((2m, 2.5m, 5m), (differences.Single().SourcePrice, differences[0].InvoicePrice, differences[0].Amount));
// Without the supplier's number and date the invoice is not registered.
invoice.Header.ExternalReference = null;
invoice = await engine.SaveAsync(Root, company, invoice);
var missing = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, invoice.Header.Id));
CollectionAssert.Contains(missing.Errors.ToArray(), "ExternalReference:" + DocumentErrors.SupplierNumberRequired);
invoice.Header.ExternalReference = "125/A";
invoice.Header.ExternalDate = day.AddDays(8);
invoice = await engine.SaveAsync(Root, company, invoice);
invoice = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, invoice.Header.Id);
Assert.AreEqual(1L, invoice.Header.VatProtocol);
Assert.AreEqual("1", invoice.Header.DocumentNumber);
Assert.AreEqual(day.AddDays(10), invoice.Header.VatDate, "The VAT date defaults to the registration.");
var row = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
Assert.AreEqual(10m, row.OnHand, "The invoice of a receipt does not load again.");
Assert.AreEqual(2.5m, row.AverageCost, "The invoice corrects the cost of the receipt.");
// The same number of the same supplier in the same year is refused.
var again = await engine.NewAsync(Root, company, "FF");
again.Header.PartyId = supplier;
again.Header.ExternalReference = "125/A";
again.Header.ExternalDate = day.AddDays(8);
again.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Free, Description = "Spese", Quantity = 1m, Price = 10m, TaxCodeId = vat22 });
var duplicate = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => engine.SaveAsync(Root, company, again));
CollectionAssert.Contains(duplicate.Errors.ToArray(), "ExternalReference:" + DocumentErrors.SupplierDuplicate);
await app.StopAsync();
}
}
[TestMethod]
public async Task ForeignServices_NeedASelfInvoice_ByThe15thOfTheNextMonth()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var engine = app.Services.GetRequiredService<DocumentEngine>();
var purchases = app.Services.GetRequiredService<PurchaseService>();
var parties = app.Services.GetRequiredService<PartyService>();
var taxes = await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(Root, company);
var outside = taxes.First(t => t.Nature is not null && t.Nature.StartsWith("N2", StringComparison.Ordinal)).Id;
var record = await parties.NewAsync(Root, company, PartyKind.Supplier);
record.Party.Name = "Cloud Services GmbH";
record.Party.SubjectType = SubjectType.EuCompany;
record.Party.CountryCode = "DE";
record.Party.VatNumber = "DE123456789";
var supplier = (await parties.SaveAsync(Root, company, record)).Party.Id;
var day = new DateOnly(DateTime.Now.Year, 5, 20);
var invoice = await engine.NewAsync(Root, company, "FF");
invoice.Header.PartyId = supplier;
invoice.Header.DocumentDate = day;
invoice.Header.ExternalReference = "INV-2026-0042";
invoice.Header.ExternalDate = day.AddDays(-2);
invoice.Lines.Add(new PurchaseDocumentLine { Kind = DocumentLineKind.Free, Description = "Abbonamento software maggio", Quantity = 1m, Price = 100m, TaxCodeId = outside });
invoice = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, (await engine.SaveAsync(Root, company, invoice)).Header.Id);
var advice = await purchases.AdviseAsync(Root, company, invoice);
Assert.AreEqual("AF17", advice!.DocumentTypeCode);
Assert.AreEqual(new DateOnly(day.Year, 6, 15), advice.Deadline);
Assert.AreEqual(invoice.Header.Id, (await purchases.PendingSelfInvoicesAsync(Root, company)).Single().Invoice.Id);
var self = await purchases.CreateSelfInvoiceAsync(Root, company, invoice.Header.Id, null);
Assert.AreEqual(DocumentKind.SelfInvoice, self.Header.Kind);
Assert.AreEqual("INV-2026-0042", self.Header.RelatedNumber);
Assert.AreEqual(taxes.Single(t => t.Code == "22").Id, self.Lines.Single().TaxCodeId, "The integration applies the ordinary rate.");
Assert.AreEqual(22m, self.Header.TaxAmount);
self = await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, self.Header.Id);
Assert.IsNotNull(self.Header.DocumentNumber);
Assert.IsEmpty(await purchases.PendingSelfInvoicesAsync(Root, company), "An integrated invoice no longer waits.");
await app.StopAsync();
}
}
[TestMethod]
public void ItalianRules_ChooseTheTypeOfTheSelfInvoice()
{
var rules = new SelfInvoiceRulesIt();
var day = new DateOnly(2026, 12, 3);
Assert.AreEqual("AF16", rules.Advise(new SelfInvoiceCase("IT", false, false, ["N6.3"], day))!.DocumentTypeCode);
Assert.IsNull(rules.Advise(new SelfInvoiceCase("IT", false, true, [], day)));
Assert.AreEqual("AF18", rules.Advise(new SelfInvoiceCase("FR", true, true, ["N3.2"], day))!.DocumentTypeCode);
Assert.AreEqual("AF19", rules.Advise(new SelfInvoiceCase("CH", false, true, [], day))!.DocumentTypeCode);
Assert.AreEqual("AF17", rules.Advise(new SelfInvoiceCase("US", false, false, [], day))!.DocumentTypeCode);
Assert.AreEqual(new DateOnly(2027, 1, 15), rules.Deadline("AF17", day));
Assert.AreEqual(day.AddDays(90), rules.Deadline("AF20", day));
}
}