using System.IO.Compression;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Purchases;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Files;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Inventory;
///
/// The import of supplier e-invoices on a real instance (issue #57): the supplier is added from the file, the items found
/// by code, the tax codes by rate and nature; the draft keeps the file; the same invoice is not registered twice; a ZIP
/// holds several files.
///
[TestClass]
public sealed class PurchaseImportTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
private static string Invoice(string type, string number, string date, string lines, string summary, string total) => $"""
IT01234567897
00042FPR120000000
IT01234567897
Ferramenta Piemontese S.r.l.
RF01
Via Roma1210121TorinoTOIT
IT02987654304
Azienda di prova
Corso Milano20121MilanoMIIT
{type}EUR{date}{number}
{total}Fornitura di marzo
{lines}{summary}
""";
private const string Lines = """
1
SKUVALV-01
Valvola a sfera 1/210.00PZ4.000000
SC10.00
36.0022.00
2Spese di trasporto15.0015.0022.00
""";
private const string Summary = """
22.0051.0011.22I
""";
[TestMethod]
public async Task Import_AddsTheSupplier_MatchesItemsAndTaxes_AndRefusesTheSameInvoiceTwice()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
var import = app.Services.GetRequiredService();
var engine = app.Services.GetRequiredService();
var attachments = app.Services.GetRequiredService();
var parties = app.Services.GetRequiredService();
var item = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null);
var year = DateTime.Now.Year;
var xml = Encoding.UTF8.GetBytes(Invoice("TD01", "FT/123", $"{year}-03-15", Lines, Summary, "62.22"));
var reading = await import.ReadAsync(Root, company, [("IT01234567897_00042.xml", xml)]);
Assert.IsEmpty(reading.Rejected);
var candidate = reading.Invoices.Single();
Assert.AreEqual(("FF", null, false, 62.22m), (candidate.DocumentTypeCode, candidate.SupplierId, candidate.Duplicate, candidate.ComputedTotal));
Assert.IsEmpty(candidate.Problems);
var done = (await import.ImportAsync(Root, company, reading.Invoices)).Single();
Assert.IsNull(done.Error);
Assert.IsTrue(done.SupplierCreated);
Assert.IsEmpty(done.Warnings);
var record = done.Record!;
Assert.AreEqual((DocumentKind.PurchaseInvoice, DocumentStatus.Draft, "FT/123", new DateOnly(year, 3, 15)),
(record.Header.Kind, record.Header.Status, record.Header.ExternalReference, record.Header.ExternalDate));
Assert.AreEqual(62.22m, record.Header.TotalAmount);
var valve = record.Lines.Single(l => l.Kind == DocumentLineKind.Item);
Assert.AreEqual((item, 10m, 4m, "10"), (valve.ItemId!.Value, valve.Quantity, valve.Price, valve.DiscountFormula));
Assert.AreEqual(DocumentLineKind.Free, record.Lines.Single(l => l.Description == "Spese di trasporto").Kind);
var supplier = (await parties.GetAsync(Root, company, record.Header.PartyId!.Value))!.Party;
Assert.AreEqual(("Ferramenta Piemontese S.r.l.", "01234567897", PartyKind.Supplier, "Torino", "TO"),
(supplier.Name, supplier.VatNumber, supplier.Kind, supplier.City, supplier.Province));
var files = await attachments.ListAsync(Root, company, DocumentPrintService.EntityOf(DocumentFamily.PurchaseDocument), record.Header.Id);
Assert.AreEqual((AttachmentKind.EInvoice, "IT01234567897_00042.xml"), (files.Single().Kind, files[0].FileName));
// The same file again: the supplier is known and the invoice is a duplicate.
var again = (await import.ReadAsync(Root, company, [("IT01234567897_00042.xml", xml)])).Invoices.Single();
Assert.AreEqual((supplier.Id, true, false), (again.SupplierId!.Value, again.Duplicate, again.CanImport));
CollectionAssert.Contains(again.Problems.ToArray(), PurchaseInvoiceImportService.DuplicateProblem);
// A ZIP with a credit note, a self-invoice the company sent itself and a stray file.
var credit = Encoding.UTF8.GetBytes(Invoice("TD04", "NC/7", $"{year}-03-20", Lines, Summary, "62.22"));
var self = Encoding.UTF8.GetBytes(Invoice("TD17", "AF/1", $"{year}-03-21", Lines, Summary, "62.22"));
using var zip = new MemoryStream();
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
{
await Add(archive, "nc.xml", credit);
await Add(archive, "af.xml", self);
await Add(archive, "leggimi.txt", Encoding.UTF8.GetBytes("nothing"));
}
var zipped = await import.ReadAsync(Root, company, [("marzo.zip", zip.ToArray()), ("rotto.xml", Encoding.UTF8.GetBytes(""))]);
Assert.AreEqual("rotto.xml", zipped.Rejected.Single().FileName);
Assert.HasCount(2, zipped.Invoices);
var note = zipped.Invoices.Single(i => i.Invoice.Number == "NC/7");
Assert.AreEqual(("NCF", supplier.Id), (note.DocumentTypeCode, note.SupplierId!.Value));
var unsupported = zipped.Invoices.Single(i => i.Invoice.Number == "AF/1");
Assert.IsFalse(unsupported.CanImport);
CollectionAssert.Contains(unsupported.Problems.ToArray(), PurchaseInvoiceImportService.UnsupportedType);
var results = await import.ImportAsync(Root, company, zipped.Invoices);
Assert.AreEqual(DocumentKind.PurchaseCreditNote, results.Single(r => r.Candidate == note).Record!.Header.Kind);
Assert.AreEqual(PurchaseInvoiceImportService.UnsupportedType, results.Single(r => r.Candidate == unsupported).Error);
// Confirmed, the imported invoice takes its protocol like one typed.
var confirmed = await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseDocument, record.Header.Id);
Assert.IsNotNull(confirmed.Header.VatProtocol);
await app.StopAsync();
}
}
[TestMethod]
public void ItalianRules_RegisterInvoicesAndCreditNotes()
{
var rules = new Khaemhat.Fiscal.Italy.IncomingInvoiceRulesIt();
Assert.AreEqual("FF", rules.DocumentTypeCode("TD01"));
Assert.AreEqual("FF", rules.DocumentTypeCode("td24"));
Assert.AreEqual("NCF", rules.DocumentTypeCode("TD04"));
Assert.IsNull(rules.DocumentTypeCode("TD17"));
Assert.IsInstanceOfType(rules);
}
private static async Task Add(ZipArchive archive, string name, byte[] content)
{
await using var stream = archive.CreateEntry(name).Open();
await stream.WriteAsync(content);
}
}