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:
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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user