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