using Khaemhat.Application.Documents; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Documents; using Khaemhat.Core.Items; using Khaemhat.Core.Parties; using Khaemhat.Core.Tables; using Khaemhat.Data; using Khaemhat.Data.Querying; using Khaemhat.Fiscal.Abstractions; namespace Khaemhat.Application.Purchases; /// A line of a supplier invoice whose price differs from the order or receipt it comes from (§11.5). /// The line of the invoice. /// Its description. /// The kind of the document it comes from. /// Its number. /// The net unit price there. /// The net unit price on the invoice. /// The quantity of the invoice line. public sealed record PriceDifference( int LineNumber, string Description, DocumentKind SourceKind, string? SourceNumber, decimal SourcePrice, decimal InvoicePrice, decimal Quantity) { /// The difference on the whole line: positive when the invoice costs more. public decimal Amount => Math.Round((InvoicePrice - SourcePrice) * Quantity, 2, MidpointRounding.AwayFromZero); } /// A supplier invoice that waits for its self-invoice (mockup 035). /// The invoice. /// The self-invoice it needs and by when. public sealed record PendingSelfInvoice(DocumentRow Invoice, SelfInvoiceAdvice Advice); /// /// The rules of purchases beyond the document engine (SPEC §11.5): price differences against orders and receipts, /// the self-invoice a supplier invoice needs (reverse charge, purchases from abroad) and its draft. /// /// Permissions purchases.invoice.read and write. public sealed class PurchaseService { /// Permission to read supplier invoices. public const string ReadPermission = "purchases.invoice.read"; /// Permission to register supplier invoices and self-invoices. public const string WritePermission = "purchases.invoice.write"; /// The supplier invoice does not need a self-invoice. public const string SelfInvoiceNotNeeded = "purchase.self-invoice.not-needed"; private readonly DocumentEngine _engine; private readonly DocumentCopyService _copies; private readonly DocumentEditor _editor; private readonly CompanyFiscalContext _packs; private readonly IUnitOfWorkFactory _factory; private readonly PermissionService _permissions; /// Creates the service. /// The document engine. /// Copies and transformations. /// The editor (radars). /// The fiscal pack of each company. /// The units of work. /// The permissions. public PurchaseService( DocumentEngine engine, DocumentCopyService copies, DocumentEditor editor, CompanyFiscalContext packs, IUnitOfWorkFactory factory, PermissionService permissions) { ArgumentNullException.ThrowIfNull(engine); ArgumentNullException.ThrowIfNull(copies); ArgumentNullException.ThrowIfNull(editor); ArgumentNullException.ThrowIfNull(packs); ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(permissions); _engine = engine; _copies = copies; _editor = editor; _packs = packs; _factory = factory; _permissions = permissions; } /// The lines of a supplier invoice whose net price differs from their order or receipt. /// Who reads. /// The company. /// The invoice, as on screen. /// Cancellation. /// The differences. public async Task> PriceDifferencesAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(record); var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); var result = new List(); if (record.Header.Kind is not (DocumentKind.PurchaseInvoice or DocumentKind.PurchaseDeliveryNote)) { return result; } await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var headers = new Dictionary<(DocumentFamily, long), DocumentHeader?>(); for (var i = 0; i < record.Lines.Count; i++) { var line = record.Lines[i]; if (line.SourceFamily is not { } family || line.SourceLineId is not { } sourceId || line.Quantity == 0m) { continue; } var source = await DocumentStores.Of(family).GetLineAsync(uow, sourceId, cancellationToken).ConfigureAwait(false); if (source is null || source.Quantity == 0m) { continue; } if (!headers.TryGetValue((family, source.DocumentId), out var header)) { header = await DocumentStores.Of(family).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false); headers[(family, source.DocumentId)] = header; } if (header is null) { continue; } var before = Math.Round(source.TaxableAmount / source.Quantity, 4, MidpointRounding.AwayFromZero); var now = Math.Round(line.TaxableAmount / line.Quantity, 4, MidpointRounding.AwayFromZero); if (before != now) { result.Add(new PriceDifference(i + 1, line.Description, header.Kind, header.DocumentNumber ?? header.ExternalReference, before, now, line.Quantity)); } } return result; } /// The self-invoice a supplier invoice needs, if any (reverse charge, purchase from abroad). /// Who reads. /// The company. /// The invoice. /// Cancellation. /// The advice, or . public async Task AdviseAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(record); var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); if (record.Header.Kind != DocumentKind.PurchaseInvoice || record.Header.PartyId is null) { return null; } var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); if (rules is null) { return null; } await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); return await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false); } /// /// The confirmed supplier invoices that need a self-invoice and have none yet, the nearest deadline first. /// /// Who reads. /// The company. /// Cancellation. /// The invoices with their advice. public async Task> PendingSelfInvoicesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) { var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false); var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature(); if (rules is null) { return []; } var rows = await _editor.ListAsync(actor, company, DocumentFamily.PurchaseDocument, [DocumentKind.PurchaseInvoice], new Querying.ListQuery { Limit = 500 }, cancellationToken) .ConfigureAwait(false); var result = new List(); await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var integrated = (await uow.Repository().ListAsync( Query.For().Where(l => l.SourceFamily == DocumentFamily.PurchaseDocument && l.TargetFamily == DocumentFamily.SaleDocument), cancellationToken) .ConfigureAwait(false)).Items.Select(l => l.SourceDocumentId).ToHashSet(); foreach (var row in rows.Items.Where(r => DocumentStateMachine.IsInForce(r.Status) && !integrated.Contains(r.Id))) { var record = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, row.Id, cancellationToken).ConfigureAwait(false); if (record is not null && await AdviseAsync(uow, rules, record, cancellationToken).ConfigureAwait(false) is { } advice) { result.Add(new PendingSelfInvoice(row, advice)); } } return [.. result.OrderBy(p => p.Advice.Deadline).ThenBy(p => p.Invoice.Date)]; } /// /// The draft self-invoice of a supplier invoice: its lines with the ordinary VAT code where the supplier wrote a /// nature, the supplier's number and date as the related invoice, today as date. /// /// Who creates. /// The company. /// The supplier invoice. /// The type, such as AF17; the advised one when empty. /// Cancellation. /// The draft, saved. /// No type was given and none is advised. public async Task CreateSelfInvoiceAsync(Actor actor, string companyCode, long purchaseInvoiceId, string? typeCode, CancellationToken cancellationToken = default) { var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false); var invoice = await _engine.GetAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).Require(); var code = typeCode; if (string.IsNullOrWhiteSpace(code)) { await using var read = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); code = (await AdviseAsync(read, rules, invoice, cancellationToken).ConfigureAwait(false))?.DocumentTypeCode ?? throw new ValidationFailedException([":" + SelfInvoiceNotNeeded]); } var draft = await _copies.CopyAsync(actor, company, DocumentFamily.PurchaseDocument, purchaseInvoiceId, code, null, cancellationToken).ConfigureAwait(false); var header = draft.Header; header.RelatedDocumentId = invoice.Header.Id; header.RelatedNumber = invoice.Header.ExternalReference; header.RelatedDate = invoice.Header.ExternalDate; header.ExternalReference = null; header.ExternalDate = null; header.InventoryReasonId = null; await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) { var taxes = (await uow.Repository().ListAsync(Query.For().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items; var ordinary = taxes.FirstOrDefault(t => t.Code == rules.OrdinaryTaxCode)?.Id; foreach (var line in draft.Lines) { // The supplier invoiced without VAT (a nature): the integration applies the rate. if (line.TaxCodeId is { } id && taxes.FirstOrDefault(t => t.Id == id) is { Nature: not null } && ordinary is not null) { line.TaxCodeId = ordinary; } } } return await _engine.SaveAsync(actor, company, draft, cancellationToken).ConfigureAwait(false); } private static async Task AdviseAsync(IUnitOfWork uow, ISelfInvoiceRules rules, DocumentRecord record, CancellationToken cancellationToken) { if (record.Header.PartyId is not { } partyId || await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { } party) { return null; } var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant(); var inEu = (await uow.Repository().FindAsync(Query.For().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false; var taxIds = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).Distinct().ToList(); var natures = taxIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(t => taxIds.Contains(t.Id)), cancellationToken) .ConfigureAwait(false)).Items.Where(t => t.Nature is not null).Select(t => t.Nature!).Distinct().ToList(); var itemIds = record.Lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().ToList(); var kinds = itemIds.Count == 0 ? [] : (await uow.Repository().ListAsync(Query.For().Where(i => itemIds.Contains(i.Id)), cancellationToken) .ConfigureAwait(false)).Items.ToDictionary(i => i.Id, i => i.Kind); // Goods when the item lines of goods weigh more than the rest; free lines count as services. var goods = record.Lines.Where(l => l.ItemId is { } id && kinds.GetValueOrDefault(id) == ItemKind.Goods).Sum(l => Math.Abs(l.TaxableAmount)); var other = record.Lines.Where(l => l.Kind != DocumentLineKind.Description).Sum(l => Math.Abs(l.TaxableAmount)) - goods; var received = record.Header.VatDate ?? record.Header.DocumentDate; return rules.Advise(new SelfInvoiceCase(country, inEu && country != "IT", goods > other, natures, received)); } }