using Khaemhat.Application.Security; using Khaemhat.Application.Tables; using Khaemhat.Core.Tables; using Khaemhat.Data; using Khaemhat.Data.Querying; namespace Khaemhat.Application.ImportExport; /// /// An entity of the guided import and export (SPEC ยง12.12): its columns, the check of the rows as if typed in its /// record, the writing through its own service, and the export with the same columns so that a file exported can be /// imported again. /// public interface IImportTarget { /// The key in addresses and texts (clienti, piano-dei-conti). string Key { get; } /// The licence module the entity belongs to. string ModuleCode { get; } /// The permission to import it (the write permission of its record). string Permission { get; } /// The permission to export it (besides the can export flag of the user). string ExportPermission { get; } /// Whether rows can be written now; otherwise the file is only checked (opening stock until M6, chart of accounts until M7). bool CanApply { get; } /// Whether there are records to export now. bool CanExport { get; } /// The columns, in the order of templates and exports. IReadOnlyList Fields { get; } /// Checks the rows without writing. /// Who, where, how. /// The rows. /// Cancellation. /// A result per row, in order. Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken); /// Writes the rows without errors, each like a save of its record. /// Who, where, how. /// The rows. /// Cancellation. /// A result per row, in order, with what was done. Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken); /// The records as rows of cells in the order of . /// Who, where. /// Cancellation. /// The rows. Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken); } /// Reads the cells of a row as values, adding a remark for every cell that is not what its field wants. /// The row. /// Where the remarks go. public sealed class CellReader(ImportRow row, List messages) { /// The row. public ImportRow Row => row; /// The remarks so far. public List Messages => messages; /// Whether the cell has a value. /// The field. /// when not empty. public bool Has(string key) => row[key] is not null; /// The text of a cell. /// The field. /// The text, or . public string? Text(string key) => row[key]; /// A number. /// The field. /// The number, or when empty or wrong (with a remark). public decimal? Number(string key) { if (row[key] is not { } text) { return null; } if (ImportValues.TryNumber(text, out var value)) { return value; } messages.Add(new(key, ImportErrors.Number, Value: text)); return null; } /// A date. /// The field. /// The date, or when empty or wrong (with a remark). public DateOnly? Date(string key) { if (row[key] is not { } text) { return null; } if (ImportValues.TryDate(text, out var value)) { return value; } messages.Add(new(key, ImportErrors.Date, Value: text)); return null; } /// Yes or no. /// The field. /// The value, or when empty or wrong (with a remark). public bool? Boolean(string key) { if (row[key] is not { } text) { return null; } if (ImportValues.TryBoolean(text, out var value)) { return value; } messages.Add(new(key, ImportErrors.Boolean, Value: text)); return null; } /// One of the words of a field. /// The field with its choices. /// The position of the word, or when empty or unknown (with a remark). public int? Choice(ImportField field) { ArgumentNullException.ThrowIfNull(field); if (row[field.Key] is not { } text) { return null; } var choices = field.Choices ?? []; var index = ImportValues.Choice(text, choices); if (index >= 0) { return index; } messages.Add(new(field.Key, ImportErrors.Choice, Value: string.Join(", ", choices))); return null; } /// The id of a code of another archive or table. /// The field. /// The codes. /// The id, or when empty or unknown (with a remark). public long? Code(string key, CodeIndex index) { ArgumentNullException.ThrowIfNull(index); if (row[key] is not { } code) { return null; } if (index.Find(code) is { } id) { return id; } messages.Add(new(key, ImportErrors.CodeUnknown, Value: code)); return null; } } /// The ids of the records of an archive or table by code, ignoring case. public sealed class CodeIndex { private readonly Dictionary _ids = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _codes = []; /// Creates an index. /// The codes with their ids. public CodeIndex(IEnumerable<(string Code, long Id)> entries) { ArgumentNullException.ThrowIfNull(entries); foreach (var (code, id) in entries) { _ids.TryAdd(code, id); _codes[id] = code; } } /// The number of codes. public int Count => _ids.Count; /// Loads the codes of a table of the company. /// The table. /// The unit of work. /// Cancellation. /// The index. public static async Task LoadAsync(IUnitOfWork uow, CancellationToken cancellationToken) where T : CodedEntity, new() { ArgumentNullException.ThrowIfNull(uow); var rows = await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false); return new CodeIndex(rows.Items.Select(r => (r.Code, r.Id))); } /// The id of a code. /// The code. /// The id, or . public long? Find(string? code) => code is not null && _ids.TryGetValue(code.Trim(), out var id) ? id : null; /// The code of an id. /// The id. /// The code, or . public string? CodeOf(long? id) => id is { } key && _codes.TryGetValue(key, out var code) ? code : null; /// Adds a code written meanwhile. /// The code. /// The id. public void Add(string code, long id) { ArgumentNullException.ThrowIfNull(code); _ids[code] = id; _codes[id] = code; } } /// /// The common steps of the entities written as records (parties, items): each row becomes a record, new or read by its /// code, checked by the service of the record and saved by it, so the import obeys the same rules as the screen. /// /// The record. /// What is loaded once per check or import (codes of tables and archives). public abstract class RecordImportTarget : IImportTarget where TRecord : class { /// public abstract string Key { get; } /// public abstract string ModuleCode { get; } /// public abstract string Permission { get; } /// public abstract string ExportPermission { get; } /// public bool CanApply => true; /// public bool CanExport => true; /// public abstract IReadOnlyList Fields { get; } /// The column with the code of the record. protected virtual string CodeField => "codice"; /// public Task> CheckAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => RunAsync(context, rows, write: false, cancellationToken); /// public Task> ApplyAsync(ImportContext context, IReadOnlyList rows, CancellationToken cancellationToken) => RunAsync(context, rows, write: true, cancellationToken); /// public abstract Task>> ExportAsync(ImportContext context, CancellationToken cancellationToken); /// Loads what every row needs, checking a permission. /// Who, where, how. /// The permission demanded (to import or to export). /// Cancellation. /// The state. protected abstract Task LoadAsync(ImportContext context, string permission, CancellationToken cancellationToken); /// The id of an existing record with a code, or ; a remark refuses the code (another kind). /// The state. /// The code. /// Where remarks go. /// The id. protected abstract long? Existing(TState state, string code, List messages); /// A new record, or an existing one read by id. /// Who, where. /// The id, or for a new record. /// Cancellation. /// The record. protected abstract Task OpenAsync(ImportContext context, long? id, CancellationToken cancellationToken); /// Copies the cells of a row into the record; a code given for a new record is set too. /// Who, where, how. /// The state. /// The record. /// The row with its remarks. /// Whether the record is new. /// Cancellation. /// A task. protected abstract Task FillAsync(ImportContext context, TState state, TRecord record, CellReader cells, bool isNew, CancellationToken cancellationToken); /// Checks a record with the rules of its service. /// Who, where. /// The record. /// Whether the record is new (its code is checked against the code rules). /// Cancellation. /// The problems. protected abstract Task> ValidateAsync(ImportContext context, TRecord record, bool isNew, CancellationToken cancellationToken); /// Saves a record with its service. /// Who, where, how. /// The record. /// Cancellation. /// The code and id given by the save. protected abstract Task<(string Code, long Id)> SaveAsync(ImportContext context, TRecord record, CancellationToken cancellationToken); /// What identifies the row in the preview (code, else description). /// The row. /// The text. protected abstract string Label(ImportRow row); /// Records a code saved, so that later rows find it. /// The state. /// The code. /// The id. protected abstract void Remember(TState state, string code, long id); /// The column of a field of the service (VatNumber, Fiscal.RecipientCode); empty for the row. /// The field named by the service. /// The column key. protected abstract string ColumnOf(string serviceField); private async Task> RunAsync(ImportContext context, IReadOnlyList rows, bool write, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(rows); var state = await LoadAsync(context, Permission, cancellationToken).ConfigureAwait(false); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); var results = new List(rows.Count); foreach (var row in rows) { cancellationToken.ThrowIfCancellationRequested(); var messages = new List(); var cells = new CellReader(row, messages); var code = row[CodeField]; long? id = null; if (code is not null) { if (!seen.Add(code)) { messages.Add(new(CodeField, ImportErrors.CodeRepeated, Value: code)); results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); continue; } id = Existing(state, code, messages); if (messages.Count > 0) { results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); continue; } if (id is not null && context.Options.Existing == ExistingCodeAction.Skip) { results.Add(new(row.Line, Label(row), ImportAction.Skip, [new(CodeField, ImportErrors.CodeExists, IsWarning: true, Value: code)])); continue; } } else if (context.Options.Missing == MissingCodeAction.Refuse) { messages.Add(new(CodeField, ImportErrors.CodeMissing)); results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); continue; } var isNew = id is null; var action = isNew ? ImportAction.Create : ImportAction.Update; var record = await OpenAsync(context, id, cancellationToken).ConfigureAwait(false); if (record is null) { messages.Add(new(CodeField, ImportErrors.WriteFailed, Value: code)); results.Add(new(row.Line, Label(row), ImportAction.Skip, messages)); continue; } await FillAsync(context, state, record, cells, isNew, cancellationToken).ConfigureAwait(false); if (isNew) { messages.AddRange(Fields.Where(f => f.Required && !cells.Has(f.Key) && messages.All(m => m.Field != f.Key)) .Select(f => new ImportMessage(f.Key, ImportErrors.Required))); } if (messages.All(m => m.IsWarning)) { messages.AddRange((await ValidateAsync(context, record, isNew, cancellationToken).ConfigureAwait(false)) .Select(p => new ImportMessage(ColumnOf(p.Field), p.Code, p.IsWarning))); } if (write && messages.All(m => m.IsWarning)) { try { var (savedCode, savedId) = await SaveAsync(context, record, cancellationToken).ConfigureAwait(false); Remember(state, savedCode, savedId); } catch (ValidationFailedException ex) { messages.AddRange(ex.Errors.Select(TableErrors.Split).Select(e => new ImportMessage(ColumnOf(e.Field), e.Code))); } catch (Core.Common.ConcurrencyException) { messages.Add(new(string.Empty, ImportErrors.WriteFailed)); } } results.Add(new(row.Line, Label(row), messages.Any(m => !m.IsWarning) ? ImportAction.Skip : action, messages)); } return results; } } /// Splits the Field:code errors of . internal static class TableErrors { /// Splits an error. /// The error. /// The field (empty for the record) and the code. public static (string Field, string Code) Split(string error) { var colon = error.LastIndexOf(':'); return colon < 0 ? (string.Empty, error) : (error[..colon], error[(colon + 1)..]); } }