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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 21:25:25 +01:00
1 parent eeabb12f96
commit f8b72f4d17
21 files changed
+823 -58

No files matched your search

@@ -90,6 +90,15 @@ public static class DocumentErrors
/// <summary>Error: a line of an invoice without its VAT code.</summary>
public const string LineTaxRequired = "document.line.tax-required";
/// <summary>A supplier invoice needs the number and date the supplier gave it.</summary>
public const string SupplierNumberRequired = "document.purchase.number-required";
/// <summary>The same supplier already has a document of the kind with that number in that year.</summary>
public const string SupplierDuplicate = "document.purchase.duplicate";
/// <summary>The VAT date comes before the date of the supplier document.</summary>
public const string VatDateBefore = "document.purchase.vat-date-before";
}
/// <summary>
@@ -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<string> 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<PurchaseDocument, long>().ListAsync(
Query.For<PurchaseDocument>().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);
@@ -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;
/// </summary>
public static class InventoryPoster
{
/// <summary>A transfer needs a destination different from the origin.</summary>
public const string TransferDestination = "document.transfer.destination";
/// <summary>Writes again the movements of a document from its current state and refreshes its items.</summary>
/// <param name="uow">The unit of work of the company, in a transaction.</param>
/// <param name="family">The family of the document.</param>
@@ -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<StockMovement> 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<List<StockLineInput>> StockLinesAsync(IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, CancellationToken cancellationToken)
private static async Task<List<StockLineInput>> StockLinesAsync(
IUnitOfWork uow, DocumentHeader header, IReadOnlyList<DocumentLine> lines, int sign, CancellationToken cancellationToken)
{
var result = new List<StockLineInput>();
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<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().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<long>>();
var moved = new Dictionary<(DocumentFamily, long), Dictionary<long, int>>();
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<bool> AlreadyMovedAsync(
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), HashSet<long>> moved, CancellationToken cancellationToken)
// How a line of another document moved the stock: 1 loaded, -1 unloaded, 0 not at all.
private static async Task<int> MovedSignAsync(
IUnitOfWork uow, DocumentFamily sourceFamily, long sourceLineId, Dictionary<(DocumentFamily, long), Dictionary<long, int>> 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(
@@ -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;
/// <summary>A line of a supplier invoice whose price differs from the order or receipt it comes from (§11.5).</summary>
/// <param name="LineNumber">The line of the invoice.</param>
/// <param name="Description">Its description.</param>
/// <param name="SourceKind">The kind of the document it comes from.</param>
/// <param name="SourceNumber">Its number.</param>
/// <param name="SourcePrice">The net unit price there.</param>
/// <param name="InvoicePrice">The net unit price on the invoice.</param>
/// <param name="Quantity">The quantity of the invoice line.</param>
public sealed record PriceDifference(
int LineNumber, string Description, DocumentKind SourceKind, string? SourceNumber, decimal SourcePrice, decimal InvoicePrice, decimal Quantity)
{
/// <summary>The difference on the whole line: positive when the invoice costs more.</summary>
public decimal Amount => Math.Round((InvoicePrice - SourcePrice) * Quantity, 2, MidpointRounding.AwayFromZero);
}
/// <summary>A supplier invoice that waits for its self-invoice (mockup 035).</summary>
/// <param name="Invoice">The invoice.</param>
/// <param name="Advice">The self-invoice it needs and by when.</param>
public sealed record PendingSelfInvoice(DocumentRow Invoice, SelfInvoiceAdvice Advice);
/// <summary>
/// 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.
/// </summary>
/// <remarks>Permissions <c>purchases.invoice.read</c> and <c>write</c>.</remarks>
public sealed class PurchaseService
{
/// <summary>Permission to read supplier invoices.</summary>
public const string ReadPermission = "purchases.invoice.read";
/// <summary>Permission to register supplier invoices and self-invoices.</summary>
public const string WritePermission = "purchases.invoice.write";
/// <summary>The supplier invoice does not need a self-invoice.</summary>
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;
/// <summary>Creates the service.</summary>
/// <param name="engine">The document engine.</param>
/// <param name="copies">Copies and transformations.</param>
/// <param name="editor">The editor (radars).</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
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;
}
/// <summary>The lines of a supplier invoice whose net price differs from their order or receipt.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The invoice, as on screen.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The differences.</returns>
public async Task<IReadOnlyList<PriceDifference>> 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<PriceDifference>();
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;
}
/// <summary>The self-invoice a supplier invoice needs, if any (reverse charge, purchase from abroad).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The advice, or <see langword="null"/>.</returns>
public async Task<SelfInvoiceAdvice?> 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<ISelfInvoiceRules>();
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);
}
/// <summary>
/// The confirmed supplier invoices that need a self-invoice and have none yet, the nearest deadline first.
/// </summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices with their advice.</returns>
public async Task<IReadOnlyList<PendingSelfInvoice>> 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<ISelfInvoiceRules>();
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<PendingSelfInvoice>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var integrated = (await uow.Repository<DocumentLink, long>().ListAsync(
Query.For<DocumentLink>().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)];
}
/// <summary>
/// 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.
/// </summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="purchaseInvoiceId">The supplier invoice.</param>
/// <param name="typeCode">The type, such as <c>AF17</c>; the advised one when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft, saved.</returns>
/// <exception cref="ValidationFailedException">No type was given and none is advised.</exception>
public async Task<DocumentRecord> 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<ISelfInvoiceRules>();
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<TaxCode, long>().ListAsync(Query.For<TaxCode>().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<SelfInvoiceAdvice?> AdviseAsync(IUnitOfWork uow, ISelfInvoiceRules rules, DocumentRecord record, CancellationToken cancellationToken)
{
if (record.Header.PartyId is not { } partyId || await uow.Repository<Party, long>().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<Country, long>().FindAsync(Query.For<Country>().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<TaxCode, long>().ListAsync(Query.For<TaxCode>().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<Item, long>().ListAsync(Query.For<Item>().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));
}
}
@@ -273,3 +273,41 @@ public interface IPlaceDirectory
/// <summary>The municipalities.</summary>
IReadOnlyList<MunicipalityTemplate> Municipalities { get; }
}
/// <summary>What a received invoice tells about the self-invoice it may need.</summary>
/// <param name="SupplierCountry">The country of the supplier (ISO 3166-1 alpha-2).</param>
/// <param name="SupplierInEu">The supplier is in another member state of the European Union.</param>
/// <param name="Goods">The invoice is mostly for goods (otherwise services).</param>
/// <param name="Natures">The VAT natures of its lines (codes of the country's e-invoice format), if any.</param>
/// <param name="Received">The day it was received or registered.</param>
public sealed record SelfInvoiceCase(string SupplierCountry, bool SupplierInEu, bool Goods, IReadOnlyCollection<string> Natures, DateOnly Received);
/// <summary>The self-invoice a received invoice needs.</summary>
/// <param name="DocumentTypeCode">The document type of the base tables, such as <c>AF17</c>.</param>
/// <param name="Reason">Why, in the language of the users.</param>
/// <param name="Deadline">The last day to issue it.</param>
public sealed record SelfInvoiceAdvice(string DocumentTypeCode, string Reason, DateOnly Deadline);
/// <summary>
/// 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.
/// </summary>
public interface ISelfInvoiceRules
{
/// <summary>The document types of self-invoices, in the order of the menu.</summary>
IReadOnlyList<string> DocumentTypeCodes { get; }
/// <summary>The VAT code (of the base tables) of the ordinary rate, proposed on the lines of an integration.</summary>
string OrdinaryTaxCode { get; }
/// <summary>The self-invoice a received invoice needs, if any.</summary>
/// <param name="input">The invoice.</param>
/// <returns>The advice, or <see langword="null"/> when none is needed.</returns>
SelfInvoiceAdvice? Advise(SelfInvoiceCase input);
/// <summary>The last day to issue a self-invoice of a type for an invoice received on a day.</summary>
/// <param name="documentTypeCode">The type.</param>
/// <param name="received">The day the invoice was received (or the operation took place).</param>
/// <returns>The deadline.</returns>
DateOnly Deadline(string documentTypeCode, DateOnly received);
}
@@ -16,6 +16,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
{
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
@@ -0,0 +1,59 @@
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// 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.
/// </summary>
public sealed class SelfInvoiceRulesIt : ISelfInvoiceRules
{
/// <inheritdoc />
public IReadOnlyList<string> DocumentTypeCodes { get; } = ["AF16", "AF17", "AF18", "AF19", "AF20", "AF21", "AF22", "AF23", "AF28", "AF29"];
/// <inheritdoc />
public string OrdinaryTaxCode => "22";
/// <inheritdoc />
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);
}
/// <inheritdoc />
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));
}
@@ -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<DocumentRecord, DocumentLine>
@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. *@
<KhPageTitle Text="@PageTitle" Icon="@(_section?.Icon ?? "file")" />
@@ -47,7 +52,7 @@ else
<KhRecordLayout Page="this">
<Heading>
<KhDocHead KindIcon="@_section.Icon" KindLabel="@_definition.Type.Description" Number="@(h.DocumentNumber ?? T["Sales.DraftNumber"])"
PartyName="@(_party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
PartyName="@(IsInternal ? (PartyScreens.Describe(_lookups.InventoryReasons, h.InventoryReasonId) ?? T["Inventory.NoReason"]) : _party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
TotalLabel="@T[ShowsNet ? "Sales.Totals.Net" : "Sales.Totals.Total"]" TotalValue="@T.Money(ShowsNet ? h.NetAmount : h.TotalAmount)" SubValues="HeadStats">
<Facts>
<span>@T["Sales.Fields.DocumentDate"] <b>@T.Date(h.DocumentDate)</b></span>
@@ -104,7 +109,7 @@ else
@switch (ActiveTab)
{
case TabIds.Lines:
@if (h.PartyId is null && !IsReadOnly)
@if (h.PartyId is null && !IsReadOnly && !IsInternal)
{
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
<button type="button" class="btn" @onclick="() => ShowTabAsync(TabIds.Header)">@T["Sales.Actions.ChooseParty"]</button></div>
@@ -143,9 +148,17 @@ else
{
<KhDateBox Label="@T["Sales.Fields.DeliveryDate"]" Name="DeliveryDate" Value="h.DeliveryDate" ValueChanged="v => Change(() => h.DeliveryDate = v)" Span="4" />
}
<KhTextBox Label="@T["Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference" ValueChanged="v => Change(() => h.ExternalReference = v)"
Span="8" MaxLength="60" Hint="@T["Sales.Hints.ExternalReference"]" />
<KhDateBox Label="@T["Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate" ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" />
<KhTextBox Label="@T[IsPurchase ? "Purchases.Fields.SupplierNumber" : "Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference"
ValueChanged="v => Change(() => h.ExternalReference = v)" Span="8" MaxLength="40" Required="@IsRegistered"
Hint="@T[IsPurchase ? "Purchases.Hints.SupplierNumber" : "Sales.Hints.ExternalReference"]" Mono="@IsPurchase" />
<KhDateBox Label="@T[IsPurchase ? "Purchases.Fields.SupplierDate" : "Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate"
ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" Required="@IsRegistered" />
@if (IsRegistered)
{
<KhTextBox Label="@T["Purchases.Fields.Protocol"]" Name="VatProtocol" Value="@(h.VatProtocol?.ToString(T.Culture) ?? T["Sales.NumberOnConfirm"])" ReadOnly="true" Mono="true" Span="4" />
<KhDateBox Label="@T["Purchases.Fields.VatDate"]" Name="VatDate" Value="h.VatDate" ValueChanged="v => Change(() => h.VatDate = v)" Span="4"
Hint="@T["Purchases.Hints.VatDate"]" />
}
@if (IsNote)
{
<KhTextBox Label="@T["Sales.Fields.RelatedNumber"]" Name="RelatedNumber" Value="@h.RelatedNumber" ValueChanged="v => Change(() => h.RelatedNumber = v)"
@@ -153,11 +166,31 @@ else
<KhDateBox Label="@T["Sales.Fields.RelatedDate"]" Name="RelatedDate" Value="h.RelatedDate" ValueChanged="v => Change(() => h.RelatedDate = v)" Span="4" />
}
</KhFieldGroup>
@if (IsInternal)
{
<KhFieldGroup Title="@T["Inventory.Groups.Movement"]" Icon="layers">
<KhSelect TValue="string" Label="@T["Inventory.Fields.Reason"]" Name="InventoryReasonId" Options="_lookups.InventoryReasons" Empty="" Span="6" Required="true"
Value="@PartyScreens.Text(h.InventoryReasonId)" ValueChanged="v => Change(() => h.InventoryReasonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T[IsTransfer ? "Inventory.Fields.FromWarehouse" : "Inventory.Fields.Warehouse"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
Value="@PartyScreens.Text(h.WarehouseId)" ValueChanged="v => Change(() => h.WarehouseId = PartyScreens.Id(v))" />
@if (IsTransfer)
{
<KhSelect TValue="string" Label="@T["Inventory.Fields.ToWarehouse"]" Name="ToWarehouseId" Options="_lookups.Warehouses" Empty="" Span="6" Required="true"
Value="@PartyScreens.Text(h.ToWarehouseId)" ValueChanged="v => Change(() => h.ToWarehouseId = PartyScreens.Id(v))" />
}
<p class="muted sm c12"><KhIcon Name="info" /> @T["Inventory.Hints.Movement"]</p>
</KhFieldGroup>
}
else
{
<KhFieldGroup Title="@T["Sales.Groups.Party"]" Icon="users">
<KhHotlink TItem="PartyRow" Label="@T["Sales.Fields.PartyId"]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
<KhHotlink TItem="PartyRow" Label="@T[SalesScreens.PartyLabel(_section.Direction)]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
Search="SearchPartiesAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenParty" ReadOnly="@(Record.Lines.Any(l => l.SourceLineId is not null))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
@if (!IsPurchase)
{
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
}
<KhSelect TValue="string" Label="@T["Sales.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_lookups.Currencies" Span="6"
Value="@h.CurrencyCode" ValueChanged="SetCurrency" />
@if (h.PartyId is not null)
@@ -203,6 +236,7 @@ else
<p class="muted sm c9">@T["Sales.Hints.Withholding"]</p>
</KhFieldGroup>
}
}
</KhForm>
break;
@@ -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;
/// <inheritdoc />
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<IReadOnlyList<PartyRow>> 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,
};
@@ -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. *@
<KhPageTitle Text="@Title" Icon="@(_section?.Icon ?? "cart")" />
@if (!_loaded)
@@ -36,7 +39,7 @@ else if (!CanRead)
}
else
{
<KhRadar TItem="DocumentRow" @key="_section.Segment" Id="@("sales." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
<KhRadar TItem="DocumentRow" @key="_section.Area + _section.Segment" Id="@(_section.Area == SalesScreens.BasePath ? "sales." + _section.Segment : _section.Area + "." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
Label="@Title">
<Toolbar>
@@ -44,7 +47,7 @@ else
{
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Sales.Sections." + _section.Key + ".New"]</button>
}
@if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
@if (_section.Area == SalesScreens.BasePath && _section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
{
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
}
@@ -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<KhColumn<DocumentRow>> 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);
@@ -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);
/// <inheritdoc />
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;
@@ -33,6 +33,12 @@ public sealed class DocumentLookups
/// <summary>Warehouses.</summary>
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
/// <summary>Warehouse reasons (causali di magazzino).</summary>
public IReadOnlyList<KhOption<string>> InventoryReasons { get; private init; } = [];
/// <summary>The ids of the reasons that move goods between two warehouses.</summary>
public IReadOnlySet<long> TransferReasons { get; private init; } = new HashSet<long>();
/// <summary>Carriers.</summary>
public IReadOnlyList<KhOption<string>> Carriers { get; private init; } = [];
@@ -68,6 +74,8 @@ public sealed class DocumentLookups
Salespeople = await ReadAsync<Salesperson>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
BankAccounts = await ReadAsync<BankAccount>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
InventoryReasons = await ReadAsync<InventoryReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TransferReasons = (await tables.ActiveAsync<InventoryReason>(actor, company, cancellationToken).ConfigureAwait(false)).Where(r => r.IsTransfer).Select(r => r.Id).ToHashSet(),
Carriers = await ReadAsync<Carrier>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
ShippingTerms = await ReadAsync<ShippingTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TransportReasons = await ReadAsync<TransportReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
+49 -8
View File
@@ -5,24 +5,37 @@ using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>A radar of the sales menu and the document types it holds.</summary>
/// <summary>A radar of the documents menus (sales, purchases, warehouse) and the document types it holds.</summary>
/// <param name="Segment">The path segment, such as <c>fatture</c>.</param>
/// <param name="Family">The family of the documents.</param>
/// <param name="Kinds">The kinds shown.</param>
/// <param name="NewTypes">The document types a user can create from the radar, the first being the usual one.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Key">The key of the texts under <c>Sales.Sections</c>.</param>
public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key);
/// <param name="Area">The menu area, such as <c>vendite</c> or <c>acquisti</c>.</param>
public sealed record SalesSection(
string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key, string Area = SalesScreens.BasePath)
{
/// <summary>Whose documents: customers, suppliers or nobody.</summary>
public DocumentDirection Direction => DocumentBehaviors.Of(Kinds[0]).Direction;
}
/// <summary>
/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under
/// <c>/vendite</c>, 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
/// <c>/vendite</c>, <c>/acquisti</c> and <c>/magazzino</c>, 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).
/// </summary>
public static class SalesScreens
{
/// <summary>The menu area.</summary>
/// <summary>The sales area.</summary>
public const string BasePath = "vendite";
/// <summary>The purchases area.</summary>
public const string PurchasesPath = "acquisti";
/// <summary>The warehouse area.</summary>
public const string InventoryPath = "magazzino";
/// <summary>The deferred invoicing of the delivery notes.</summary>
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),
];
/// <summary>The radar of a path segment.</summary>
/// <summary>The sales radar of a path segment.</summary>
/// <param name="segment">The segment.</param>
/// <returns>The radar, or <see langword="null"/>.</returns>
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);
/// <summary>The radar of an area and a path segment.</summary>
/// <param name="area">The area, such as <c>acquisti</c>.</param>
/// <param name="segment">The segment.</param>
/// <returns>The radar, or <see langword="null"/>.</returns>
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));
/// <summary>The area of a relative address: its first segment.</summary>
/// <param name="relativePath">The address relative to the base, such as <c>acquisti/fatture/3</c>.</param>
/// <returns>The area.</returns>
public static string AreaOf(string? relativePath)
{
var path = relativePath ?? string.Empty;
var end = path.IndexOfAny(['/', '?', '#']);
return end < 0 ? path : path[..end];
}
/// <summary>The key of the label of the party for a direction: customer, supplier.</summary>
/// <param name="direction">The direction.</param>
/// <returns>The key of the text.</returns>
public static string PartyLabel(DocumentDirection direction) => direction == DocumentDirection.Purchase ? "Purchases.Fields.Supplier" : "Sales.Fields.PartyId";
/// <summary>The radar that holds a kind of document.</summary>
/// <param name="kind">The kind.</param>
@@ -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;
}
/// <summary>The address of a document.</summary>
@@ -147,6 +147,7 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
services.AddSingleton<Khaemhat.Application.Inventory.InventoryService>();
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseService>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
@@ -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.",
@@ -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."
}
}
}
@@ -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."
}
}
}
+13 -2
View File
@@ -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": {
+3 -1
View File
@@ -74,7 +74,9 @@
"_": "Acquisti",
"Orders": "Ordini fornitori",
"Receipts": "Ricevimenti merce",
"Invoices": "Fatture passive"
"Invoices": "Fatture passive",
"Import": "Importa fatture",
"SelfInvoices": "Autofatture"
},
"Inventory": {
"_": "Magazzino",
+4 -3
View File
@@ -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",
@@ -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();
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<DocumentEngine>();
var copies = app.Services.GetRequiredService<DocumentCopyService>();
var purchases = app.Services.GetRequiredService<PurchaseService>();
var stock = app.Services.GetRequiredService<InventoryService>();
var vat22 = (await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<DocumentEngine>();
var purchases = app.Services.GetRequiredService<PurchaseService>();
var parties = app.Services.GetRequiredService<PartyService>();
var taxes = await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(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));
}
}