[Feature] Implementata schedulazione completa per file CSV/Excel
- Aggiunta validazione percorsi file prima del salvataggio profili - Implementati metodi di lettura file CSV e Excel per schedulazioni - Supporto doppia modalità: caricamento browser (preview) e percorso manuale (schedulazione) - Gestione completa deletion sync anche per file CSV/Excel - Rilevamento automatico separatori CSV (virgola, punto e virgola, tab, pipe) - Supporto formati Excel legacy (.xls) e moderni (.xlsx) - Abilitati profili file nella UI di schedulazione - Logging dettagliato per troubleshooting - Documentazione completa in CSV_SCHEDULING_IMPLEMENTATION.md - Aggiornati README.md e copilot-instructions.md con nuove feature - Rimosso testo 'TEST' dalla pagina di login
This commit was merged in pull request #5.
This commit is contained in:
@@ -36,6 +36,8 @@ public partial class DataCoupler : ComponentBase
|
||||
|
||||
// File handling
|
||||
private string selectedFileName = "";
|
||||
private string manualFilePath = ""; // Percorso inserito manualmente dall'utente
|
||||
private string uploadedFilePath = ""; // Percorso completo del file validato
|
||||
private bool isProcessingFile = false;
|
||||
private string fileErrorMessage = "";
|
||||
private Dictionary<string, IEnumerable<string>> fileSheets = new(); // SheetName -> Columns
|
||||
@@ -250,8 +252,10 @@ public partial class DataCoupler : ComponentBase
|
||||
// Per i file, non possiamo ricreare il file caricato, ma possiamo impostare le informazioni
|
||||
if (!string.IsNullOrEmpty(profile.SourceFilePath))
|
||||
{
|
||||
uploadedFilePath = profile.SourceFilePath;
|
||||
selectedFileName = Path.GetFileName(profile.SourceFilePath);
|
||||
Logger.LogInformation("Informazioni file impostate: {FileName}", selectedFileName);
|
||||
Logger.LogInformation("Informazioni file impostate - Nome: {FileName}, Percorso: {FilePath}",
|
||||
selectedFileName, uploadedFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,6 +405,37 @@ public partial class DataCoupler : ComponentBase
|
||||
var profileService = new DataCouplerProfileService(null!); // Usa il service di conversione
|
||||
var profile = profileService.FromDto(profileDto, "System"); // TODO: Usa utente corrente
|
||||
|
||||
// Validazione specifica per file CSV
|
||||
if (profile.SourceType == "file" && !string.IsNullOrEmpty(profile.SourceFilePath))
|
||||
{
|
||||
Logger.LogInformation("Validazione file CSV: {FilePath}", profile.SourceFilePath);
|
||||
|
||||
// Verifica che il file esista
|
||||
if (!System.IO.File.Exists(profile.SourceFilePath))
|
||||
{
|
||||
await JSRuntime.InvokeVoidAsync("alert",
|
||||
$"Errore: Il file '{profile.SourceFilePath}' non esiste o non è accessibile. " +
|
||||
"Verifica il percorso del file prima di salvare il profilo.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Verifica che il file sia leggibile
|
||||
try
|
||||
{
|
||||
using var fs = new System.IO.FileStream(profile.SourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
fs.Close();
|
||||
Logger.LogInformation("File CSV validato con successo: {FilePath}", profile.SourceFilePath);
|
||||
}
|
||||
catch (Exception fileEx)
|
||||
{
|
||||
Logger.LogError(fileEx, "Errore nella lettura del file CSV: {FilePath}", profile.SourceFilePath);
|
||||
await JSRuntime.InvokeVoidAsync("alert",
|
||||
$"Errore: Il file '{profile.SourceFilePath}' non può essere letto. " +
|
||||
$"Dettagli: {fileEx.Message}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Controlla se esiste già un profilo con lo stesso nome (inclusi quelli inattivi)
|
||||
Logger.LogInformation("Controllo esistenza profilo con nome: {ProfileName}", profileDto.Name);
|
||||
var existingProfile = await ProfileService.GetProfileByNameIncludingInactiveAsync(profileDto.Name);
|
||||
@@ -685,6 +720,8 @@ public partial class DataCoupler : ComponentBase
|
||||
|
||||
// Reset file state
|
||||
selectedFileName = "";
|
||||
manualFilePath = "";
|
||||
uploadedFilePath = "";
|
||||
isProcessingFile = false;
|
||||
fileErrorMessage = "";
|
||||
fileSheets.Clear();
|
||||
@@ -698,6 +735,213 @@ public partial class DataCoupler : ComponentBase
|
||||
ClearAllMappings();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valida e carica un file dal percorso specificato manualmente
|
||||
/// </summary>
|
||||
private async Task ValidateAndLoadFileFromPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
isProcessingFile = true;
|
||||
fileErrorMessage = "";
|
||||
fileSheets.Clear();
|
||||
fileData.Clear();
|
||||
selectedSheet = "";
|
||||
uploadedFilePath = "";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manualFilePath))
|
||||
{
|
||||
fileErrorMessage = "Inserire il percorso del file";
|
||||
return;
|
||||
}
|
||||
|
||||
// Valida che il file esista
|
||||
if (!System.IO.File.Exists(manualFilePath))
|
||||
{
|
||||
fileErrorMessage = $"Il file '{manualFilePath}' non esiste o non è accessibile";
|
||||
Logger.LogWarning("File non trovato: {FilePath}", manualFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
// Valida estensione
|
||||
var extension = Path.GetExtension(manualFilePath).ToLowerInvariant();
|
||||
if (extension != ".xlsx" && extension != ".xls" && extension != ".csv")
|
||||
{
|
||||
fileErrorMessage = "Formato file non supportato. Utilizzare Excel (.xlsx, .xls) o CSV (.csv)";
|
||||
return;
|
||||
}
|
||||
|
||||
// Verifica che il file sia leggibile
|
||||
try
|
||||
{
|
||||
using var testStream = new System.IO.FileStream(manualFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
testStream.Close();
|
||||
}
|
||||
catch (Exception readEx)
|
||||
{
|
||||
fileErrorMessage = $"Il file non può essere letto: {readEx.Message}";
|
||||
Logger.LogError(readEx, "Errore nella lettura del file: {FilePath}", manualFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("Validazione file completata: {FilePath}", manualFilePath);
|
||||
|
||||
// Carica il file dal percorso per preview
|
||||
selectedFileName = Path.GetFileName(manualFilePath);
|
||||
|
||||
if (extension == ".csv")
|
||||
{
|
||||
await ProcessCsvFileFromPath(manualFilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
await ProcessExcelFileFromPath(manualFilePath);
|
||||
}
|
||||
|
||||
// Se tutto è andato bene, salva il percorso validato
|
||||
uploadedFilePath = manualFilePath;
|
||||
Logger.LogInformation("File caricato con successo dal percorso: {FilePath}", uploadedFilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Errore nella validazione/caricamento del file dal percorso: {FilePath}", manualFilePath);
|
||||
fileErrorMessage = $"Errore: {ex.Message}";
|
||||
uploadedFilePath = "";
|
||||
}
|
||||
finally
|
||||
{
|
||||
isProcessingFile = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processa un file CSV dal percorso specificato
|
||||
/// </summary>
|
||||
private async Task ProcessCsvFileFromPath(string filePath)
|
||||
{
|
||||
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(stream);
|
||||
|
||||
var firstLine = await reader.ReadLineAsync();
|
||||
if (string.IsNullOrEmpty(firstLine))
|
||||
{
|
||||
fileErrorMessage = "Il file CSV è vuoto";
|
||||
return;
|
||||
}
|
||||
|
||||
var separator = DetectCsvSeparator(firstLine);
|
||||
var headers = ParseCsvLine(firstLine, separator);
|
||||
|
||||
var sheetName = Path.GetFileNameWithoutExtension(filePath);
|
||||
fileSheets[sheetName] = headers;
|
||||
|
||||
var dataRows = new List<Dictionary<string, object>>();
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||
|
||||
var values = ParseCsvLine(line, separator);
|
||||
var row = new Dictionary<string, object>();
|
||||
for (int i = 0; i < headers.Count; i++)
|
||||
{
|
||||
var value = i < values.Count ? values[i] : "";
|
||||
row[headers[i]] = string.IsNullOrEmpty(value) ? "" : value;
|
||||
}
|
||||
dataRows.Add(row);
|
||||
}
|
||||
|
||||
fileData[sheetName] = dataRows;
|
||||
selectedSheet = sheetName;
|
||||
|
||||
Logger.LogInformation("File CSV processato: {FilePath}, Headers: {HeaderCount}, Rows: {RowCount}",
|
||||
filePath, headers.Count, dataRows.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processa un file Excel dal percorso specificato
|
||||
/// </summary>
|
||||
private async Task ProcessExcelFileFromPath(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||
|
||||
using var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||
var extension = Path.GetExtension(filePath).ToLowerInvariant();
|
||||
|
||||
IExcelDataReader reader;
|
||||
if (extension == ".xlsx")
|
||||
{
|
||||
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
|
||||
}
|
||||
else if (extension == ".xls")
|
||||
{
|
||||
reader = ExcelReaderFactory.CreateBinaryReader(stream);
|
||||
}
|
||||
else
|
||||
{
|
||||
fileErrorMessage = "Formato Excel non supportato";
|
||||
return;
|
||||
}
|
||||
|
||||
using (reader)
|
||||
{
|
||||
var configuration = new ExcelDataSetConfiguration()
|
||||
{
|
||||
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
|
||||
{
|
||||
UseHeaderRow = true
|
||||
}
|
||||
};
|
||||
|
||||
var dataSet = reader.AsDataSet(configuration);
|
||||
|
||||
foreach (DataTable table in dataSet.Tables)
|
||||
{
|
||||
var sheetName = table.TableName;
|
||||
var headers = new List<string>();
|
||||
var dataRows = new List<Dictionary<string, object>>();
|
||||
|
||||
foreach (DataColumn column in table.Columns)
|
||||
{
|
||||
headers.Add(column.ColumnName);
|
||||
}
|
||||
|
||||
foreach (DataRow dataRow in table.Rows)
|
||||
{
|
||||
var row = new Dictionary<string, object>();
|
||||
foreach (var header in headers)
|
||||
{
|
||||
var value = dataRow[header];
|
||||
row[header] = value == DBNull.Value ? "" : value?.ToString() ?? "";
|
||||
}
|
||||
dataRows.Add(row);
|
||||
}
|
||||
|
||||
fileSheets[sheetName] = headers;
|
||||
fileData[sheetName] = dataRows;
|
||||
}
|
||||
|
||||
if (fileSheets.Any())
|
||||
{
|
||||
selectedSheet = fileSheets.First().Key;
|
||||
}
|
||||
|
||||
Logger.LogInformation("File Excel processato: {FilePath}, Sheets: {SheetCount}",
|
||||
filePath, dataSet.Tables.Count);
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Errore nel processing del file Excel: {FilePath}", filePath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnFileSelected(InputFileChangeEventArgs e)
|
||||
{
|
||||
try
|
||||
@@ -719,7 +963,9 @@ public partial class DataCoupler : ComponentBase
|
||||
return;
|
||||
}
|
||||
|
||||
// Process file based on type
|
||||
Logger.LogInformation("File caricato per preview: {FileName}", file.Name);
|
||||
|
||||
// Process file based on type (solo per preview, non salva sul server)
|
||||
if (extension == ".csv")
|
||||
{
|
||||
await ProcessCsvFile(file);
|
||||
|
||||
Reference in New Issue
Block a user