| | 1 | | using Microsoft.Extensions.Logging; |
| | 2 | | using MRA.DTO; |
| | 3 | | using MRA.DTO.Models; |
| | 4 | | using MRA.Extensions; |
| | 5 | | using MRA.Infrastructure.Enums; |
| | 6 | | using MRA.Infrastructure.Excel.Attributes; |
| | 7 | | using MRA.Infrastructure.Settings; |
| | 8 | | using MRA.Services.Excel; |
| | 9 | | using MRA.Services.Excel.Interfaces; |
| | 10 | | using MRA.Services.Models.Drawings; |
| | 11 | | using MRA.Services.UserInput; |
| | 12 | | using OfficeOpenXml; |
| | 13 | | using System.ComponentModel; |
| | 14 | | using System.Reflection; |
| | 15 | |
|
| | 16 | | namespace MRA.Services.Backup.Import; |
| | 17 | |
|
| | 18 | | public class ImportService : IImportService |
| | 19 | | { |
| | 20 | | private readonly IExcelService excelService; |
| | 21 | | private readonly IDrawingService drawingService; |
| | 22 | | private readonly IUserInputService inputService; |
| | 23 | | private readonly AppSettings appSettings; |
| | 24 | | private readonly ILogger<ImportService> logger; |
| | 25 | |
|
| 1 | 26 | | public ImportService( |
| 1 | 27 | | IExcelService excelService, |
| 1 | 28 | | IDrawingService drawingService, |
| 1 | 29 | | IUserInputService inputService, |
| 1 | 30 | | AppSettings appSettings, |
| 1 | 31 | | ILogger<ImportService> logger) |
| | 32 | | { |
| 1 | 33 | | this.excelService = excelService; |
| 1 | 34 | | this.drawingService = drawingService; |
| 1 | 35 | | this.inputService = inputService; |
| 1 | 36 | | this.appSettings = appSettings; |
| 1 | 37 | | this.logger = logger; |
| 1 | 38 | | } |
| | 39 | |
|
| | 40 | | public async Task ImportDrawings() |
| | 41 | | { |
| 0 | 42 | | logger.LogInformation("Iniciando Aplicación de Importación"); |
| | 43 | |
|
| 0 | 44 | | logger.LogInformation("Recuperando documentos"); |
| 0 | 45 | | var listDrawings = await drawingService.GetAllDrawingsAsync(onlyIfVisible: false); |
| | 46 | |
|
| 0 | 47 | | var filePath = inputService.ReadStringValue("Ruta del Fichero a Procesar"); |
| 0 | 48 | | logger.LogInformation("Recuperando documentos desde Excel '{FilePath}'", filePath); |
| | 49 | |
|
| 0 | 50 | | var fileInfo = new FileInfo(filePath); |
| 0 | 51 | | var listDrawingsProcessed = new List<DrawingModel>(); |
| 0 | 52 | | var listDrawingsSaved = new List<DrawingModel>(); |
| 0 | 53 | | var listDrawingsError = new Dictionary<int, DrawingModel>(); |
| | 54 | |
|
| 0 | 55 | | logger.LogInformation("Leyendo comandos automáticos"); |
| 0 | 56 | | bool updateEverythingFromExcel = appSettings.Commands.UpdateEverythingFromExcel; |
| 0 | 57 | | if (updateEverythingFromExcel) |
| | 58 | | { |
| 0 | 59 | | logger.LogWarning("Se sobreescribirán todos los cambios en Firestore con los datos del Excel"); |
| | 60 | | } |
| | 61 | | else |
| | 62 | | { |
| 0 | 63 | | logger.LogInformation("Se preguntará al usuario en caso de cambios"); |
| | 64 | | } |
| | 65 | |
|
| 0 | 66 | | using (var package = new ExcelPackage(fileInfo)) |
| | 67 | | { |
| 0 | 68 | | logger.LogInformation("Leyendo hoja principal '{Sheet}'", ExcelService.EXCEL_DRAWING_SHEET_NAME); |
| 0 | 69 | | var workSheet = package.Workbook.Worksheets[ExcelService.EXCEL_DRAWING_SHEET_NAME]; |
| 0 | 70 | | if (workSheet == null) |
| | 71 | | { |
| 0 | 72 | | throw new Exception($"Worksheet '{ExcelService.EXCEL_DRAWING_SHEET_NAME}' not found in the file."); |
| | 73 | | } |
| | 74 | |
|
| 0 | 75 | | logger.LogInformation("Obteniendo propiedades del DTO de Drawing"); |
| 0 | 76 | | var drawingProperties = excelService.GetPropertiesAttributes<DrawingModel>(); |
| | 77 | |
|
| 0 | 78 | | logger.LogInformation("Obteniendo mapeo entre nombres y números de columnas en el Excel"); |
| 0 | 79 | | Dictionary<string, int> nameToColumnMap = excelService.GetColumnMapDrawing(workSheet); |
| | 80 | |
|
| 0 | 81 | | int row = 2; |
| 0 | 82 | | while (workSheet.Cells[row, 1].Value != null) |
| | 83 | | { |
| 0 | 84 | | bool error = false; |
| 0 | 85 | | logger.LogInformation("Leyendo fila {Row}", row); |
| 0 | 86 | | DrawingModel drawingExcel = ReadDrawingFromRow(workSheet, drawingProperties, nameToColumnMap, row); |
| | 87 | |
|
| 0 | 88 | | logger.LogInformation("Dibujo '{Id}' leído desde Excel", drawingExcel.Id); |
| 0 | 89 | | drawingExcel.Date = drawingExcel.DateObject.FormattedDate(); |
| | 90 | |
|
| 0 | 91 | | DrawingModel? drawingDatabase = listDrawings.FirstOrDefault(x => x.Id == drawingExcel.Id); |
| | 92 | |
|
| 0 | 93 | | if (drawingDatabase != null) |
| | 94 | | { |
| | 95 | | try |
| | 96 | | { |
| 0 | 97 | | bool differentValues = false; |
| 0 | 98 | | logger.LogInformation("Existe un dibujo '{Id}'. Procediendo a EDITAR", drawingDatabase.Id); |
| | 99 | |
|
| 0 | 100 | | foreach (var prop in drawingProperties.Where(x => x.Property.CanWrite)) |
| | 101 | | { |
| 0 | 102 | | if (!prop.Attribute.IgnoreOnImport && !prop.SameValues(drawingExcel, drawingDatabase)) |
| | 103 | | { |
| | 104 | | bool updateValue = false; |
| 0 | 105 | | logger.LogInformation("-------------------------"); |
| 0 | 106 | | logger.LogWarning("'{Id}' tiene diferentes valores para '{Property}'.", drawingExcel.Id, |
| | 107 | |
|
| 0 | 108 | | logger.LogError("En BBDD: {Value}", prop.GetValueToPrint(drawingDatabase)); |
| 0 | 109 | | logger.LogWarning("En EXCEL: {Value}", prop.GetValueToPrint(drawingExcel)); |
| | 110 | |
|
| 0 | 111 | | updateValue = updateEverythingFromExcel || inputService.ReadBoolValue($"Actualizar valor |
| | 112 | |
|
| 0 | 113 | | if (updateValue) |
| | 114 | | { |
| 0 | 115 | | differentValues = true; |
| 0 | 116 | | logger.LogInformation("Actualizando valor con EXCEL: {Value}", prop.GetValueToPrint( |
| 0 | 117 | | prop.Property.SetValue(drawingDatabase, prop.GetValue(drawingExcel)); |
| | 118 | | } |
| | 119 | | else |
| | 120 | | { |
| 0 | 121 | | logger.LogInformation("Permanece el valor de FIRESTORE: {Value}", prop.GetValueToPri |
| | 122 | | } |
| | 123 | | } |
| | 124 | | } |
| | 125 | |
|
| 0 | 126 | | if (differentValues) |
| | 127 | | { |
| 0 | 128 | | logger.LogInformation("Actualizando '{Id}' en BBDD", drawingDatabase.Id); |
| 0 | 129 | | var updatedDrawingSaved = await drawingService.SaveDrawingAsync(drawingDatabase); |
| 0 | 130 | | logger.LogInformation("'{Id}' guardado con éxito", updatedDrawingSaved.Id); |
| | 131 | |
|
| 0 | 132 | | if (!listDrawingsSaved.Any(x => x.Id == updatedDrawingSaved.Id)) |
| | 133 | | { |
| 0 | 134 | | listDrawingsSaved.Add(updatedDrawingSaved); |
| | 135 | | } |
| 0 | 136 | | } |
| | 137 | | else |
| | 138 | | { |
| 0 | 139 | | logger.LogInformation("No se han detectado cambios en '{Id}' respecto al Excel. Se ignora", |
| | 140 | | } |
| 0 | 141 | | } |
| 0 | 142 | | catch (Exception ex) |
| | 143 | | { |
| 0 | 144 | | logger.LogError(ex, "No se pudo actualizar el dibujo '{Id}'.", drawingExcel.Id); |
| 0 | 145 | | error = true; |
| 0 | 146 | | } |
| | 147 | | } |
| | 148 | | else |
| | 149 | | { |
| | 150 | | try |
| | 151 | | { |
| 0 | 152 | | logger.LogWarning("No existe ningún dibujo con ID '{Id}'", drawingExcel.Id); |
| 0 | 153 | | var newDrawingSaved = await drawingService.SaveDrawingAsync(drawingExcel); |
| 0 | 154 | | logger.LogInformation("Dibujo '{Id}' creado con éxito", newDrawingSaved.Id); |
| | 155 | |
|
| 0 | 156 | | if (!listDrawingsSaved.Any(x => x.Id == newDrawingSaved.Id)) |
| | 157 | | { |
| 0 | 158 | | listDrawingsSaved.Add(newDrawingSaved); |
| | 159 | | } |
| 0 | 160 | | } |
| 0 | 161 | | catch (Exception ex) |
| | 162 | | { |
| 0 | 163 | | logger.LogError(ex, "No se pudo crear el dibujo '{Id}'.", drawingExcel.Id); |
| 0 | 164 | | error = true; |
| 0 | 165 | | } |
| | 166 | | } |
| | 167 | |
|
| 0 | 168 | | if (!error && !listDrawingsProcessed.Any(x => x.Id == drawingExcel.Id)) |
| | 169 | | { |
| 0 | 170 | | listDrawingsProcessed.Add(drawingExcel); |
| | 171 | | } |
| | 172 | |
|
| 0 | 173 | | if (error) |
| | 174 | | { |
| 0 | 175 | | listDrawingsError.Add(row, drawingExcel); |
| | 176 | | } |
| | 177 | |
|
| 0 | 178 | | if (!updateEverythingFromExcel) |
| | 179 | | { |
| 0 | 180 | | logger.LogInformation("Pulsa cualquier tecla para continuar con la siguiente línea. Actual: {Row}.", |
| 0 | 181 | | inputService.ReadKey(); |
| | 182 | | } |
| | 183 | |
|
| 0 | 184 | | row++; |
| 0 | 185 | | } |
| 0 | 186 | | } |
| | 187 | |
|
| 0 | 188 | | logger.LogInformation("Dibujos En Firestore: {Count}.", listDrawings.Count()); |
| 0 | 189 | | logger.LogInformation("Dibujos Procesados: {Count}.", listDrawingsProcessed.Count); |
| 0 | 190 | | logger.LogInformation("Guardados: {Count}.", listDrawingsSaved.Count); |
| 0 | 191 | | logger.LogError("Errores: {Count}.", listDrawingsError.Count); |
| 0 | 192 | | if (listDrawingsError.Any()) |
| | 193 | | { |
| 0 | 194 | | foreach (var error in listDrawingsError) |
| | 195 | | { |
| 0 | 196 | | logger.LogError("Fila {Key}, '{Id}'", error.Key, error.Value.Id); |
| | 197 | | } |
| | 198 | | } |
| 0 | 199 | | } |
| | 200 | |
|
| | 201 | | private static DrawingModel ReadDrawingFromRow(ExcelWorksheet workSheet, List<ExcelColumnInfo> drawingProperties, Di |
| | 202 | | { |
| 0 | 203 | | var drawing = new DrawingModel(); |
| | 204 | |
|
| 0 | 205 | | foreach (var propInfo in drawingProperties.Where(x => x.Property.CanWrite)) |
| | 206 | | { |
| 0 | 207 | | if (!nameToColumnMap.TryGetValue(propInfo.Attribute.Name, out int col)) |
| | 208 | | { |
| | 209 | | continue; |
| | 210 | | } |
| | 211 | |
|
| | 212 | | //throw new NotImplementedException("TODO: fix reading value null in boolean and numbers."); |
| | 213 | |
|
| 0 | 214 | | var cellValue = workSheet.GetValue(row, col); |
| 0 | 215 | | SetPropertyValue(drawing, propInfo.Property, cellValue); |
| | 216 | | } |
| | 217 | |
|
| 0 | 218 | | return drawing; |
| | 219 | | } |
| | 220 | |
|
| | 221 | | private static void SetPropertyValue(DrawingModel drawing, PropertyInfo property, object cellValue) |
| | 222 | | { |
| 0 | 223 | | if (cellValue == null) |
| | 224 | | { |
| 0 | 225 | | property.SetValue(drawing, null); |
| 0 | 226 | | return; |
| | 227 | | } |
| | 228 | |
|
| 0 | 229 | | Type propType = property.PropertyType; |
| | 230 | |
|
| | 231 | | try |
| | 232 | | { |
| 0 | 233 | | if (propType == typeof(string)) |
| | 234 | | { |
| 0 | 235 | | property.SetValue(drawing, cellValue.ToString()); |
| | 236 | | } |
| 0 | 237 | | else if (propType == typeof(int)) |
| | 238 | | { |
| 0 | 239 | | property.SetValue(drawing, Convert.ToInt32(cellValue)); |
| | 240 | | } |
| 0 | 241 | | else if (propType == typeof(long)) |
| | 242 | | { |
| 0 | 243 | | property.SetValue(drawing, Convert.ToInt64(cellValue)); |
| | 244 | | } |
| 0 | 245 | | else if (propType == typeof(double)) |
| | 246 | | { |
| 0 | 247 | | property.SetValue(drawing, Convert.ToDouble(cellValue)); |
| | 248 | | } |
| 0 | 249 | | else if (propType == typeof(decimal)) |
| | 250 | | { |
| 0 | 251 | | property.SetValue(drawing, Convert.ToDecimal(cellValue)); |
| | 252 | | } |
| 0 | 253 | | else if (propType == typeof(DateTime)) |
| | 254 | | { |
| 0 | 255 | | property.SetValue(drawing, DateTime.FromOADate(Convert.ToDouble(cellValue))); |
| | 256 | | } |
| 0 | 257 | | else if (propType == typeof(bool)) |
| | 258 | | { |
| 0 | 259 | | switch (property.Name) |
| | 260 | | { |
| | 261 | | case "Visible": |
| 0 | 262 | | property.SetValue(drawing, cellValue.ToString() == ExcelService.EXCEL_VISIBLE_VALUE); |
| 0 | 263 | | break; |
| | 264 | | case "Favorite": |
| 0 | 265 | | property.SetValue(drawing, cellValue.ToString() == ExcelService.EXCEL_FAVORITE_VALUE); |
| 0 | 266 | | break; |
| | 267 | | default: |
| 0 | 268 | | property.SetValue(drawing, cellValue.ToString() == "TRUE"); |
| 0 | 269 | | break; |
| | 270 | | } |
| | 271 | | } |
| 0 | 272 | | else if (propType == typeof(IEnumerable<string>)) |
| | 273 | | { |
| | 274 | | List<string> list; |
| 0 | 275 | | switch (property.Name) |
| | 276 | | { |
| | 277 | | case "Tags": |
| 0 | 278 | | list = cellValue.ToString().Split(new[] { DrawingTagManager.TAG_SEPARATOR }, StringSplitOptions. |
| 0 | 279 | | break; |
| | 280 | | default: |
| 0 | 281 | | list = cellValue.ToString().Split(new[] { ExcelService.EXCEL_SEPARATOR_COMMENTS }, StringSplitOp |
| | 282 | | break; |
| | 283 | | } |
| | 284 | |
|
| 0 | 285 | | property.SetValue(drawing, list); |
| | 286 | | } |
| 0 | 287 | | else if (propType == typeof(Uri)) |
| | 288 | | { |
| 0 | 289 | | if (Uri.IsWellFormedUriString(cellValue.ToString(), UriKind.Absolute)) |
| | 290 | | { |
| 0 | 291 | | property.SetValue(drawing, new Uri(cellValue.ToString())); |
| | 292 | | } |
| | 293 | | } |
| 0 | 294 | | else if (propType.IsEnum) // Manejo de enumeraciones |
| | 295 | | { |
| 0 | 296 | | string stringValue = cellValue.ToString(); |
| | 297 | |
|
| | 298 | | // Intentar mapear al enum por nombre |
| 0 | 299 | | if (Enum.TryParse(propType, stringValue, true, out var enumValue)) |
| | 300 | | { |
| 0 | 301 | | property.SetValue(drawing, enumValue); |
| 0 | 302 | | return; |
| | 303 | | } |
| | 304 | |
|
| | 305 | | // Intentar mapear al enum por descripción |
| 0 | 306 | | foreach (var field in propType.GetFields()) |
| | 307 | | { |
| 0 | 308 | | var descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>(); |
| 0 | 309 | | if (descriptionAttribute != null && descriptionAttribute.Description.Equals(stringValue, StringCompa |
| | 310 | | { |
| 0 | 311 | | var enumParsedValue = Enum.Parse(propType, field.Name); |
| 0 | 312 | | property.SetValue(drawing, enumParsedValue); |
| 0 | 313 | | return; |
| | 314 | | } |
| | 315 | | } |
| | 316 | |
|
| | 317 | | // Si no se puede mapear, asignar valor predeterminado (si existe) |
| 0 | 318 | | var defaultEnumValueAttribute = propType.GetCustomAttribute<DefaultEnumValueAttribute>(); |
| 0 | 319 | | if (defaultEnumValueAttribute != null) |
| | 320 | | { |
| 0 | 321 | | property.SetValue(drawing, defaultEnumValueAttribute.DefaultValue); |
| | 322 | | } |
| | 323 | | else |
| | 324 | | { |
| 0 | 325 | | property.SetValue(drawing, Activator.CreateInstance(propType)); |
| | 326 | | } |
| | 327 | | } |
| 0 | 328 | | } |
| 0 | 329 | | catch (Exception ex) |
| | 330 | | { |
| 0 | 331 | | Console.WriteLine($"Error setting property {property.Name}: {ex.Message}"); |
| 0 | 332 | | } |
| 0 | 333 | | } |
| | 334 | | } |