Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP) become draft purchase invoices with supplier, items and tax codes matched, the file attached and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase invoices show price differences against the order and the self-invoice still to issue, with a pending list on the self-invoice screen. The opening stock import now writes an opening movement. The demo company gets purchases, an opening stock, a pending self-invoice and a stock take being counted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
171 lines
10 KiB
C#
171 lines
10 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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) => $"""
|
|
<?xml version="1.0" encoding="UTF-8"?>
|
|
<p:FatturaElettronica versione="FPR12" xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2">
|
|
<FatturaElettronicaHeader>
|
|
<DatiTrasmissione>
|
|
<IdTrasmittente><IdPaese>IT</IdPaese><IdCodice>01234567897</IdCodice></IdTrasmittente>
|
|
<ProgressivoInvio>00042</ProgressivoInvio><FormatoTrasmissione>FPR12</FormatoTrasmissione><CodiceDestinatario>0000000</CodiceDestinatario>
|
|
</DatiTrasmissione>
|
|
<CedentePrestatore>
|
|
<DatiAnagrafici>
|
|
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>01234567897</IdCodice></IdFiscaleIVA>
|
|
<Anagrafica><Denominazione>Ferramenta Piemontese S.r.l.</Denominazione></Anagrafica>
|
|
<RegimeFiscale>RF01</RegimeFiscale>
|
|
</DatiAnagrafici>
|
|
<Sede><Indirizzo>Via Roma</Indirizzo><NumeroCivico>12</NumeroCivico><CAP>10121</CAP><Comune>Torino</Comune><Provincia>TO</Provincia><Nazione>IT</Nazione></Sede>
|
|
</CedentePrestatore>
|
|
<CessionarioCommittente>
|
|
<DatiAnagrafici>
|
|
<IdFiscaleIVA><IdPaese>IT</IdPaese><IdCodice>02987654304</IdCodice></IdFiscaleIVA>
|
|
<Anagrafica><Denominazione>Azienda di prova</Denominazione></Anagrafica>
|
|
</DatiAnagrafici>
|
|
<Sede><Indirizzo>Corso Milano</Indirizzo><CAP>20121</CAP><Comune>Milano</Comune><Provincia>MI</Provincia><Nazione>IT</Nazione></Sede>
|
|
</CessionarioCommittente>
|
|
</FatturaElettronicaHeader>
|
|
<FatturaElettronicaBody>
|
|
<DatiGenerali>
|
|
<DatiGeneraliDocumento>
|
|
<TipoDocumento>{type}</TipoDocumento><Divisa>EUR</Divisa><Data>{date}</Data><Numero>{number}</Numero>
|
|
<ImportoTotaleDocumento>{total}</ImportoTotaleDocumento><Causale>Fornitura di marzo</Causale>
|
|
</DatiGeneraliDocumento>
|
|
</DatiGenerali>
|
|
<DatiBeniServizi>{lines}{summary}</DatiBeniServizi>
|
|
</FatturaElettronicaBody>
|
|
</p:FatturaElettronica>
|
|
""";
|
|
|
|
private const string Lines = """
|
|
<DettaglioLinee>
|
|
<NumeroLinea>1</NumeroLinea>
|
|
<CodiceArticolo><CodiceTipo>SKU</CodiceTipo><CodiceValore>VALV-01</CodiceValore></CodiceArticolo>
|
|
<Descrizione>Valvola a sfera 1/2</Descrizione><Quantita>10.00</Quantita><UnitaMisura>PZ</UnitaMisura><PrezzoUnitario>4.000000</PrezzoUnitario>
|
|
<ScontoMaggiorazione><Tipo>SC</Tipo><Percentuale>10.00</Percentuale></ScontoMaggiorazione>
|
|
<PrezzoTotale>36.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA>
|
|
</DettaglioLinee>
|
|
<DettaglioLinee>
|
|
<NumeroLinea>2</NumeroLinea><Descrizione>Spese di trasporto</Descrizione><PrezzoUnitario>15.00</PrezzoUnitario><PrezzoTotale>15.00</PrezzoTotale><AliquotaIVA>22.00</AliquotaIVA>
|
|
</DettaglioLinee>
|
|
""";
|
|
|
|
private const string Summary = """
|
|
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>51.00</ImponibileImporto><Imposta>11.22</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
|
|
""";
|
|
|
|
[TestMethod]
|
|
public async Task Import_AddsTheSupplier_MatchesItemsAndTaxes_AndRefusesTheSameInvoiceTwice()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var import = app.Services.GetRequiredService<PurchaseInvoiceImportService>();
|
|
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
|
var attachments = app.Services.GetRequiredService<AttachmentService>();
|
|
var parties = app.Services.GetRequiredService<PartyService>();
|
|
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("<FatturaElettronica>"))]);
|
|
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<IIncomingInvoiceRules>(rules);
|
|
}
|
|
|
|
private static async Task Add(ZipArchive archive, string name, byte[] content)
|
|
{
|
|
await using var stream = archive.CreateEntry(name).Open();
|
|
await stream.WriteAsync(content);
|
|
}
|
|
}
|