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

@@ -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));
}
}