feat: guided import and export for parties, items, prices, opening stock and chart of accounts (#44)

Companies starting on Khaemhat need to bring their master data from another
system or a spreadsheet, and the chart of accounts has no Italian exchange
standard, so SPEC 12.12 asks for a guided wizard and an own layout.

- Administration > Import / export: CSV (separator and encoding guessed),
  XLSX (in-house reader, first sheet) and JSON, automatic column mapping with
  aliases, row-by-row check, error report, import confirmation and log entry.
- Rows go through PartyService, ItemService and PriceListService, so the
  import has exactly the rules, error codes and history of the forms; options
  cover existing and missing codes, VIES and city from postal code.
- Export writes the same columns as the import, plus empty templates.
- Opening stock and the chart of accounts (khaemhat-coa layout, natura, tipo,
  flag) are check-only until M6 and M7 add the ledgers to write into.
- PartyService.SaveAsync takes an explicit VIES switch for the import.
- ADR 0031, wiki Import-Export, CHANGELOG and STATUS updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 11:52:59 +01:00
1 parent 3dbbaba86e
commit caa33a2cee
29 files changed
+4783 -90

No files matched your search

@@ -0,0 +1,231 @@
@page "/amministrazione/import-export"
@attribute [Authorize]
@using Khaemhat.Application.ImportExport
@inject ShellSession Session
@inject ImportService Imports
@inject ToastService Toasts
@inject DialogService Dialogs
@inject IJSRuntime JS
@* The guided import and export (SPEC §11.7, §12.12, mockup 077, ADR 0031): entity and file, mapping of the columns,
check of every row as if typed in its record, import of the rows without errors; on the side, the export with the
same columns and the empty templates. *@
<KhPageTitle Text="@T["ImportExport.Title"]" Icon="upload" />
@if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["ImportExport.NoCompany"]</h1></div>
}
else if (Targets.Count == 0)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["ImportExport.NoTargets"]</p>
</div>
}
else
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["ImportExport.Wizard"]" Icon="upload">
<KhVSteps Items="Steps" Current="_step" Label="@T["ImportExport.Steps.Label"]" />
<div class="kh-import-options">
<KhSelect TValue="string" Label="@T["ImportExport.Target"]" Name="target" Options="TargetChoices" Value="_targetKey" ValueChanged="SetTargetAsync"
Span="12" Disabled="_busy" />
@if (IsRecordTarget)
{
<KhSelect TValue="ExistingCodeAction" Label="@T["ImportExport.Existing"]" Name="existing" Options="ExistingChoices" Value="_options.Existing"
ValueChanged="SetExisting" Span="6" Disabled="_busy" />
<KhSelect TValue="MissingCodeAction" Label="@T["ImportExport.Missing"]" Name="missing" Options="MissingChoices" Value="_options.Missing"
ValueChanged="SetMissing" Span="6" Disabled="_busy" />
}
else if (IsPrices)
{
<KhSelect TValue="ExistingCodeAction" Label="@T["ImportExport.Existing"]" Name="existing" Options="ExistingChoices" Value="_options.Existing"
ValueChanged="SetExisting" Span="12" Disabled="_busy" />
}
@if (IsParties)
{
<KhCheck Label="@T["ImportExport.VerifyVat"]" Name="vies" Value="_options.VerifyVat" ValueChanged="SetVerifyVat" Span="12" Disabled="_busy" />
<KhCheck Label="@T["ImportExport.FillFromPostalCode"]" Name="cap" Value="_options.FillFromPostalCode" ValueChanged="SetFillFromPostalCode" Span="12"
Disabled="_busy" />
}
<div class="f c12">
<label for="kh-import-file">@T["ImportExport.File"]</label>
<InputFile id="kh-import-file" class="in" OnChange="ReadAsync" accept=".csv,.txt,.xlsx,.json" disabled="@_busy" />
<span class="hint">@T["ImportExport.FileHint"]</span>
</div>
</div>
</KhPanel>
<KhPanel Title="@T["ImportExport.Export.Title"]" Icon="download">
<p class="muted kh-import-lead">@T["ImportExport.Export.Lead"]</p>
<div class="kh-seg" role="radiogroup" aria-label="@T["ImportExport.Export.Format"]">
@foreach (var format in Formats)
{
<button type="button" role="radio" class="@(_format == format ? "on" : null)" aria-checked="@(_format == format ? "true" : "false")"
@onclick="() => _format = format">@FormatName(format)</button>
}
</div>
<div class="kh-import-actions">
<button type="button" class="btn" disabled="@_busy" @onclick="TemplateAsync"><KhIcon Name="file" /> @T["ImportExport.Export.Template"]</button>
<button type="button" class="btn" disabled="@(_busy || !CanExport)" title="@ExportHint" @onclick="ExportAsync"><KhIcon Name="download" /> @T["ImportExport.Export.Run"]</button>
</div>
</KhPanel>
</div>
<div class="kh-import-main">
@if (_file is null)
{
<KhPanel Title="@T["ImportExport.Formats.Title"]" Icon="info">
<p class="kh-import-lead">@T["ImportExport.Formats.Lead"]</p>
<ul class="kh-import-list">
<li>@T["ImportExport.Formats.Csv"]</li>
<li>@T["ImportExport.Formats.Xlsx"]</li>
<li>@T["ImportExport.Formats.Json"]</li>
</ul>
@if (!Target.CanApply)
{
<div class="callout info"><KhIcon Name="info" /> <span>@T.Format("ImportExport.Formats.CheckOnly", CheckOnlyMilestone)</span></div>
}
<h3 class="kh-import-h">@T.Format("ImportExport.Formats.Columns", TargetName(Target.Key))</h3>
<div class="kh-import-chips">
@foreach (var field in Target.Fields)
{
<span class="chip @(field.Required ? null : "soft")" title="@FieldName(field.Key)"><span class="mono">@field.Key</span>@RequiredMark(field)</span>
}
</div>
</KhPanel>
}
else if (_step == 1)
{
<KhPanel Title="@T["ImportExport.Mapping.Title"]" Icon="columns" Tight="true">
<Actions>
<button type="button" class="btn" disabled="@_busy" @onclick="ChangeFile"><KhIcon Name="x" /> @T["ImportExport.Mapping.ChangeFile"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="CheckAsync"><KhIcon Name="check" /> @T["ImportExport.Mapping.Check"]</button>
</Actions>
<ChildContent>
<p class="muted kh-pad">@T["ImportExport.Mapping.Lead"]</p>
@if (MissingRequired.Count > 0)
{
<div class="callout warn kh-import-callout"><KhIcon Name="alert" /> <span>@T.Format("ImportExport.Mapping.RequiredMissing", string.Join(", ", MissingRequired))</span></div>
}
@if (_file.Sections is { Count: > 0 } sections)
{
<div class="callout info kh-import-callout"><KhIcon Name="info" /> <span>@T.Format("ImportExport.Mapping.Sections", SectionsText(sections))</span></div>
}
<table class="grid kh-import-map" aria-label="@T["ImportExport.Mapping.Title"]">
<thead>
<tr>
<th>@T["ImportExport.Mapping.Header"]</th>
<th>@T["ImportExport.Mapping.Sample"]</th>
<th>@T["ImportExport.Mapping.Field"]</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < _file.Headers.Count; i++)
{
var column = i;
<tr>
<td><b>@_file.Headers[column]</b></td>
<td class="muted">@Sample(column)</td>
<td>
<select class="in" aria-label="@_file.Headers[column]" @onchange="e => SetMapping(column, e.Value as string)">
<option value="" selected="@(_mapping[column] is null)">@T["ImportExport.Mapping.Ignore"]</option>
@foreach (var field in Target.Fields)
{
<option value="@field.Key" selected="@(_mapping[column] == field.Key)">@FieldName(field.Key)@RequiredMark(field)</option>
}
</select>
</td>
</tr>
}
</tbody>
</table>
</ChildContent>
</KhPanel>
}
else if (_preview is { } preview)
{
<KhPanel Title="@PreviewTitle" Icon="check" Tight="true">
<Actions>
<div class="kh-seg" role="radiogroup" aria-label="@T["ImportExport.Preview.Title"]">
<button type="button" role="radio" class="@(_onlyProblems ? null : "on")" aria-checked="@(_onlyProblems ? "false" : "true")"
@onclick="() => _onlyProblems = false">@T["ImportExport.Preview.All"]</button>
<button type="button" role="radio" class="@(_onlyProblems ? "on" : null)" aria-checked="@(_onlyProblems ? "true" : "false")"
@onclick="() => _onlyProblems = true">@T["ImportExport.Preview.Problems"]</button>
</div>
@if (_report is null)
{
<button type="button" class="btn" disabled="@_busy" @onclick="BackToMapping"><KhIcon Name="columns" /> @T["ImportExport.Preview.Back"]</button>
}
<button type="button" class="btn" disabled="@(_busy || !HasProblems)" @onclick="ReportAsync"><KhIcon Name="download" /> @T["ImportExport.Preview.Report"]</button>
@if (_report is null)
{
<button type="button" class="btn primary" disabled="@(_busy || !preview.CanApply || preview.Importable == 0)" @onclick="ImportAsync">
<KhIcon Name="upload" /> @ImportLabel(preview.Importable)
</button>
}
else
{
<button type="button" class="btn primary" disabled="@_busy" @onclick="ChangeFile"><KhIcon Name="plus" /> @T["ImportExport.Done.Again"]</button>
}
</Actions>
<ChildContent>
@if (_report is { } report)
{
<div class="callout ok kh-import-callout">
<KhIcon Name="check" />
<span><b>@T["ImportExport.Done.Title"]</b> · @T.Format("ImportExport.Done.Lead", TargetName(report.Target), report.Created, report.Updated, report.Skipped, report.Failed)</span>
</div>
}
else if (!preview.CanApply)
{
<div class="callout info kh-import-callout"><KhIcon Name="info" /> <span>@T.Format("ImportExport.Formats.CheckOnly", CheckOnlyMilestone)</span></div>
}
@if (VisibleRows.Count == 0)
{
<p class="muted kh-pad">@T["ImportExport.Preview.NoRows"]</p>
}
else
{
<table class="grid kh-import-preview" aria-label="@T["ImportExport.Preview.Title"]">
<thead>
<tr>
<th class="num">@T["ImportExport.Preview.Line"]</th>
@foreach (var key in PreviewFields)
{
<th>@FieldName(key)</th>
}
<th>@T["ImportExport.Preview.Outcome"]</th>
</tr>
</thead>
<tbody>
@foreach (var row in VisibleRows)
{
var cells = CellsOf(row.Line);
<tr class="@RowClass(row)">
<td class="num muted">@row.Line</td>
@foreach (var key in PreviewFields)
{
<td class="@CellClass(row, key)">@CellOf(row, cells, key)</td>
}
<td class="kh-import-outcome">
<KhBadge Tone="ToneOf(row)">@OutcomeText(row)</KhBadge>
@foreach (var message in row.Messages)
{
<span class="kh-import-msg @(message.IsWarning ? "warn" : "err")">@MessageText(message)</span>
}
</td>
</tr>
}
</tbody>
</table>
}
</ChildContent>
</KhPanel>
}
</div>
</div>
}
@@ -0,0 +1,391 @@
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 string CheckOnlyMilestone => Target is ChartOfAccountsImportTarget ? "M7" : "M6";
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);
}
}
@@ -147,6 +147,17 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Parties.PartyService>();
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// Guided import and export (ADR 0031): the entities in the order of the screen.
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
sp, Khaemhat.Core.Parties.PartyKind.Customer));
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
sp, Khaemhat.Core.Parties.PartyKind.Supplier));
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.ItemsImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.PricesImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.OpeningStockImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget, Khaemhat.Application.ImportExport.ChartOfAccountsImportTarget>();
services.AddSingleton<Khaemhat.Application.ImportExport.ImportService>();
services.AddSingleton<ExchangeRateService>();
services.AddHttpClient<EcbRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(30));
services.AddHttpClient<ViesClient>(c => c.Timeout = TimeSpan.FromSeconds(20));
@@ -0,0 +1,237 @@
{
"ImportExport": {
"Title": "Import / export dati",
"NoCompany": "Scegli un'azienda per importare o esportare i dati.",
"NoTargets": "Il tuo ruolo non permette di importare dati in questa azienda.",
"Wizard": "Importazione guidata",
"Steps": {
"Label": "Passi dell'importazione",
"Origin": "Origine",
"OriginEmpty": "Scegli entità e file",
"OriginDetail": "{0} · {1} righe · {2}",
"Mapping": "Mappatura colonne",
"MappingEmpty": "Dopo la scelta del file",
"MappingDetail": "{0} di {1} colonne abbinate",
"Check": "Validazione",
"CheckEmpty": "Dopo la mappatura",
"CheckDetail": "OK {0} · avvisi {1} · errori {2}",
"Import": "Importazione",
"ImportEmpty": "Dopo la validazione",
"ImportReady": "Righe pronte: {0}",
"ImportCheckOnly": "Solo verifica per ora",
"ImportDone": "Creati {0} · aggiornati {1}"
},
"Target": "Entità",
"Targets": {
"clienti": "Clienti",
"fornitori": "Fornitori",
"articoli": "Articoli",
"listini": "Prezzi di listino e netti cliente",
"giacenze-iniziali": "Giacenze iniziali",
"piano-dei-conti": "Piano dei conti"
},
"Existing": "Se il codice esiste",
"ExistingChoices": {
"Update": "Aggiorna",
"Skip": "Salta la riga"
},
"Missing": "Codice mancante",
"MissingChoices": {
"Generate": "Genera automatico",
"Refuse": "Errore sulla riga"
},
"VerifyVat": "Verifica P.IVA su VIES (UE)",
"FillFromPostalCode": "Completa comune da CAP",
"File": "File da importare",
"FileHint": "CSV, XLSX o JSON; la prima riga contiene le intestazioni.",
"Reading": "Lettura del file...",
"TooLarge": "Il file supera {0} MB.",
"Formats": {
"Title": "Formati e colonne",
"Lead": "Scegli l'entità e il file: le colonne con il nome indicato qui sotto (o un nome simile) si abbinano da sole, le altre si abbinano nel passo successivo.",
"Csv": "CSV: separatore punto e virgola (anche virgola o tabulazione), UTF-8 o Windows-1252, numeri e date all'italiana.",
"Xlsx": "XLSX: il primo foglio della cartella, intestazioni nella prima riga.",
"Json": "JSON: un elenco di oggetti con le colonne come chiavi; per il piano dei conti anche il file khaemhat-coa.json.",
"Columns": "Colonne di {0}",
"RequiredMark": "obbligatoria",
"CheckOnly": "Per ora questa entità si verifica soltanto: la scrittura arriva con {0}. Il controllo serve a preparare il file in anticipo."
},
"Mapping": {
"Title": "Mappatura colonne",
"Lead": "Per ogni colonna del file scegli il campo di destinazione; le colonne senza campo si ignorano.",
"Header": "Colonna del file",
"Sample": "Esempio (riga 2)",
"Field": "Campo",
"Ignore": "Ignora",
"Check": "Verifica le righe",
"ChangeFile": "Cambia file",
"RequiredMissing": "Campi obbligatori non abbinati: {0}.",
"Sections": "Il file contiene anche: {0}. Queste sezioni si importano con la contabilità (M7)."
},
"Preview": {
"Title": "Anteprima e validazione",
"Subtitle": "Anteprima e validazione (prime {0} di {1})",
"SubtitleAll": "Anteprima e validazione ({0} righe)",
"All": "Tutte",
"Problems": "Solo problemi",
"Line": "Riga",
"Key": "Codice",
"Outcome": "Esito",
"Ok": "OK",
"Warnings": "{0} avvisi",
"Warning": "1 avviso",
"Error": "Errore",
"Create": "Nuovo",
"Update": "Aggiorna",
"Skip": "Saltata",
"NoRows": "Nessuna riga da mostrare.",
"Back": "Mappatura",
"Report": "Scarica report errori",
"Import": "Importa {0} righe",
"ImportOne": "Importa 1 riga",
"Confirm": "Righe da importare: {0}. Le righe con errori restano fuori e si trovano nel report.",
"Importing": "Importazione in corso..."
},
"Done": {
"Title": "Importazione completata",
"Lead": "{0}: creati {1}, aggiornati {2}, saltati {3}, con errori {4}.",
"Again": "Nuova importazione",
"Toast": "Righe importate: {0}"
},
"Export": {
"Title": "Esporta e modelli",
"Lead": "L'esportazione usa le stesse colonne dell'import: il file si può correggere e importare di nuovo.",
"Format": "Formato",
"Template": "Scarica modello",
"Run": "Esporta",
"Done": "Record esportati: {0}",
"NotAllowed": "Il tuo utente non può esportare dati.",
"Nothing": "Per questa entità c'è solo il modello: non ci sono ancora dati da esportare."
},
"ReportColumns": {
"Line": "riga",
"Key": "codice",
"Field": "colonna",
"Outcome": "esito",
"Message": "messaggio"
},
"Outcome": {
"Error": "errore",
"Warning": "avviso"
},
"MessageField": "{0}: {1}",
"Fields": {
"codice": "Codice",
"ragione_sociale": "Ragione sociale",
"nome": "Nome",
"cognome": "Cognome",
"tipo_soggetto": "Tipo soggetto",
"partita_iva": "Partita IVA",
"codice_fiscale": "Codice fiscale",
"rea": "REA",
"indirizzo": "Indirizzo",
"civico": "Civico",
"cap": "CAP",
"comune": "Comune",
"provincia": "Provincia",
"nazione": "Nazione",
"telefono": "Telefono",
"email": "Email",
"pec": "PEC",
"sito": "Sito web",
"codice_destinatario": "Codice destinatario",
"categoria": "Categoria",
"agente": "Agente",
"pagamento": "Pagamento",
"listino": "Listino",
"sconto1": "Sconto 1",
"sconto2": "Sconto 2",
"fido": "Fido",
"iban": "IBAN",
"note": "Note",
"descrizione": "Descrizione",
"descrizione_estesa": "Descrizione estesa",
"tipo": "Tipo",
"um": "Unità di misura",
"iva_vendite": "IVA vendite",
"iva_acquisti": "IVA acquisti",
"ean": "Codice a barre",
"nc8": "Nomenclatura combinata",
"marca": "Marca",
"produttore": "Produttore",
"peso_netto": "Peso netto",
"peso_lordo": "Peso lordo",
"a_magazzino": "Gestito a magazzino",
"magazzino": "Deposito",
"scorta_minima": "Scorta minima",
"punto_riordino": "Punto di riordino",
"lotto_riordino": "Lotto di riordino",
"prezzo": "Prezzo",
"costo_standard": "Costo standard",
"conto_ricavo": "Conto ricavo",
"conto_costo": "Conto costo",
"articolo": "Articolo",
"cliente": "Cliente",
"valido_dal": "Valido dal",
"deposito": "Deposito",
"quantita": "Quantità",
"costo_unitario": "Costo unitario",
"livello": "Livello",
"padre": "Conto padre",
"natura": "Natura",
"voce_cee": "Voce CEE",
"riclassifica": "Riclassifica",
"flag": "Attributi"
}
},
"import": {
"file": {
"format": "Il file non è CSV, XLSX o JSON.",
"empty": "Il file non ha intestazioni o righe.",
"unreadable": "Il file non si riesce a leggere: è danneggiato o non è nel formato atteso.",
"too-large": "Il file ha troppe righe: al massimo 50.000 per importazione."
},
"target": {
"unknown": "Entità sconosciuta o non attiva con la licenza.",
"check-only": "Per ora questa entità si verifica soltanto."
},
"value": {
"required": "Valore obbligatorio.",
"number": "Non è un numero.",
"date": "Non è una data.",
"boolean": "Scrivi sì o no.",
"choice": "Valore non previsto: usa {0}.",
"code-unknown": "Il codice {0} non esiste.",
"positive": "Deve essere maggiore di zero."
},
"code": {
"missing": "Manca il codice e le opzioni non lo generano.",
"repeated": "Il codice {0} è già in una riga precedente del file.",
"exists": "Il codice {0} esiste già: riga saltata come richiesto."
},
"party": {
"other-kind": "Il codice {0} appartiene a un'anagrafica di altro tipo."
},
"filled": {
"city": "Comune completato dal CAP: {0}.",
"postal-code": "CAP completato dal comune: {0}."
},
"price": {
"target": "Indica il listino oppure il cliente, non entrambi."
},
"stock": {
"not-stocked": "L'articolo {0} non è merce gestita a magazzino."
},
"write": {
"failed": "Riga non scritta: il dato è cambiato nel frattempo o una regola l'ha rifiutata."
},
"coa": {
"level": "Livello non valido: il codice ha da 1 a 3 parti separate da punto ({0}).",
"parent": "Il conto padre deve essere {0} e deve trovarsi nel file.",
"nature": "La natura deve essere quella del conto padre ({0}).",
"postable": "Un conto con sottoconti non può essere movimentabile.",
"leaf": "Conto senza sottoconti non movimentabile: manca la lettera M negli attributi.",
"flag": "Attributo {0} sconosciuto: usa M, I, P, C, X."
}
}
}
+2 -1
View File
@@ -144,7 +144,8 @@
"Licenses": "Licenze e moduli",
"Jobs": "Attività programmate",
"Log": "Log",
"Status": "Stato del sistema"
"Status": "Stato del sistema",
"ImportExport": "Import / export dati"
}
},
"Tabs": {
+1
View File
@@ -29,6 +29,7 @@ public static class HelpLinks
("/report", "Report"),
("/tabelle", "Tabelle-azienda"),
("/automazioni", "Automazioni"),
("/amministrazione/import-export", "Import-Export"),
("/amministrazione/licenze", "Licenze-e-moduli"),
("/amministrazione/log", "Log"),
("/amministrazione/attivita", "Attivita-programmate"),
+10 -5
View File
@@ -95,11 +95,13 @@ public static class MenuCatalog
("Shell.Menu.CompanyTables.Currencies", "valute"), ("Shell.Menu.CompanyTables.ExchangeRates", "cambi")),
Area("Shell.Menu.Automation", "zap", "/automazioni", ModuleCodes.Automation, null, "M12",
("Shell.Menu.Automation.Rules", "regole"), ("Shell.Menu.Automation.Procedures", "procedure")),
Area("Shell.Menu.Admin", "shield", "/amministrazione", ModuleCodes.Core, null, "M13",
MenuAudience.InstanceAccounts,
("Shell.Menu.Admin.Companies", "aziende"), ("Shell.Menu.Admin.Users", "utenti"), ("Shell.Menu.Admin.Roles", "ruoli"),
("Shell.Menu.Admin.Licenses", "licenze"), ("Shell.Menu.Admin.Jobs", "attivita"), ("Shell.Menu.Admin.Log", "log"),
("Shell.Menu.Admin.Status", "stato")),
WithChild(
Area("Shell.Menu.Admin", "shield", "/amministrazione", ModuleCodes.Core, null, "M13",
MenuAudience.InstanceAccounts,
("Shell.Menu.Admin.Companies", "aziende"), ("Shell.Menu.Admin.Users", "utenti"), ("Shell.Menu.Admin.Roles", "ruoli"),
("Shell.Menu.Admin.Licenses", "licenze"), ("Shell.Menu.Admin.Jobs", "attivita"), ("Shell.Menu.Admin.Log", "log"),
("Shell.Menu.Admin.Status", "stato")),
new MenuItem("Shell.Menu.Admin.ImportExport", "shield", "/amministrazione/import-export", ModuleCodes.Core, null, null, MenuAudience.InstanceAccounts)),
]),
];
@@ -118,6 +120,9 @@ public static class MenuCatalog
public static MenuItem? FindArea(string path) =>
Sections.SelectMany(s => s.Items).Where(i => i.Matches(path)).OrderByDescending(i => i.Href.Length).FirstOrDefault();
// An entry delivered before the rest of its area (the guided import of M4 under the administration of M13).
private static MenuItem WithChild(MenuItem area, MenuItem child) => area with { Children = [.. area.Children, child] };
private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone,
params (string Key, string Slug)[] children) =>
Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children);
+23
View File
@@ -332,3 +332,26 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
/* Stronger than the striped and hovered rows, so every pending cell shows. */
.grid tbody tr td.kh-changed { background: var(--kh-warn-soft); font-weight: 600; }
.grid td.kh-derived { color: var(--kh-text-2); font-style: italic; }
/* Guided import and export (mockup 077): the wizard and the export on the left, mapping or preview on the right. */
.kh-import { display: grid; grid-template-columns: 330px minmax(0, 1fr); gap: var(--kh-gap); align-items: start; }
.kh-import-side { display: flex; flex-direction: column; gap: var(--kh-gap); }
.kh-import-main { min-width: 0; }
.kh-import-options { display: grid; grid-template-columns: repeat(12, 1fr); gap: 10px 12px; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--kh-border); }
.kh-import-options .f { display: flex; flex-direction: column; gap: 4px; }
.kh-import-options input[type=file].in { padding: 4px; height: auto; }
.kh-import-lead { margin: 0 0 10px; }
.kh-import-list { margin: 0 0 12px; padding-left: 18px; display: grid; gap: 4px; }
.kh-import-h { font-size: 13px; margin: 14px 0 8px; }
.kh-import-chips { display: flex; flex-wrap: wrap; gap: 6px; }
.kh-import-chips .chip.soft { background: var(--kh-surface-3); color: var(--kh-text-2); }
.kh-import-actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
.kh-import-callout { margin: 0 12px 10px; }
.kh-import-map td select.in { min-width: 220px; }
.kh-import-preview td.kh-import-outcome { white-space: normal; min-width: 220px; }
.kh-import-msg { display: block; font-size: 11.5px; margin-top: 3px; }
.kh-import-msg.err { color: var(--kh-err); }
.kh-import-msg.warn { color: var(--kh-warn-text, var(--kh-text-2)); }
.grid tbody tr td.kh-import-cell-err { background: var(--kh-err-soft); }
.grid tbody tr td.kh-import-cell-warn { background: var(--kh-warn-soft); }
@media (max-width: 1100px) { .kh-import { grid-template-columns: 1fr; } }
@@ -187,6 +187,7 @@ a.kh-tilelink:hover { border-color: var(--kh-accent); }
.kh-steps { list-style: none; margin: 0; }
.steps.kh-steps { padding: 4px 0; }
.vsteps.kh-steps { padding: 6px 0; }
.vsteps.kh-steps .vs { display: block; }
button.tab { border: 0; border-bottom: 2px solid transparent; background: none; font: inherit; cursor: pointer; }
button.tab.active { border-bottom-color: var(--kh-accent); }