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)
{