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>
This commit is contained in:
1 parent
eb301fa570
commit
ced689b297
31 files changed
+3478
-110
No files matched your search
@@ -81,6 +81,7 @@ public sealed class MappingTests
|
||||
"sale_quotations", "sale_quotation_lines", "sale_orders", "sale_order_lines", "sale_documents", "sale_document_lines",
|
||||
"purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines",
|
||||
"document_links", "document_tax_summaries", "document_installments",
|
||||
"inventory_entries", "inventory_entry_lines", "item_balances", "stock_takes", "stock_take_lines",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
@@ -148,13 +148,14 @@ public sealed class ImportServiceTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OpeningStock_IsOnlyChecked_UntilTheStockEntriesExist()
|
||||
public async Task OpeningStock_LoadsTheWarehouse_WithAnOpeningMovement()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var imports = app.Services.GetRequiredService<ImportService>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
var stockService = app.Services.GetRequiredService<Khaemhat.Application.Inventory.InventoryService>();
|
||||
await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
|
||||
var items = Csv("codice;descrizione;categoria;tipo", "A-1;Valvola;VALV;merce", "S-1;Manodopera;VALV;servizio");
|
||||
await imports.ImportAsync(Root, company, "articoli", items, ImportService.SuggestMapping(imports.Target("articoli"), items.Headers), new ImportOptions());
|
||||
@@ -162,13 +163,16 @@ public sealed class ImportServiceTests
|
||||
var stock = Csv("articolo;deposito;quantita;costo_unitario", "A-1;;5;3,20", "S-1;;1;", "A-1;;0;", "B-9;;1;");
|
||||
var mapping = ImportService.SuggestMapping(imports.Target("giacenze-iniziali"), stock.Headers);
|
||||
var preview = await imports.PreviewAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions());
|
||||
Assert.IsFalse(preview.CanApply);
|
||||
Assert.IsTrue(preview.CanApply);
|
||||
Assert.AreEqual(ImportOutcome.Ok, preview.Rows[0].Outcome, string.Join("; ", preview.Rows[0].Messages.Select(m => m.Field + ":" + m.Code)));
|
||||
Assert.AreEqual(ImportErrors.NotStocked, preview.Rows[1].Messages.Single().Code);
|
||||
CollectionAssert.Contains(preview.Rows[2].Messages.Select(m => m.Code).ToList(), ImportErrors.Positive);
|
||||
Assert.AreEqual(ImportErrors.CodeUnknown, preview.Rows[3].Messages.Single().Code);
|
||||
var refused = await Assert.ThrowsExactlyAsync<ImportFileException>(() => imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions()));
|
||||
Assert.AreEqual(ImportErrors.CheckOnly, refused.Code);
|
||||
|
||||
var report = await imports.ImportAsync(Root, company, "giacenze-iniziali", stock, mapping, new ImportOptions());
|
||||
Assert.AreEqual(1, report.Created);
|
||||
var row = (await stockService.StockAsync(Root, company, new Khaemhat.Application.Inventory.StockFilter())).Single();
|
||||
Assert.AreEqual((5m, 3.2m), (row.OnHand, row.AverageCost));
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Inventory;
|
||||
using Khaemhat.Application.Purchases;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Seeding;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// The demo purchases and warehouse (SPEC §14, issue #61): the opening stock, the orders, the receipts and the invoices
|
||||
/// made through the engine, a self-invoice still to issue, items under their minimum and a stock take being counted.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DemoPurchasesTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public async Task DemoSeed_MakesPurchasesAndStock_Once()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
|
||||
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
|
||||
await app.Services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, context);
|
||||
var seeder = app.Services.GetRequiredService<DemoPurchasesSeeder>();
|
||||
await seeder.SeedAsync(company, context);
|
||||
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
var all = await AllAsync(editor, company);
|
||||
int Count(DocumentKind kind, DocumentStatus status) => all.Count(r => r.Kind == kind && r.Status == status);
|
||||
Assert.AreEqual(1, Count(DocumentKind.PurchaseOrder, DocumentStatus.Fulfilled), "One order received in full.");
|
||||
Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.PurchaseOrder && r.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled),
|
||||
"One order still partly on its way.");
|
||||
Assert.AreEqual(2, all.Count(r => r.Kind == DocumentKind.PurchaseDeliveryNote));
|
||||
Assert.AreEqual(3, all.Count(r => r.Kind == DocumentKind.PurchaseInvoice && r.Status != DocumentStatus.Draft));
|
||||
Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.InventoryEntry));
|
||||
Assert.IsTrue(all.All(r => r.Date.Year == DateTime.Now.Year && r.Date <= DateOnly.FromDateTime(DateTime.Now)), "Dates of this year, never in the future.");
|
||||
|
||||
// The German invoice waits for its self-invoice; the stock has items under the minimum to reorder.
|
||||
var pending = await app.Services.GetRequiredService<PurchaseService>().PendingSelfInvoicesAsync(Root, company);
|
||||
Assert.HasCount(1, pending);
|
||||
var inventory = app.Services.GetRequiredService<InventoryService>();
|
||||
Assert.IsNotEmpty(await inventory.StockAsync(Root, company, new StockFilter()));
|
||||
Assert.IsNotEmpty(await app.Services.GetRequiredService<ReorderService>().ProposalsAsync(Root, company));
|
||||
var take = (await app.Services.GetRequiredService<StockTakeService>().ListAsync(Root, company)).Single();
|
||||
Assert.AreEqual(StockTakeStatus.Open, take.Status);
|
||||
|
||||
// Run again, nothing changes.
|
||||
await seeder.SeedAsync(company, context);
|
||||
Assert.HasCount(all.Count, await AllAsync(editor, company));
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<List<DocumentRow>> AllAsync(DocumentEditor editor, string company)
|
||||
{
|
||||
var all = new List<DocumentRow>();
|
||||
foreach (var family in new[] { DocumentFamily.PurchaseOrder, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
|
||||
{
|
||||
all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues<DocumentKind>()], new ListQuery { Limit = 200 })).Items);
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user