Files
Khaemhat/src/Khaemhat.Web/Components/Pages/Admin/ImportExportPage.razor.cs
T
Alby96andClaude Opus 5.5 ced689b297 feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60)
Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the
movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP)
become draft purchase invoices with supplier, items and tax codes matched, the file attached
and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase
invoices show price differences against the order and the self-invoice still to issue,
with a pending list on the self-invoice screen. The opening stock import now writes an
opening movement. The demo company gets purchases, an opening stock, a pending
self-invoice and a stock take being counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:01:32 +01:00

392 lines
15 KiB
C#

using Khaemhat.Application.ImportExport;
using Khaemhat.Application.Security;
using Khaemhat.Web.Shell;
using Khaemhat.Web.Ui;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.JSInterop;
namespace Khaemhat.Web.Components.Pages.Admin;
/// <summary>The state and the actions of the guided import and export (mockup 077).</summary>
public partial class ImportExportPage
{
/// <summary>The largest file accepted, in megabytes.</summary>
public const int MaxMegabytes = 25;
private const int MaxPreviewRows = 500;
private const int MaxPreviewFields = 6;
private static readonly TransferFormat[] Formats = [TransferFormat.Csv, TransferFormat.Xlsx, TransferFormat.Json];
private ImportOptions _options = new();
private string _targetKey = "clienti";
private TransferFormat _format = TransferFormat.Csv;
private ImportFile? _file;
private long _fileBytes;
private string?[] _mapping = [];
private Dictionary<int, ImportRow> _rows = [];
private ImportPreview? _preview;
private ImportReport? _report;
private bool _onlyProblems;
private bool _busy;
private int _step;
private IReadOnlyList<IImportTarget> Targets =>
[.. Imports.Targets.Where(t => Session.Permissions.Allows(t.Permission) || Session.Permissions.Allows(t.ExportPermission))];
private IImportTarget Target => Targets.FirstOrDefault(t => t.Key == _targetKey) ?? Targets[0];
private bool IsParties => Target is PartiesImportTarget;
private bool IsRecordTarget => Target is PartiesImportTarget or ItemsImportTarget;
private bool IsPrices => Target is PricesImportTarget;
private bool CanExport => Target.CanExport && Session.Permissions.Flags.CanExport && Session.Permissions.Allows(Target.ExportPermission);
private string? ExportHint => !Target.CanExport ? T["ImportExport.Export.Nothing"] : !Session.Permissions.Flags.CanExport ? T["ImportExport.Export.NotAllowed"] : null;
private static string CheckOnlyMilestone => "M7";
private IReadOnlyList<KhOption<string>> TargetChoices => [.. Targets.Select(t => new KhOption<string>(t.Key, TargetName(t.Key)))];
private IReadOnlyList<KhOption<ExistingCodeAction>> ExistingChoices =>
[.. Enum.GetValues<ExistingCodeAction>().Select(v => new KhOption<ExistingCodeAction>(v, T["ImportExport.ExistingChoices." + v]))];
private IReadOnlyList<KhOption<MissingCodeAction>> MissingChoices =>
[.. Enum.GetValues<MissingCodeAction>().Select(v => new KhOption<MissingCodeAction>(v, T["ImportExport.MissingChoices." + v]))];
private IReadOnlyList<KhStep> Steps
{
get
{
var preview = _preview;
return
[
new(T["ImportExport.Steps.Origin"], _file is { } file
? T.Format("ImportExport.Steps.OriginDetail", file.Name, file.Count.ToString("N0", T.Culture), Size(_fileBytes))
: T["ImportExport.Steps.OriginEmpty"]),
new(T["ImportExport.Steps.Mapping"], _file is { } mapped
? T.Format("ImportExport.Steps.MappingDetail", _mapping.Count(m => m is not null), mapped.Headers.Count)
: T["ImportExport.Steps.MappingEmpty"]),
new(T["ImportExport.Steps.Check"], preview is null
? T["ImportExport.Steps.CheckEmpty"]
: T.Format("ImportExport.Steps.CheckDetail", Number(preview.Rows.Count - preview.Errors - preview.Warnings), Number(preview.Warnings), Number(preview.Errors))),
new(T["ImportExport.Steps.Import"], _report is { } report
? T.Format("ImportExport.Steps.ImportDone", Number(report.Created), Number(report.Updated))
: preview is null ? T["ImportExport.Steps.ImportEmpty"]
: preview.CanApply ? T.Format("ImportExport.Steps.ImportReady", Number(preview.Importable))
: T["ImportExport.Steps.ImportCheckOnly"]),
];
}
}
private IReadOnlyList<string> MissingRequired =>
[.. Target.Fields.Where(f => f.Required && !_mapping.Contains(f.Key)).Select(f => FieldName(f.Key))];
// The first mapped columns, then the columns that have a remark somewhere, so that every remark is next to its cell.
private IReadOnlyList<string> PreviewFields
{
get
{
var mapped = Target.Fields.Select(f => f.Key).Where(k => _mapping.Contains(k)).ToList();
var remarked = AllRows.SelectMany(r => r.Messages).Select(m => m.Field).ToHashSet(StringComparer.Ordinal);
var shown = mapped.Take(MaxPreviewFields).ToHashSet(StringComparer.Ordinal);
shown.UnionWith(mapped.Where(remarked.Contains).Take(MaxPreviewFields));
return [.. mapped.Where(shown.Contains)];
}
}
private bool HasProblems => (_report?.Rows ?? _preview?.Rows ?? []).Any(r => r.Messages.Count > 0);
private IReadOnlyList<ImportRowResult> AllRows => _report?.Rows ?? _preview?.Rows ?? [];
private IReadOnlyList<ImportRowResult> VisibleRows =>
[.. AllRows.Where(r => !_onlyProblems || r.Messages.Count > 0).Take(MaxPreviewRows)];
private string PreviewTitle
{
get
{
var total = AllRows.Count(r => !_onlyProblems || r.Messages.Count > 0);
return total > MaxPreviewRows
? T.Format("ImportExport.Preview.Subtitle", Number(MaxPreviewRows), Number(total))
: T.Format("ImportExport.Preview.SubtitleAll", Number(total));
}
}
private string TargetName(string key) => T["ImportExport.Targets." + key];
private string FieldName(string key) => T.Contains("ImportExport.Fields." + key) ? T["ImportExport.Fields." + key] : key;
private static string RequiredMark(ImportField field) => field.Required ? " *" : string.Empty;
private static string FormatName(TransferFormat format) => format.ToString().ToUpperInvariant();
private string Number(int value) => value.ToString("N0", T.Culture);
private string Size(long bytes) => bytes >= 1024 * 1024
? (bytes / 1024d / 1024d).ToString("0.0", T.Culture) + " MB"
: Math.Max(1, (bytes + 512) / 1024).ToString(T.Culture) + " KB";
private string ImportLabel(int rows) => rows == 1 ? T["ImportExport.Preview.ImportOne"] : T.Format("ImportExport.Preview.Import", Number(rows));
private string SectionsText(IReadOnlyDictionary<string, int> sections) =>
string.Join(", ", sections.Select(s => s.Key + " (" + Number(s.Value) + ")"));
private string? Sample(int column) => _file is { Count: > 0 } file && column < file.Rows[0].Count ? file.Rows[0][column] : null;
private IReadOnlyDictionary<string, string>? CellsOf(int line) => _rows.TryGetValue(line, out var row) ? row.Values : null;
// The cell of the file, or the value the check proposes for it (the city from the postal code).
private static string? CellOf(ImportRowResult row, IReadOnlyDictionary<string, string>? cells, string key) =>
cells?.GetValueOrDefault(key) ?? row.Messages.FirstOrDefault(m => m.Field == key && m.IsWarning && m.Value is not null)?.Value;
private static string? RowClass(ImportRowResult row) => row.Outcome switch
{
ImportOutcome.Error => "kh-import-err",
ImportOutcome.Warning => "kh-import-warn",
_ => null,
};
private static string? CellClass(ImportRowResult row, string key) =>
row.Messages.FirstOrDefault(m => m.Field == key) is { } message ? (message.IsWarning ? "kh-import-cell-warn" : "kh-import-cell-err") : null;
private static KhTone ToneOf(ImportRowResult row) => row.Outcome switch
{
ImportOutcome.Error => KhTone.Error,
ImportOutcome.Warning => KhTone.Warning,
_ => row.Action == ImportAction.Skip ? KhTone.Neutral : KhTone.Ok,
};
private string OutcomeText(ImportRowResult row) => row.Outcome switch
{
ImportOutcome.Error => T["ImportExport.Preview.Error"],
ImportOutcome.Warning when row.Messages.Count == 1 => T["ImportExport.Preview.Warning"],
ImportOutcome.Warning => T.Format("ImportExport.Preview.Warnings", row.Messages.Count),
_ => T["ImportExport.Preview." + row.Action],
};
private string MessageText(ImportMessage message)
{
var text = !T.Contains(message.Code) ? message.Code
: message.Value is null ? T[message.Code]
: T.Format(message.Code, message.Value);
return message.Field.Length == 0 ? text : T.Format("ImportExport.MessageField", FieldName(message.Field), text);
}
private void Reset()
{
_file = null;
_fileBytes = 0;
_mapping = [];
_rows = [];
_preview = null;
_report = null;
_onlyProblems = false;
_step = 0;
}
private Task SetTargetAsync(string? key)
{
_targetKey = key ?? Targets[0].Key;
_options = new ImportOptions();
if (_file is { } file)
{
_mapping = [.. ImportService.SuggestMapping(Target, file.Headers)];
_preview = null;
_report = null;
_step = 1;
}
return Task.CompletedTask;
}
private void SetExisting(ExistingCodeAction value) => _options = _options with { Existing = value };
private void SetMissing(MissingCodeAction value) => _options = _options with { Missing = value };
private void SetVerifyVat(bool value) => _options = _options with { VerifyVat = value };
private void SetFillFromPostalCode(bool value) => _options = _options with { FillFromPostalCode = value };
private void SetMapping(int column, string? key)
{
var field = string.IsNullOrEmpty(key) ? null : key;
if (field is not null)
{
// A field goes to one column only: the column that had it loses it.
for (var i = 0; i < _mapping.Length; i++)
{
if (i != column && _mapping[i] == field)
{
_mapping[i] = null;
}
}
}
_mapping[column] = field;
_preview = null;
}
private void ChangeFile() => Reset();
private void BackToMapping()
{
_preview = null;
_report = null;
_step = 1;
}
private async Task ReadAsync(InputFileChangeEventArgs e)
{
Reset();
if (e.File.Size > MaxMegabytes * 1024L * 1024L)
{
Toasts.Show(ToastKind.Error, e.File.Name, T.Format("ImportExport.TooLarge", MaxMegabytes));
return;
}
_busy = true;
try
{
await using var source = e.File.OpenReadStream(MaxMegabytes * 1024L * 1024L);
var file = await ImportFileReader.ReadAsync(e.File.Name, source);
_file = file;
_fileBytes = e.File.Size;
_mapping = [.. ImportService.SuggestMapping(Target, file.Headers)];
_step = 1;
}
catch (ImportFileException ex)
{
Toasts.Show(ToastKind.Error, e.File.Name, T[ex.Code]);
}
catch (IOException ex)
{
Toasts.Show(ToastKind.Error, e.File.Name, ex.Message);
}
finally
{
_busy = false;
}
}
private async Task CheckAsync()
{
if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file)
{
return;
}
_busy = true;
try
{
_rows = ImportService.Rows(file, _mapping).ToDictionary(r => r.Line);
_preview = await Imports.PreviewAsync(actor, company.Code, Target.Key, file, _mapping, _options);
_report = null;
_onlyProblems = _preview.Errors + _preview.Warnings > 0 && _preview.Rows.Count > MaxPreviewRows;
_step = 2;
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]);
}
finally
{
_busy = false;
}
}
private async Task ImportAsync()
{
if (Session.Actor is not { } actor || Session.Company is not { } company || _file is not { } file || _preview is not { } preview)
{
return;
}
if (!await Dialogs.ConfirmAsync(new(ImportLabel(preview.Importable), T.Format("ImportExport.Preview.Confirm", Number(preview.Importable)),
ImportLabel(preview.Importable), T["Common.Cancel"])))
{
return;
}
_busy = true;
try
{
_report = await Imports.ImportAsync(actor, company.Code, Target.Key, file, _mapping, _options);
_onlyProblems = _report.Rows.Any(r => r.Messages.Count > 0);
_step = 3;
Toasts.Show(ToastKind.Success, T.Format("ImportExport.Done.Toast", Number(_report.Created + _report.Updated)),
T.Format("ImportExport.Done.Lead", TargetName(_report.Target), _report.Created, _report.Updated, _report.Skipped, _report.Failed));
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.NoTargets"]);
}
catch (ImportFileException ex)
{
Toasts.Show(ToastKind.Error, TargetName(Target.Key), T[ex.Code]);
}
finally
{
_busy = false;
}
}
private async Task ReportAsync()
{
using var buffer = new MemoryStream();
IReadOnlyList<string> labels =
[
T["ImportExport.ReportColumns.Line"], T["ImportExport.ReportColumns.Key"], T["ImportExport.ReportColumns.Field"], T["ImportExport.ReportColumns.Outcome"],
T["ImportExport.ReportColumns.Message"],
];
await ImportService.WriteErrorReportAsync(
AllRows,
(_, message) => (T[message.IsWarning ? "ImportExport.Outcome.Warning" : "ImportExport.Outcome.Error"], MessageText(message)),
labels,
buffer);
var name = "report-" + Path.GetFileNameWithoutExtension(_file?.Name ?? Target.Key) + ".csv";
await DownloadAsync(buffer, name, ImportService.MediaType(TransferFormat.Csv));
}
private async Task TemplateAsync()
{
using var buffer = new MemoryStream();
await ImportService.WriteTemplateAsync(Target, _format, buffer);
await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, null), ImportService.MediaType(_format));
}
private async Task ExportAsync()
{
if (Session.Actor is not { } actor || Session.Company is not { } company)
{
return;
}
_busy = true;
try
{
using var buffer = new MemoryStream();
var count = await Imports.ExportAsync(actor, company.Code, Target.Key, _format, buffer);
await DownloadAsync(buffer, ImportService.FileName(Target.Key, _format, DateOnly.FromDateTime(DateTime.Now)), ImportService.MediaType(_format));
Toasts.Show(ToastKind.Success, TargetName(Target.Key), T.Format("ImportExport.Export.Done", Number(count)));
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"], T["ImportExport.Export.NotAllowed"]);
}
finally
{
_busy = false;
}
}
private async Task DownloadAsync(MemoryStream buffer, string name, string mediaType)
{
buffer.Position = 0;
using var stream = new DotNetStreamReference(buffer, leaveOpen: true);
await JS.InvokeVoidAsync("khaemhat.download", name, mediaType, stream);
}
}