using Khaemhat.Application.Items; using Khaemhat.Application.Modules; using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Items; using Khaemhat.Core.Parties; using Khaemhat.Core.Tables; using Khaemhat.Data; using Khaemhat.Data.Querying; namespace Khaemhat.Application.ImportExport; /// /// The prices of the lists and the net prices of the customers (SPEC ยง12.12): each row is the price of an item in a list /// or for a customer, valid from a day; the same item, list or customer and day replaces the price, another day adds a /// dated price as the price grid does. All rows are written by in one transaction. /// /// The price lists. /// Opens the company databases. /// Checks the permission. public sealed class PricesImportTarget(PriceListService prices, IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget { private static readonly ImportField[] PriceFields = [ new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]), new("listino", ImportFieldKind.Code, Aliases: ["codice_listino", "cod_listino"]), new("cliente", ImportFieldKind.Code, Aliases: ["codice_cliente", "cod_cliente"]), new("prezzo", ImportFieldKind.Number, Required: true, Aliases: ["prezzo_netto", "price"]), new("valido_dal", ImportFieldKind.Date, Aliases: ["validita", "data_inizio", "dal", "decorrenza"]), ]; /// public string Key => "listini"; /// public string ModuleCode => ModuleCodes.Core; /// public string Permission => ItemService.WritePermission; /// public string ExportPermission => ItemService.ReadPermission; /// public bool CanApply => true; /// public bool CanExport => true; /// public IReadOnlyList Fields => PriceFields; /// public async Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => (await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false)).Results; /// public async Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) { var plan = await PlanAsync(context, rows, cancellationToken).ConfigureAwait(false); if (plan.Edits.Count == 0) { return plan.Results; } try { await prices.SaveAsync(context.Actor, context.CompanyCode, [.. plan.Edits.Select(e => e.Edit)], cancellationToken).ConfigureAwait(false); return plan.Results; } catch (ValidationFailedException ex) { // The rows were checked already: an error here is a change made meanwhile; it goes on its row and nothing is written. var results = plan.Results.ToList(); foreach (var (index, code) in ex.Errors.Select(TableErrors.Split)) { var position = int.TryParse(index, out var i) && i >= 0 && i < plan.Edits.Count ? plan.Edits[i].Result : -1; if (position >= 0) { var row = results[position]; results[position] = row with { Action = ImportAction.Skip, Messages = [.. row.Messages, new ImportMessage("prezzo", code)] }; } } return [.. results.Select(r => r.Outcome == ImportOutcome.Error ? r : r with { Action = ImportAction.Skip, Messages = [.. r.Messages, new ImportMessage(string.Empty, ImportErrors.WriteFailed)] })]; } } /// public async Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, ExportPermission, cancellationToken).ConfigureAwait(false); await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var items = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id))); var parties = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(p => (p.Code, p.Id))); var lists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); var rows = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; return [ .. rows.Select(p => (IReadOnlyList)[items.CodeOf(p.ItemId), lists.CodeOf(p.PriceListId), parties.CodeOf(p.PartyId), p.Price, p.ValidFrom]) .OrderBy(r => (string?)r[0], StringComparer.OrdinalIgnoreCase) .ThenBy(r => (string?)r[1] ?? "~" + (string?)r[2], StringComparer.OrdinalIgnoreCase) .ThenBy(r => (DateOnly?)r[4]), ]; } private async Task PlanAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(rows); var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false); await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); var items = new CodeIndex((await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items.Select(i => (i.Code, i.Id))); var allParties = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; var customers = new CodeIndex(allParties.Where(p => p.IsCustomer).Select(p => (p.Code, p.Id))); var others = new HashSet(allParties.Where(p => !p.IsCustomer).Select(p => p.Code), StringComparer.OrdinalIgnoreCase); var lists = await CodeIndex.LoadAsync(uow, cancellationToken).ConfigureAwait(false); var existing = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items .Select(p => (p.ItemId, p.PriceListId, p.PartyId, p.ValidFrom)).ToHashSet(); var seen = new HashSet<(long, long?, long?, DateOnly?)>(); var results = new List(rows.Count); var edits = new List<(PriceEdit Edit, int Result)>(); foreach (var row in rows) { var messages = new List(); var cells = new CellReader(row, messages); var item = cells.Code("articolo", items); long? list = null; long? party = null; if (cells.Has("listino") == cells.Has("cliente")) { messages.Add(new(cells.Has("listino") ? "cliente" : "listino", ImportErrors.PriceTarget)); } else if (cells.Has("listino")) { list = cells.Code("listino", lists); } else if (row["cliente"] is { } customer && others.Contains(customer)) { messages.Add(new("cliente", ImportErrors.OtherKind, Value: customer)); } else { party = cells.Code("cliente", customers); } var price = cells.Number("prezzo"); if (price < 0) { messages.Add(new("prezzo", ItemService.NotNegative)); } var from = cells.Date("valido_dal"); messages.AddRange(PriceFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required))); var label = row["articolo"] ?? string.Empty; if (messages.Any(m => !m.IsWarning) || item is not { } itemId || price is not { } value) { results.Add(new(row.Line, label, ImportAction.Skip, messages)); continue; } var key = (itemId, list, party, from); if (!seen.Add(key)) { messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label)); results.Add(new(row.Line, label, ImportAction.Skip, messages)); continue; } var update = existing.Contains(key); if (update && context.Options.Existing == ExistingCodeAction.Skip) { results.Add(new(row.Line, label, ImportAction.Skip, [new("articolo", ImportErrors.CodeExists, IsWarning: true, Value: label)])); continue; } edits.Add((new PriceEdit(itemId, list, party, value, from), results.Count)); results.Add(new(row.Line, label, update ? ImportAction.Update : ImportAction.Create, messages)); } return new Plan(results, edits); } private sealed record Plan(IReadOnlyList Results, IReadOnlyList<(PriceEdit Edit, int Result)> Edits); }