From f8b72f4d1741e66f5c7da8f279d9040aff5d35d9 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 12 Nov 2026 21:25:25 +0100 Subject: [PATCH] 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 --- .../Documents/DocumentEngine.cs | 65 +++++ .../Inventory/InventoryPoster.cs | 39 ++- .../Purchases/PurchaseService.cs | 267 ++++++++++++++++++ src/Khaemhat.Fiscal.Abstractions/Features.cs | 38 +++ src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs | 1 + .../SelfInvoiceRulesIt.cs | 59 ++++ .../Pages/Sales/SalesDocumentPage.razor | 54 +++- .../Pages/Sales/SalesDocumentPage.razor.cs | 35 ++- .../Pages/Sales/SalesDocumentsPage.razor | 29 +- .../Pages/Sales/SalesPrintPage.razor | 7 +- src/Khaemhat.Web/Documents/DocumentLookups.cs | 8 + src/Khaemhat.Web/Documents/SalesScreens.cs | 57 +++- src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 1 + .../Resources/it-IT/Documents.json | 8 + .../Resources/it-IT/Inventory.json | 17 ++ .../Resources/it-IT/Purchases.json | 15 + src/Khaemhat.Web/Resources/it-IT/Sales.json | 15 +- src/Khaemhat.Web/Resources/it-IT/Shell.json | 4 +- src/Khaemhat.Web/Shell/MenuCatalog.cs | 7 +- .../Documents/SalesFlowTests.cs | 7 +- .../Inventory/PurchaseFlowTests.cs | 148 ++++++++++ 21 files changed, 823 insertions(+), 58 deletions(-) create mode 100644 src/Khaemhat.Application/Purchases/PurchaseService.cs create mode 100644 src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs create mode 100644 src/Khaemhat.Web/Resources/it-IT/Inventory.json create mode 100644 src/Khaemhat.Web/Resources/it-IT/Purchases.json create mode 100644 tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 4de5c8c..755b410 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -90,6 +90,15 @@ public static class DocumentErrors /// Error: a line of an invoice without its VAT code. public const string LineTaxRequired = "document.line.tax-required"; + + /// A supplier invoice needs the number and date the supplier gave it. + public const string SupplierNumberRequired = "document.purchase.number-required"; + + /// The same supplier already has a document of the kind with that number in that year. + public const string SupplierDuplicate = "document.purchase.duplicate"; + + /// The VAT date comes before the date of the supplier document. + public const string VatDateBefore = "document.purchase.vat-date-before"; } /// @@ -241,6 +250,7 @@ public sealed partial class DocumentEngine } var errors = Check(definition, record, before); + await CheckSupplierDocumentAsync(uow, record, confirming: false, errors, cancellationToken).ConfigureAwait(false); if (errors.Count > 0) { throw new ValidationFailedException(errors); @@ -302,6 +312,8 @@ public sealed partial class DocumentEngine errors.Add("Lines:" + DocumentErrors.LinesRequired); } + await CheckSupplierDocumentAsync(uow, record, confirming: true, errors, cancellationToken).ConfigureAwait(false); + if (definition.Behavior.Has(DocumentEffects.Ledger)) { // A document that goes to the VAT registers needs the VAT of every line with an amount. @@ -331,6 +343,13 @@ public sealed partial class DocumentEngine } header.Year = header.DocumentDate.Year; + if (IsRegistered(header.Kind)) + { + // A supplier invoice takes its protocol from the numbering of the purchase register (§11.5). + header.VatProtocol = header.Number; + header.VatDate ??= header.DocumentDate; + } + header.Status = next; header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime; header.ConfirmedBy = actor.UserName; @@ -839,6 +858,52 @@ public sealed partial class DocumentEngine header.Revision = 0; } + // Supplier invoices and credit notes go to the purchase register with a protocol and a VAT date. + private static bool IsRegistered(DocumentKind kind) => kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote; + + // The rules of a supplier document (§11.5): its own number and date, the VAT date not before it, no duplicate of + // the same supplier, kind, number and year among the documents in force or in draft. + private static async Task CheckSupplierDocumentAsync(IUnitOfWork uow, DocumentRecord record, bool confirming, List errors, CancellationToken cancellationToken) + { + var header = record.Header; + if (!IsRegistered(header.Kind)) + { + return; + } + + var number = header.ExternalReference?.Trim(); + if (confirming && string.IsNullOrEmpty(number)) + { + errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierNumberRequired); + } + + if (confirming && header.ExternalDate is null) + { + errors.Add(nameof(DocumentHeader.ExternalDate) + ":" + DocumentErrors.SupplierNumberRequired); + } + + if (header.VatDate is { } vatDate && header.ExternalDate is { } supplierDate && vatDate < supplierDate) + { + errors.Add(nameof(DocumentHeader.VatDate) + ":" + DocumentErrors.VatDateBefore); + } + + if (string.IsNullOrEmpty(number) || header.PartyId is not { } party) + { + return; + } + + var year = (header.ExternalDate ?? header.DocumentDate).Year; + var kind = header.Kind; + var id = header.Id; + var others = (await uow.Repository().ListAsync( + Query.For().Where(d => d.PartyId == party && d.Kind == kind && d.ExternalReference == number && d.Id != id && d.Status != DocumentStatus.Cancelled), + cancellationToken).ConfigureAwait(false)).Items; + if (others.Any(d => (d.ExternalDate ?? d.DocumentDate).Year == year)) + { + errors.Add(nameof(DocumentHeader.ExternalReference) + ":" + DocumentErrors.SupplierDuplicate); + } + } + private static string Company(Actor actor, string companyCode) { ArgumentNullException.ThrowIfNull(actor); diff --git a/src/Khaemhat.Application/Inventory/InventoryPoster.cs b/src/Khaemhat.Application/Inventory/InventoryPoster.cs index e183cba..876f849 100644 --- a/src/Khaemhat.Application/Inventory/InventoryPoster.cs +++ b/src/Khaemhat.Application/Inventory/InventoryPoster.cs @@ -1,3 +1,4 @@ +using Khaemhat.Application.Security; using Khaemhat.Core.Documents; using Khaemhat.Core.Inventory; using Khaemhat.Core.Items; @@ -15,6 +16,9 @@ namespace Khaemhat.Application.Inventory; /// public static class InventoryPoster { + /// A transfer needs a destination different from the origin. + public const string TransferDestination = "document.transfer.destination"; + /// Writes again the movements of a document from its current state and refreshes its items. /// The unit of work of the company, in a transaction. /// The family of the document. @@ -132,8 +136,19 @@ public static class InventoryPoster return; } - var stockLines = await StockLinesAsync(uow, header, lines, cancellationToken).ConfigureAwait(false); - var movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines); + // A line that comes from a document that already moved its goods the same way (the invoice of a delivery note) + // does not move them again; a credit note of an invoice moves them back. + var sign = reason.IsTransfer ? 0 : reason.Effect switch { StockEffect.Load => 1, StockEffect.Unload => -1, _ => 0 }; + var stockLines = await StockLinesAsync(uow, header, lines, sign, cancellationToken).ConfigureAwait(false); + IReadOnlyList movements; + try + { + movements = StockEffectMatrix.Movements(header.Kind, StockReason.Of(reason), header.ToWarehouseId, stockLines); + } + catch (InvalidOperationException) + { + throw new ValidationFailedException([nameof(DocumentHeader.ToWarehouseId) + ":" + TransferDestination]); + } if (movements.Count == 0) { return; @@ -176,7 +191,8 @@ public static class InventoryPoster // The stocked lines of a document in the base unit, with their warehouse and cost; the lines that come from a // document that already moved the stock (the invoice of a delivery note) are left out. - private static async Task> StockLinesAsync(IUnitOfWork uow, DocumentHeader header, IReadOnlyList lines, CancellationToken cancellationToken) + private static async Task> StockLinesAsync( + IUnitOfWork uow, DocumentHeader header, IReadOnlyList lines, int sign, CancellationToken cancellationToken) { var result = new List(); var itemIds = lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null).Select(l => l.ItemId).Distinct().ToList(); @@ -190,7 +206,7 @@ public static class InventoryPoster var ids = catalog.Keys.ToList(); var units = (await uow.Repository().ListAsync(Query.For().Where(u => ids.Contains(u.ItemId)), cancellationToken).ConfigureAwait(false)).Items; var fallback = await DefaultWarehouseAsync(uow, cancellationToken).ConfigureAwait(false); - var moved = new Dictionary<(DocumentFamily, long), HashSet>(); + var moved = new Dictionary<(DocumentFamily, long), Dictionary>(); foreach (var line in lines.Where(l => l.Kind == DocumentLineKind.Item && l.ItemId is not null && l.Quantity != 0m)) { if (!catalog.TryGetValue(line.ItemId!.Value, out var item) || !item.Stocked || item.Kind != ItemKind.Goods) @@ -198,8 +214,8 @@ public static class InventoryPoster continue; } - if (line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId - && await AlreadyMovedAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false)) + if (sign != 0 && line.SourceFamily is { } sourceFamily && line.SourceLineId is { } sourceLineId + && await MovedSignAsync(uow, sourceFamily, sourceLineId, moved, cancellationToken).ConfigureAwait(false) == sign) { continue; } @@ -234,13 +250,14 @@ public static class InventoryPoster return Math.Round(amount / baseQuantity, StockCostCalculator.CostDecimals, MidpointRounding.AwayFromZero); } - private static async Task AlreadyMovedAsync( - IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), HashSet> moved, CancellationToken cancellationToken) + // How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all. + private static async Task MovedSignAsync( + IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary> moved, CancellationToken cancellationToken) { var source = await StoreLineAsync(uow, sourceFamily, sourceLineId, cancellationToken).ConfigureAwait(false); if (source is null) { - return false; + return 0; } var key = (sourceFamily, source.DocumentId); @@ -256,7 +273,7 @@ public static class InventoryPoster { if (line.SourceLineId is { } id) { - lines.Add(id); + lines[id] = Math.Sign(line.Quantity); } } } @@ -264,7 +281,7 @@ public static class InventoryPoster moved[key] = lines; } - return lines.Contains(sourceLineId); + return lines.GetValueOrDefault(sourceLineId); } private static async Task RecomputeItemAsync( diff --git a/src/Khaemhat.Application/Purchases/PurchaseService.cs b/src/Khaemhat.Application/Purchases/PurchaseService.cs new file mode 100644 index 0000000..8d6fde2 --- /dev/null +++ b/src/Khaemhat.Application/Purchases/PurchaseService.cs @@ -0,0 +1,267 @@ +using Khaemhat.Application.Documents; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Items; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Purchases; + +/// A line of a supplier invoice whose price differs from the order or receipt it comes from (§11.5). +/// The line of the invoice. +/// Its description. +/// The kind of the document it comes from. +/// Its number. +/// The net unit price there. +/// The net unit price on the invoice. +/// The quantity of the invoice line. +public sealed record PriceDifference( + int LineNumber, string Description, DocumentKind SourceKind, string? SourceNumber, decimal SourcePrice, decimal InvoicePrice, decimal Quantity) +{ + /// The difference on the whole line: positive when the invoice costs more. + public decimal Amount => Math.Round((InvoicePrice - SourcePrice) * Quantity, 2, MidpointRounding.AwayFromZero); +} + +/// A supplier invoice that waits for its self-invoice (mockup 035). +/// The invoice. +/// The self-invoice it needs and by when. +public sealed record PendingSelfInvoice(DocumentRow Invoice, SelfInvoiceAdvice Advice); + +/// +/// The rules of purchases beyond the document engine (SPEC §11.5): price differences against orders and receipts, +/// the self-invoice a supplier invoice needs (reverse charge, purchases from abroad) and its draft. +/// +/// Permissions purchases.invoice.read and write. +public sealed class PurchaseService +{ + /// Permission to read supplier invoices. + public const string ReadPermission = "purchases.invoice.read"; + + /// Permission to register supplier invoices and self-invoices. + public const string WritePermission = "purchases.invoice.write"; + + /// The supplier invoice does not need a self-invoice. + public const string SelfInvoiceNotNeeded = "purchase.self-invoice.not-needed"; + + private readonly DocumentEngine _engine; + private readonly DocumentCopyService _copies; + private readonly DocumentEditor _editor; + private readonly CompanyFiscalContext _packs; + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + + /// Creates the service. + /// The document engine. + /// Copies and transformations. + /// The editor (radars). + /// The fiscal pack of each company. + /// The units of work. + /// The permissions. + public PurchaseService( + DocumentEngine engine, DocumentCopyService copies, DocumentEditor editor, CompanyFiscalContext packs, IUnitOfWorkFactory factory, PermissionService permissions) + { + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(copies); + ArgumentNullException.ThrowIfNull(editor); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + _engine = engine; + _copies = copies; + _editor = editor; + _packs = packs; + _factory = factory; + _permissions = permissions; + } + + /// The lines of a supplier invoice whose net price differs from their order or receipt. + /// Who reads. + /// The company. + /// The invoice, as on screen. + /// Cancellation. + /// The differences. + public async Task> PriceDifferencesAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var result = new List(); + if (record.Header.Kind is not (DocumentKind.PurchaseInvoice or DocumentKind.PurchaseDeliveryNote)) + { + return result; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var headers = new Dictionary<(DocumentFamily, long), DocumentHeader?>(); + for (var i = 0; i < record.Lines.Count; i++) + { + var line = record.Lines[i]; + if (line.SourceFamily is not { } family || line.SourceLineId is not { } sourceId || line.Quantity == 0m) + { + continue; + } + + var source = await DocumentStores.Of(family).GetLineAsync(uow, sourceId, cancellationToken).ConfigureAwait(false); + if (source is null || source.Quantity == 0m) + { + continue; + } + + if (!headers.TryGetValue((family, source.DocumentId), out var header)) + { + header = await DocumentStores.Of(family).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false); + headers[(family, source.DocumentId)] = header; + } + + if (header is null) + { + continue; + } + + var before = Math.Round(source.TaxableAmount / source.Quantity, 4, MidpointRounding.AwayFromZero); + var now = Math.Round(line.TaxableAmount / line.Quantity, 4, MidpointRounding.AwayFromZero); + if (before != now) + { + result.Add(new PriceDifference(i + 1, line.Description, header.Kind, header.DocumentNumber ?? header.ExternalReference, before, now, line.Quantity)); + } + } + + return result; + } + + /// The self-invoice a supplier invoice needs, if any (reverse charge, purchase from abroad). + /// Who reads. + /// The company. + /// The invoice. + /// Cancellation. + /// The advice, or . + public async Task AdviseAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(record); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + if (record.Header.Kind != DocumentKind.PurchaseInvoice || record.Header.PartyId is null) + { + return null; + } + + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + if (rules is null) + { + return null; + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false); + } + + /// + /// The confirmed supplier invoices that need a self-invoice and have none yet, the nearest deadline first. + /// + /// Who reads. + /// The company. + /// Cancellation. + /// The invoices with their advice. + public async Task> PendingSelfInvoicesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); + if (rules is null) + { + return []; + } + + var rows = await _editor.ListAsync(actor, company, DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseInvoice], new Querying.ListQuery { Limit = 500 }, cancellationToken) + .ConfigureAwait(false); + var result = new List(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var integrated = (await uow.Repository().ListAsync( + Query.For().Where(l => l.SourceFamily == DocumentFamily.PurchaseDocument && l.TargetFamily == DocumentFamily.SaleDocument), cancellationToken) + .ConfigureAwait(false)).Items.Select(l => l.SourceDocumentId).ToHashSet(); + foreach (var row in rows.Items.Where(r => DocumentStateMachine.IsInForce(r.Status) && !integrated.Contains(r.Id))) + { + var record = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, row.Id, cancellationToken).ConfigureAwait(false); + if (record is not null && await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false) is { } advice) + { + result.Add(new PendingSelfInvoice(row, advice)); + } + } + + return [.. result.OrderBy(p => p.Advice.Deadline).ThenBy(p => p.Invoice.Date)]; + } + + /// + /// The draft self-invoice of a supplier invoice: its lines with the ordinary VAT code where the supplier wrote a + /// nature, the supplier's number and date as the related invoice, today as date. + /// + /// Who creates. + /// The company. + /// The supplier invoice. + /// The type, such as AF17; the advised one when empty. + /// Cancellation. + /// The draft, saved. + /// No type was given and none is advised. + public async Task CreateSelfInvoiceAsync(Actor actor, string companyCode, long purchaseInvoiceId, string? typeCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); + var invoice = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); + var code = typeCode; + if (string.IsNullOrWhiteSpace(code)) + { + await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + code = (await AdviseAsync(read, rules, invoice, cancellationToken).ConfigureAwait(false))?.DocumentTypeCode + ?? throw new ValidationFailedException([":" + SelfInvoiceNotNeeded]); + } + + var draft = await _copies.CopyAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, code, null, cancellationToken).ConfigureAwait(false); + var header = draft.Header; + header.RelatedDocumentId = invoice.Header.Id; + header.RelatedNumber = invoice.Header.ExternalReference; + header.RelatedDate = invoice.Header.ExternalDate; + header.ExternalReference = null; + header.ExternalDate = null; + header.InventoryReasonId = null; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; + var ordinary = taxes.FirstOrDefault(t => t.Code == rules.OrdinaryTaxCode)?.Id; + foreach (var line in draft.Lines) + { + // The supplier invoiced without VAT (a nature): the integration applies the rate. + if (line.TaxCodeId is { } id && taxes.FirstOrDefault(t => t.Id == id) is { Nature: not null } && ordinary is not null) + { + line.TaxCodeId = ordinary; + } + } + } + + return await _engine.SaveAsync(actor, company, draft, cancellationToken).ConfigureAwait(false); + } + + private static async Task AdviseAsync(IUnitOfWork uow, ISelfInvoiceRules rules, DocumentRecord record, CancellationToken cancellationToken) + { + if (record.Header.PartyId is not { } partyId || await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { } party) + { + return null; + } + + var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant(); + var inEu = (await uow.Repository().FindAsync(Query.For().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false; + var taxIds = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).Distinct().ToList(); + var natures = taxIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(t => taxIds.Contains(t.Id)), cancellationToken) + .ConfigureAwait(false)).Items.Where(t => t.Nature is not null).Select(t => t.Nature!).Distinct().ToList(); + var itemIds = record.Lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList(); + var kinds = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) + .ConfigureAwait(false)).Items.ToDictionary(i => i.Id, i => i.Kind); + + // Goods when the item lines of goods weigh more than the rest; free lines count as services. + var goods = record.Lines.Where(l => l.ItemId is { } id && kinds.GetValueOrDefault(id) == ItemKind.Goods).Sum(l => Math.Abs(l.TaxableAmount)); + var other = record.Lines.Where(l => l.Kind != DocumentLineKind.Description).Sum(l => Math.Abs(l.TaxableAmount)) - goods; + var received = record.Header.VatDate ?? record.Header.DocumentDate; + return rules.Advise(new SelfInvoiceCase(country, inEu && country != "IT", goods > other, natures, received)); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Features.cs b/src/Khaemhat.Fiscal.Abstractions/Features.cs index 727d475..b9bb46c 100644 --- a/src/Khaemhat.Fiscal.Abstractions/Features.cs +++ b/src/Khaemhat.Fiscal.Abstractions/Features.cs @@ -273,3 +273,41 @@ public interface IPlaceDirectory /// The municipalities. IReadOnlyList Municipalities { get; } } + +/// What a received invoice tells about the self-invoice it may need. +/// The country of the supplier (ISO 3166-1 alpha-2). +/// The supplier is in another member state of the European Union. +/// The invoice is mostly for goods (otherwise services). +/// The VAT natures of its lines (codes of the country's e-invoice format), if any. +/// The day it was received or registered. +public sealed record SelfInvoiceCase(string SupplierCountry, bool SupplierInEu, bool Goods, IReadOnlyCollection Natures, DateOnly Received); + +/// The self-invoice a received invoice needs. +/// The document type of the base tables, such as AF17. +/// Why, in the language of the users. +/// The last day to issue it. +public sealed record SelfInvoiceAdvice(string DocumentTypeCode, string Reason, DateOnly Deadline); + +/// +/// The country's rules of self-invoices and integrations (Italy: TD16-TD29 under reverse charge, purchases from abroad, +/// regularisations): which type a received invoice needs, by when, and the VAT code that integrates it. +/// +public interface ISelfInvoiceRules +{ + /// The document types of self-invoices, in the order of the menu. + IReadOnlyList DocumentTypeCodes { get; } + + /// The VAT code (of the base tables) of the ordinary rate, proposed on the lines of an integration. + string OrdinaryTaxCode { get; } + + /// The self-invoice a received invoice needs, if any. + /// The invoice. + /// The advice, or when none is needed. + SelfInvoiceAdvice? Advise(SelfInvoiceCase input); + + /// The last day to issue a self-invoice of a type for an invoice received on a day. + /// The type. + /// The day the invoice was received (or the operation took place). + /// The deadline. + DateOnly Deadline(string documentTypeCode, DateOnly received); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 34498e2..b15da11 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -16,6 +16,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase { AddFeature(new FatturaPaFormat()); AddFeature(new FatturaPaReader()); + AddFeature(new SelfInvoiceRulesIt()); AddFeature(new WithholdingRulesIt()); AddFeature(new FixedAssetRulesIt()); AddFeature(new F24Exporter()); diff --git a/src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs b/src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs new file mode 100644 index 0000000..2807dfa --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/SelfInvoiceRulesIt.cs @@ -0,0 +1,59 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Italian self-invoices and integrations (provvedimento AdE 99922/2020, specifiche FatturaPA 1.9): TD16 integrates a +/// domestic reverse charge (natures N6.x), TD17 the purchase of services from abroad, TD18 of goods from another member +/// state, TD19 of goods located in Italy from a non-resident (art. 17 c.2). Integrations go to the exchange system by +/// the 15th of the month after the receipt; regularisations (TD20) and communications (TD29) within 90 days. +/// +public sealed class SelfInvoiceRulesIt : ISelfInvoiceRules +{ + /// + public IReadOnlyList DocumentTypeCodes { get; } = ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"]; + + /// + public string OrdinaryTaxCode => "22"; + + /// + public SelfInvoiceAdvice? Advise(SelfInvoiceCase input) + { + ArgumentNullException.ThrowIfNull(input); + var domestic = string.Equals(input.SupplierCountry, "IT", StringComparison.OrdinalIgnoreCase); + if (domestic) + { + if (input.Natures.Any(n => n.StartsWith("N6", StringComparison.Ordinal))) + { + return Advice("AF16", "Inversione contabile interna (art. 17 c.6 e 74 c.7-8 DPR 633/72): integrazione della fattura del fornitore.", input.Received); + } + + return null; + } + + if (string.Equals(input.SupplierCountry, "SM", StringComparison.OrdinalIgnoreCase)) + { + return input.Natures.Count == 0 + ? Advice("AF28", "Acquisto da San Marino con IVA addebitata in fattura.", input.Received) + : null; + } + + if (!input.Goods) + { + return Advice("AF17", "Acquisto di servizi da un fornitore estero (art. 17 c.2 e 7-ter DPR 633/72).", input.Received); + } + + return input.SupplierInEu + ? Advice("AF18", "Acquisto intracomunitario di beni (art. 46-47 DL 331/93).", input.Received) + : Advice("AF19", "Acquisto di beni già in Italia da un soggetto non residente (art. 17 c.2 DPR 633/72).", input.Received); + } + + /// + public DateOnly Deadline(string documentTypeCode, DateOnly received) => documentTypeCode switch + { + "AF20" or "AF29" => received.AddDays(90), + _ => new DateOnly(received.Year, received.Month, 15).AddMonths(1), + }; + + private SelfInvoiceAdvice Advice(string code, string reason, DateOnly received) => new(code, reason, Deadline(code, received)); +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor index cf5330b..240206d 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor @@ -1,5 +1,9 @@ @page "/vendite/{Segment}/nuovo" @page "/vendite/{Segment}/{Id:long}" +@page "/acquisti/{Segment}/nuovo" +@page "/acquisti/{Segment}/{Id:long}" +@page "/magazzino/{Segment}/nuovo" +@page "/magazzino/{Segment}/{Id:long}" @attribute [Authorize] @inherits DocumentPage @using Khaemhat.Application.Audit @@ -11,8 +15,9 @@ @using Khaemhat.Web.Documents @using Khaemhat.Web.Parties -@* The record of a sales document (SPEC §11.3, mockups 020-022 and 026-029): quotation, order, delivery note, invoice of - every kind, pro forma, credit and debit note. Righe first with the VAT summary, due dates and totals underneath, then +@* The record of a document (SPEC §11.3-§11.6, mockups 020-022, 026-029, 031-033, 035, 037): quotation, order, delivery + note, invoice of every kind, pro forma, credit and debit note; supplier order, receipt, supplier invoice and credit + note with protocol and VAT date, self-invoice; warehouse movement with reason and warehouses. Righe first with the VAT summary, due dates and totals underneath, then Testata, Trasporto for the documents that move goods, Totali, Scadenze, Note, Allegati, Collegamenti, Storico. The totals are computed while typing with the code of the save; the actions follow the state machine of the engine. *@ @@ -47,7 +52,7 @@ else @T["Sales.Fields.DocumentDate"] @T.Date(h.DocumentDate) @@ -104,7 +109,7 @@ else @switch (ActiveTab) { case TabIds.Lines: - @if (h.PartyId is null && !IsReadOnly) + @if (h.PartyId is null && !IsReadOnly && !IsInternal) {
@T["Sales.Hints.PartyFirst"]
@@ -143,9 +148,17 @@ else { } - - + + + @if (IsRegistered) + { + + + } @if (IsNote) { } + @if (IsInternal) + { + + + + @if (IsTransfer) + { + + } +

@T["Inventory.Hints.Movement"]

+
+ } + else + { - - + @if (!IsPurchase) + { + + } @if (h.PartyId is not null) @@ -203,6 +236,7 @@ else

@T["Sales.Hints.Withholding"]

} + } break; diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs index e52d490..78fa0fd 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs @@ -110,7 +110,10 @@ public sealed partial class SalesDocumentPage ? T["Shell.Menu.Sales"] : _definition.Type.Description + " " + (Record.Header.DocumentNumber ?? T["Sales.DraftNumber"]); - private bool IsInvoice => Record is not null && (Behavior.Lifecycle == DocumentLifecycle.Invoice || H.Kind == DocumentKind.ProForma); + private bool IsInvoice => Record is not null && (Behavior.Lifecycle == DocumentLifecycle.Invoice || H.Kind == DocumentKind.ProForma || IsRegistered); + + // A movement between two warehouses: its reason is a transfer. + private bool IsTransfer => Record is not null && H.InventoryReasonId is { } reason && _lookups.TransferReasons.Contains(reason); private bool IsNote => Record is not null && H.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote; @@ -119,7 +122,17 @@ public sealed partial class SalesDocumentPage private bool CanWrite => Record is not null && Session.Permissions.Allows(Behavior.WritePermission); // The entity of the attachments, such as sales.saledocument. - private string AttachmentEntity => "sales." + Record!.Header.GetType().Name.ToLowerInvariant(); + private string AttachmentEntity => DocumentPrintService.EntityOf(Record!.Family); + + // Customers for sales, suppliers for purchases and self-invoices. + private PartyArchive Archive => _section?.Direction == DocumentDirection.Purchase ? PartyArchive.Suppliers : PartyArchive.Customers; + + private bool IsPurchase => _section?.Direction == DocumentDirection.Purchase; + + private bool IsInternal => _section?.Direction == DocumentDirection.Internal; + + // A supplier invoice or credit note: registered with a protocol and a VAT date. + private bool IsRegistered => Record is not null && H.Kind is DocumentKind.PurchaseInvoice or DocumentKind.PurchaseCreditNote; /// public override bool IsReadOnly => Record is null || !CanWrite || !(IsNew || _actions.Contains(DocumentAction.Edit)); @@ -154,7 +167,7 @@ public sealed partial class SalesDocumentPage TabOf(TabIds.Lines, "list", "Ui.Record.Tabs.Lines", Record.Lines.Count), TabOf(TabIds.Header, "file", "Ui.Record.Tabs.Header"), }; - if (Behavior.Has(DocumentEffects.Inventory)) + if (Behavior.Has(DocumentEffects.Inventory) && !IsInternal) { tabs.Add(TabOf(SalesScreens.TransportTab, "truck", "Sales.Tabs.Transport")); } @@ -214,7 +227,7 @@ public sealed partial class SalesDocumentPage return; } - _section = SalesScreens.Find(Segment); + _section = SalesScreens.Find(SalesScreens.AreaOf(Navigation.ToBaseRelativePath(Navigation.Uri)), Segment); if (!_loaded) { _lookups = await DocumentLookups.ReadAsync(Tables, actor, company); @@ -847,10 +860,10 @@ public sealed partial class SalesDocumentPage private async Task> SearchPartiesAsync(string text, CancellationToken cancellationToken) => Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission) - ? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken) + ? await Parties.SearchAsync(actor, company, Archive, text, cancellationToken) : []; - private void OpenParty(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id)); + private void OpenParty(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(Archive, row.Id)); private void Change(Action change) { @@ -1100,11 +1113,14 @@ public sealed partial class SalesDocumentPage // An order-like document gives what is left to fulfil; an issued invoice gives its notes. var open = H.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled; var issued = Behavior.Lifecycle == DocumentLifecycle.Invoice && DocumentStateMachine.IsInForce(H.Status); + + // A registered supplier invoice gives its credit notes and self-invoices. + var registered = IsRegistered && DocumentStateMachine.IsInForce(H.Status); var preferred = SalesScreens.Sections.SelectMany(s => s.NewTypes).ToList(); return _definitions - .Where(d => d.Behavior.Direction == DocumentDirection.Sale && d.Behavior.Fulfils(H.Kind) && preferred.Contains(d.Code) + .Where(d => d.Behavior.Direction == Behavior.Direction && d.Behavior.Fulfils(H.Kind) && preferred.Contains(d.Code) && Session.Permissions.Allows(d.Behavior.WritePermission) - && (d.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote ? issued : open)) + && (d.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote or DocumentKind.PurchaseCreditNote or DocumentKind.SelfInvoice ? issued || registered : open)) .OrderBy(d => Preference(H.Kind, d.Kind)) .ThenBy(d => preferred.IndexOf(d.Code)); } @@ -1117,6 +1133,9 @@ public sealed partial class SalesDocumentPage (DocumentKind.DeliveryNote, DocumentKind.DeferredInvoice) => 0, (DocumentKind.ProForma, DocumentKind.ImmediateInvoice) => 0, (_, DocumentKind.CreditNote) => 0, + (DocumentKind.PurchaseOrder, DocumentKind.PurchaseDeliveryNote) => 0, + (DocumentKind.PurchaseDeliveryNote, DocumentKind.PurchaseInvoice) => 0, + (_, DocumentKind.PurchaseCreditNote) => 0, _ => 1, }; diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor index 1d436bc..c33ce9c 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor @@ -1,4 +1,6 @@ @page "/vendite/{Segment}" +@page "/acquisti/{Segment}" +@page "/magazzino/{Segment}" @attribute [Authorize] @using Khaemhat.Application.Documents @using Khaemhat.Core.Documents @@ -9,9 +11,10 @@ @inject NavigationManager Navigation @inject TimeProvider Clock -@* The radar of a kind of sales documents (SPEC §11.3): quotations, orders, delivery notes, invoices (with pro forma - and fees), credit and debit notes. Search on number, reference and customer; filters for state, type and year; - totals of the page. Enter or double click opens the document. *@ +@* The radar of a kind of documents (SPEC §11.3-§11.6): quotations, orders, delivery notes, invoices (with pro forma + and fees), credit and debit notes; supplier orders, receipts, supplier invoices, self-invoices; warehouse + movements. Search on number, reference and party; filters for state, type and year; totals of the page. Enter or + double click opens the document. *@ @if (!_loaded) @@ -36,7 +39,7 @@ else if (!CanRead) } else { - @@ -44,7 +47,7 @@ else { } - @if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write")) + @if (_section.Area == SalesScreens.BasePath && _section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write")) { @T["Sales.Deferred.Title"] } @@ -79,6 +82,8 @@ else private string Title => _section is null ? T["Shell.Menu.Sales"] : T["Sales.Sections." + _section.Key + ".Title"]; + private bool Internal => _section?.Direction == DocumentDirection.Internal; + private bool CanRead => _section is not null && Session.Permissions.Allows(DocumentBehaviors.Of(_section.Kinds[0]).ReadPermission); private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); @@ -90,15 +95,15 @@ else private IReadOnlyList> Columns => [ - new("number", T["Sales.Fields.DocumentNumber"], r => r.DocumentNumber ?? T["Sales.DraftNumber"]) { Kind = KhColumnKind.Code, Width = "130px" }, + new("number", T[_section?.Kinds.Contains(DocumentKind.PurchaseInvoice) == true ? "Purchases.Fields.Protocol" : "Sales.Fields.DocumentNumber"], r => r.DocumentNumber ?? T["Sales.DraftNumber"]) { Kind = KhColumnKind.Code, Width = "130px" }, new("date", T["Sales.Fields.DocumentDate"], r => r.Date) { Kind = KhColumnKind.Date, Width = "100px" }, new("type", T["Sales.Radar.Kind"], r => SalesScreens.KindName(T, r.Kind)) { Width = "150px", Sortable = false, Visible = _section?.Kinds.Count > 1 }, - new("party", T["Sales.Fields.PartyId"], r => r.PartyName) { Sortable = false }, - new("reference", T["Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" }, + new("party", T[SalesScreens.PartyLabel(_section?.Direction ?? DocumentDirection.Sale)], r => r.PartyName) { Sortable = false, Visible = !Internal }, + new("reference", T[_section?.Direction == DocumentDirection.Purchase ? "Purchases.Fields.SupplierNumber" : "Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" }, new("validUntil", T["Sales.Fields.ValidUntil"], r => r.ValidUntil) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment == "preventivi" }, - new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" }, - new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px" }, - new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px" }, + new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" or "ricevimenti" }, + new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px", Visible = !Internal }, + new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px", Visible = !Internal }, new("status", T["Sales.Radar.State"], r => StateOf(r).Text) { Width = "130px", @@ -136,7 +141,7 @@ else protected override async Task OnParametersSetAsync() { await Session.EnsureLoadedAsync(); - _section = SalesScreens.Find(Segment); + _section = SalesScreens.Find(SalesScreens.AreaOf(Navigation.ToBaseRelativePath(Navigation.Uri)), Segment); if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company) { _definitions = await Engine.DefinitionsAsync(actor, company); diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor index d6c7b9d..06af393 100644 --- a/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor @@ -1,4 +1,6 @@ @page "/vendite/{Segment}/{Id:long}/stampa" +@page "/acquisti/{Segment}/{Id:long}/stampa" +@page "/magazzino/{Segment}/{Id:long}/stampa" @attribute [Authorize] @using Khaemhat.Application.Documents @using Khaemhat.Application.Security @@ -9,6 +11,7 @@ @inject DocumentEngine Engine @inject FileGenerationService Generation @inject ToastService Toasts +@inject NavigationManager Navigation @* The print preview of a sales document (SPEC §9.4, issue #52, mockup 025): the A4 sheet in HTML from the same model as the PDF, with Stampa (the print of the browser), the PDF made by Khaemhat and "Salva come allegato", which keeps @@ -172,13 +175,13 @@ else private string Heading => _model is null ? T["Sales.Print.Title"] : T.Format("Sales.Print.Heading", _model.Title, _model.Number); - private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.BasePath + "/" + _section.Segment + "/" + Id.ToString(T.Culture); + private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.RadarUrl(_section) + "/" + Id.ToString(T.Culture); /// protected override async Task OnParametersSetAsync() { await Session.EnsureLoadedAsync(); - _section = SalesScreens.Find(Segment); + _section = SalesScreens.Find(SalesScreens.AreaOf(Navigation.ToBaseRelativePath(Navigation.Uri)), Segment); if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) { _missing = true; diff --git a/src/Khaemhat.Web/Documents/DocumentLookups.cs b/src/Khaemhat.Web/Documents/DocumentLookups.cs index 33244b9..eb00d81 100644 --- a/src/Khaemhat.Web/Documents/DocumentLookups.cs +++ b/src/Khaemhat.Web/Documents/DocumentLookups.cs @@ -33,6 +33,12 @@ public sealed class DocumentLookups /// Warehouses. public IReadOnlyList> Warehouses { get; private init; } = []; + /// Warehouse reasons (causali di magazzino). + public IReadOnlyList> InventoryReasons { get; private init; } = []; + + /// The ids of the reasons that move goods between two warehouses. + public IReadOnlySet TransferReasons { get; private init; } = new HashSet(); + /// Carriers. public IReadOnlyList> Carriers { get; private init; } = []; @@ -68,6 +74,8 @@ public sealed class DocumentLookups Salespeople = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), BankAccounts = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), Warehouses = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + InventoryReasons = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TransferReasons = (await tables.ActiveAsync(actor, company, cancellationToken).ConfigureAwait(false)).Where(r => r.IsTransfer).Select(r => r.Id).ToHashSet(), Carriers = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), ShippingTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), TransportReasons = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), diff --git a/src/Khaemhat.Web/Documents/SalesScreens.cs b/src/Khaemhat.Web/Documents/SalesScreens.cs index 6f05be7..463bc5e 100644 --- a/src/Khaemhat.Web/Documents/SalesScreens.cs +++ b/src/Khaemhat.Web/Documents/SalesScreens.cs @@ -5,24 +5,37 @@ using Khaemhat.Web.Ui; namespace Khaemhat.Web.Documents; -/// A radar of the sales menu and the document types it holds. +/// A radar of the documents menus (sales, purchases, warehouse) and the document types it holds. /// The path segment, such as fatture. /// The family of the documents. /// The kinds shown. /// The document types a user can create from the radar, the first being the usual one. /// The icon. /// The key of the texts under Sales.Sections. -public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList Kinds, IReadOnlyList NewTypes, string Icon, string Key); +/// The menu area, such as vendite or acquisti. +public sealed record SalesSection( + string Segment, DocumentFamily Family, IReadOnlyList Kinds, IReadOnlyList NewTypes, string Icon, string Key, string Area = SalesScreens.BasePath) +{ + /// Whose documents: customers, suppliers or nobody. + public DocumentDirection Direction => DocumentBehaviors.Of(Kinds[0]).Direction; +} /// -/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under -/// /vendite, the record of a document under it, and the deferred invoicing. +/// Addresses and labels of the document screens (SPEC §11.3-§11.6, mockups 020-037): one radar per menu entry under +/// /vendite, /acquisti and /magazzino, the record of a document under it, and the deferred +/// invoicing. The screens are the same for every area; the labels follow the direction (customer or supplier). /// public static class SalesScreens { - /// The menu area. + /// The sales area. public const string BasePath = "vendite"; + /// The purchases area. + public const string PurchasesPath = "acquisti"; + + /// The warehouse area. + public const string InventoryPath = "magazzino"; + /// The deferred invoicing of the delivery notes. public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita"; @@ -39,12 +52,40 @@ public static class SalesScreens [DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.Fee, DocumentKind.ProForma], ["FI", "FA", "FD", "FACC", "PAR", "PF"], "euro", "Invoices"), new("note-credito", DocumentFamily.SaleDocument, [DocumentKind.CreditNote, DocumentKind.DebitNote], ["NC", "ND"], "undo", "CreditNotes"), + new("ordini", DocumentFamily.PurchaseOrder, [DocumentKind.PurchaseOrder], ["OF"], "file-check", "PurchaseOrders", PurchasesPath), + new("ricevimenti", DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseDeliveryNote], ["DDTF"], "truck", "Receipts", PurchasesPath), + new("fatture", DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseInvoice, DocumentKind.PurchaseCreditNote], ["FF", "NCF"], "euro", "PurchaseInvoices", PurchasesPath), + new("autofatture", DocumentFamily.SaleDocument, [DocumentKind.SelfInvoice], + ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"], "refresh", "SelfInvoices", PurchasesPath), + new("movimenti", DocumentFamily.InventoryDocument, [DocumentKind.InventoryEntry], ["MM"], "layers", "Movements", InventoryPath), ]; - /// The radar of a path segment. + /// The sales radar of a path segment. /// The segment. /// The radar, or . - public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase)); + public static SalesSection? Find(string? segment) => Find(BasePath, segment); + + /// The radar of an area and a path segment. + /// The area, such as acquisti. + /// The segment. + /// The radar, or . + public static SalesSection? Find(string? area, string? segment) => + Sections.FirstOrDefault(s => string.Equals(s.Area, area, StringComparison.OrdinalIgnoreCase) && string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase)); + + /// The area of a relative address: its first segment. + /// The address relative to the base, such as acquisti/fatture/3. + /// The area. + public static string AreaOf(string? relativePath) + { + var path = relativePath ?? string.Empty; + var end = path.IndexOfAny(['/', '?', '#']); + return end < 0 ? path : path[..end]; + } + + /// The key of the label of the party for a direction: customer, supplier. + /// The direction. + /// The key of the text. + public static string PartyLabel(DocumentDirection direction) => direction == DocumentDirection.Purchase ? "Purchases.Fields.Supplier" : "Sales.Fields.PartyId"; /// The radar that holds a kind of document. /// The kind. @@ -57,7 +98,7 @@ public static class SalesScreens public static string RadarUrl(SalesSection section) { ArgumentNullException.ThrowIfNull(section); - return BasePath + "/" + section.Segment; + return section.Area + "/" + section.Segment; } /// The address of a document. diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 80f3772..5648763 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -147,6 +147,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // The document engine (ADR 0032): one engine, the copies, a typed service per family. diff --git a/src/Khaemhat.Web/Resources/it-IT/Documents.json b/src/Khaemhat.Web/Resources/it-IT/Documents.json index 6ac2981..80d7388 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Documents.json +++ b/src/Khaemhat.Web/Resources/it-IT/Documents.json @@ -41,6 +41,14 @@ "reason-required": "Per annullare una fattura indica il motivo.", "has-followers": "Altri documenti evadono questo: annulla prima quelli." }, + "purchase": { + "number-required": "Indica il numero e la data che il fornitore ha scritto sul documento.", + "duplicate": "Questo fornitore ha già un documento con lo stesso numero nello stesso anno: controlla di non registrarlo due volte.", + "vat-date-before": "La data di registrazione IVA non può precedere la data del documento del fornitore." + }, + "transfer": { + "destination": "Per un trasferimento indica il deposito d'arrivo, diverso da quello di partenza." + }, "copy": { "direction": "Si trasforma solo in un documento della stessa direzione (vendita o acquisto).", "nothing-left": "Non c'è più nulla da evadere.", diff --git a/src/Khaemhat.Web/Resources/it-IT/Inventory.json b/src/Khaemhat.Web/Resources/it-IT/Inventory.json new file mode 100644 index 0000000..56c77ec --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Inventory.json @@ -0,0 +1,17 @@ +{ + "Inventory": { + "NoReason": "Senza causale", + "Groups": { + "Movement": "Movimento" + }, + "Fields": { + "Reason": "Causale", + "Warehouse": "Deposito", + "FromWarehouse": "Dal deposito", + "ToWarehouse": "Al deposito" + }, + "Hints": { + "Movement": "La causale decide se il movimento carica, scarica o trasferisce; senza deposito vale quello dell’articolo." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Purchases.json b/src/Khaemhat.Web/Resources/it-IT/Purchases.json new file mode 100644 index 0000000..c79660a --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Purchases.json @@ -0,0 +1,15 @@ +{ + "Purchases": { + "Fields": { + "Supplier": "Fornitore", + "SupplierNumber": "N. documento fornitore", + "SupplierDate": "Data documento fornitore", + "Protocol": "Protocollo", + "VatDate": "Data registrazione IVA" + }, + "Hints": { + "SupplierNumber": "Il numero scritto dal fornitore sulla sua fattura o sul DDT.", + "VatDate": "Il mese in cui l’IVA entra in detrazione; vuota, vale la data di registrazione." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Sales.json b/src/Khaemhat.Web/Resources/it-IT/Sales.json index 1c01d68..1f10cb0 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Sales.json +++ b/src/Khaemhat.Web/Resources/it-IT/Sales.json @@ -13,7 +13,12 @@ "Orders": { "Title": "Ordini clienti", "New": "Nuovo ordine" }, "DeliveryNotes": { "Title": "Documenti di trasporto", "New": "Nuovo DDT" }, "Invoices": { "Title": "Fatture di vendita", "New": "Nuova fattura" }, - "CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" } + "CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" }, + "PurchaseOrders": { "Title": "Ordini fornitori", "New": "Nuovo ordine fornitore" }, + "Receipts": { "Title": "Ricevimenti merce", "New": "Nuovo ricevimento" }, + "PurchaseInvoices": { "Title": "Fatture passive", "New": "Registra fattura" }, + "SelfInvoices": { "Title": "Autofatture e integrazioni", "New": "Nuova autofattura" }, + "Movements": { "Title": "Movimenti di magazzino", "New": "Nuovo movimento" } }, "Kinds": { "Quotation": "Preventivo", @@ -173,7 +178,13 @@ "CreditNote": "TD04, storna in tutto o in parte una fattura.", "DebitNote": "TD05, aggiunge importi a una fattura.", "Fee": "TD06, per i professionisti, con ritenuta e cassa.", - "ProForma": "Non fiscale: anticipa la fattura al cliente." + "ProForma": "Non fiscale: anticipa la fattura al cliente.", + "SelfInvoice": "TD16-TD29: integra la fattura del fornitore o regolarizza un acquisto.", + "PurchaseOrder": "Ordine al fornitore: la merce ordinata entra nelle disponibilità.", + "PurchaseDeliveryNote": "Carica il magazzino al costo della riga, dall’ordine o libero.", + "PurchaseInvoice": "Registrata con protocollo e data IVA; carica la merce non ricevuta con DDT.", + "PurchaseCreditNote": "Storna una fattura del fornitore; restituisce la merce resa.", + "InventoryEntry": "Carico, scarico o trasferimento manuale con la sua causale." } }, "Lines": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index c52ec32..9948edc 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -74,7 +74,9 @@ "_": "Acquisti", "Orders": "Ordini fornitori", "Receipts": "Ricevimenti merce", - "Invoices": "Fatture passive" + "Invoices": "Fatture passive", + "Import": "Importa fatture", + "SelfInvoices": "Autofatture" }, "Inventory": { "_": "Magazzino", diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 4c5b190..aaa2319 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -63,9 +63,10 @@ public static class MenuCatalog Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", null, ("Shell.Menu.Sales.Quotes", "preventivi"), ("Shell.Menu.Sales.Orders", "ordini"), ("Shell.Menu.Sales.DeliveryNotes", "ddt"), ("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito"), ("Shell.Menu.Sales.DeferredInvoicing", "fatturazione-differita")), - Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", "M6", - ("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture")), - Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", "M6", + Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", null, + ("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture"), + ("Shell.Menu.Purchases.Import", "importa-fatture"), ("Shell.Menu.Purchases.SelfInvoices", "autofatture")), + Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", null, ("Shell.Menu.Inventory.Stock", "giacenze"), ("Shell.Menu.Inventory.Entries", "movimenti"), ("Shell.Menu.Inventory.StockTake", "inventario"), ("Shell.Menu.Inventory.Reorder", "riordino")), Area("Shell.Menu.Ledger", "book", "/contabilita", ModuleCodes.Accounting, "ledger.entry.read", "M7", diff --git a/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs index 9d97bdb..e1281b5 100644 --- a/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs +++ b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs @@ -152,7 +152,12 @@ public sealed class SalesFlowTests Assert.AreEqual("vendite/fatture/12", SalesScreens.RecordUrl(DocumentKind.Fee, 12)); Assert.AreEqual("vendite/note-credito/3", SalesScreens.RecordUrl(DocumentKind.DebitNote, 3)); Assert.AreEqual("vendite/ddt/nuovo?tipo=DDT", SalesScreens.NewUrl(SalesScreens.Find("ddt")!, "DDT")); - Assert.IsNull(SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1)); + Assert.AreEqual("acquisti/fatture/1", SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1)); + Assert.AreEqual("magazzino/movimenti/4", SalesScreens.RecordUrl(DocumentKind.InventoryEntry, 4)); + Assert.AreEqual(DocumentFamily.PurchaseDocument, SalesScreens.Find("acquisti", "fatture")!.Family); + Assert.IsNull(SalesScreens.Find("magazzino", "fatture")); + Assert.AreEqual("acquisti", SalesScreens.AreaOf("acquisti/fatture/3?x=1")); + Assert.AreEqual("Purchases.Fields.Supplier", SalesScreens.PartyLabel(SalesScreens.Find("acquisti", "autofatture")!.Direction)); // Each sales kind belongs to one radar only. var kinds = SalesScreens.Sections.SelectMany(s => s.Kinds).ToList(); diff --git a/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs b/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs new file mode 100644 index 0000000..d5acc32 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Inventory/PurchaseFlowTests.cs @@ -0,0 +1,148 @@ +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; + +/// +/// 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. +/// +[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(); + var copies = app.Services.GetRequiredService(); + var purchases = app.Services.GetRequiredService(); + var stock = app.Services.GetRequiredService(); + var vat22 = (await app.Services.GetRequiredService().ActiveAsync(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(() => 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(() => 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(); + var purchases = app.Services.GetRequiredService(); + var parties = app.Services.GetRequiredService(); + var taxes = await app.Services.GetRequiredService().ActiveAsync(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)); + } +}