public async Task <IActionResult> Create([Bind("Excel,Reportes")] ProdEntry entry) { if (ModelState.IsValid) { if (entry?.Excel == null) { return(View(nameof(Create))); } entry.AppUserId = _userManager.GetUserId(User); entry.IP = Request.HttpContext.Connection.RemoteIpAddress.ToString(); entry.FileName = entry.Excel.FileName; entry.Date = DateTime.Now; entry.Success = false; _context.Add(entry); await _context.SaveChangesAsync() .ConfigureAwait(false); var result = string.Empty; //var debug = false; var toskip = new List <string> { "Row", "Sheet", "Centre", "Rows", "Id", "Origin" }; if (entry.Reportes != Tipo.Producción) { toskip.Add("TipoProduccion"); toskip.Add("Dato"); toskip.Add("TipoItemProduccion"); } if (entry.Reportes != Tipo.Semilla) { toskip.Add("OrigenId"); toskip.Add("Origen"); } Stream stream = entry.Excel.OpenReadStream(); ExcelPackage package = new ExcelPackage(stream); await _import.Read <Planilla>(package, entry, toskip).ConfigureAwait(false); return(RedirectToAction(nameof(Index), new { id = entry.Id })); } var Filters = new Dictionary <string, List <string> > { ["Tipo"] = new List <string> { "Semilla", "Cosecha", "Abastecimiento", "Producción" } }; ViewData[nameof(Tipo)] = EViewData.Enum2Select <Tipo>(Filters, "Name"); return(View(entry)); }
public async Task Read <T>(ExcelPackage package, ProdEntry entry, List <string> toskip = null) where T : Planilla { if (entry == null || package == null) { return; } double pgr = 0; var planilla = entry.Reportes.ToString(); var planillas = new List <T> { }; var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; var msg = string.Empty; (Dictionary <string, Dictionary <string, object> > tdata, string error) = Analyze <T>(planilla, bindingFlags, toskip); if (error != null) { msg = $@">ERROR: El valor para la columna {error} no fue encontrada en la base de datos. 0 registros procesados. Verificar archivo."; entry.OutPut += msg; _context.Update(entry); await _context.SaveChangesAsync() .ConfigureAwait(false); return; } ; var pgrTotal = 100; pgr += 4; var pgrReadWrite = (pgrTotal - pgr) / 6; var pgrRow = pgrReadWrite / package.Workbook.Worksheets.Where(w => w.Dimension != null).Sum(w => w.Dimension.Rows); var status = "info"; foreach (var worksheet in package.Workbook.Worksheets.Where(w => w.Dimension != null)) { if (worksheet == null) { break; } int rowCount = worksheet.Dimension.Rows; for (int row = 2; row <= rowCount; row++) { if (worksheet.Cells[row, 1].Value == null) { msg = $">W: Fila '{row}' en hoja '{worksheet.Name}' Está vacía."; entry.OutPut += msg; await _hubContext .Clients.All .SendAsync("Update", "log", msg) .ConfigureAwait(false); status = "warning"; await _hubContext .Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); continue; } var item = Activator.CreateInstance <T>(); item.Row = row; item.Sheet = worksheet.Name; foreach (var d in tdata) { MethodInfo method = typeof(Import).GetMethod("GetFromExcel") .MakeGenericMethod(new Type[] { (Type)d.Value["type"] }); object value = null; value = method.Invoke(value, new object[] { worksheet, (string)d.Value["var"], row }); if (value == null) { status = "danger"; msg = $">ERROR: Columna '{(string)d.Value["var"]}' no encontrada en hoja '{worksheet.Name}'. Verificar archivo.\n0 registros procesados."; entry.OutPut += msg; _context.Update(entry); await _context.SaveChangesAsync() .ConfigureAwait(false); await _hubContext .Clients.All .SendAsync("Update", "log", msg) .ConfigureAwait(false); await _hubContext .Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); return; } if ((string)d.Value["opt"] != null) { Expression e = new Expression((value + (string)d.Value["opt"]).Replace(",", ".", StringComparison.InvariantCultureIgnoreCase)); item[d.Key] = e.Evaluate(); } else { item[d.Key] = value; } System.Diagnostics.Debug.WriteLine($"column:{d.Key}"); } //EXTRA STEPS if (item.Fecha == DateTime.MinValue) { item.Fecha = new DateTime(item.Year, item.Month, 1); } var test = (item.Fecha).ToString("MMyyyy", new CultureInfo("es-CL")); var n = item.Declaracion; item.Dato = entry.Reportes; var dt = (int)item.Dato; var test2 = string.Format(new CultureInfo("es-CL"), "{0}{1}{2}", n, dt, test); item.Id = Convert.ToInt64(test2, new CultureInfo("es-CL")); planillas.Add(item); pgr += pgrRow; await _hubContext .Clients.All .SendAsync("Update", "progress", pgr) .ConfigureAwait(false); await _hubContext .Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); Debug.WriteLine($"row:{item.Row} sheet:{item.Sheet}"); } } entry.Min = planillas.Min(p => p.Fecha); entry.Max = planillas.Max(p => p.Fecha); var registros = planillas.GroupBy(p => p.Id); var pgrP = pgrReadWrite * 5 / registros.Count(); var datos = new List <T>(); var origenes = new List <Origen>(); var centros = new List <Centre>(); var updates = new List <T>(); foreach (var r in registros) { var dato = r.First(); dato.Dato = dato.Dato > 0 ? dato.Dato : entry.Reportes; dato.Peso = r.Sum(p => p.Peso); dato.Row = r.Sum(p => p.Row); var find = await _context.FindAsync <T>(dato.Id).ConfigureAwait(false); if (find == null) { if (dato.Dato == Tipo.Semilla && !origenes.Any(o => o.Id == dato.OrigenId)) { var orig = await _context.FindAsync <Origen>(dato.OrigenId).ConfigureAwait(false); if (orig == null) { if (dato.OrigenId.HasValue && dato.Origen != null) { var origen = new Origen { Id = dato.OrigenId.Value, Name = dato.Origen }; origenes.Add(origen); //context.Origen.Add(origen); //context.SaveChanges(); } else { msg = $">W: Origen no existe en archivo." + $">Declaración de {dato.Dato} N°{dato.Id}, con fecha {dato.Fecha}, " + $"en hoja {dato.Sheet}, filas {dato.Rows} no pudieron ser procesadas.\n" + $">Verificar archivo."; entry.OutPut += msg; entry.Observaciones++; await _hubContext .Clients.All .SendAsync("Update", "log", msg) .ConfigureAwait(false); status = "warning"; await _hubContext .Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); continue; } } } if (!centros.Any(o => o.Id == dato.CentreId)) { var parent = await _context.FindAsync <Centre>(dato.CentreId) .ConfigureAwait(false); if (parent == null) { var comuna = _context.Comuna.FirstOrDefault(c => c.Name.Equals(dato.NombreComuna, StringComparison.InvariantCultureIgnoreCase)); if (comuna != null) { var centre = new Centre { Id = dato.CentreId, ComunaId = comuna.Id, CompanyId = 0, PSMBId = 0, Type = (CentreTypes)2, CuerpoAgua = CuerpoAgua.Mar }; centros.Add(centre); } else //context.Centre.Add(centre); //context.SaveChanges(); { msg = $">W: Comuna {dato.NombreComuna} no existe en base de datos." + $">Declaración de {dato.Dato} N°{dato.Id}, con fecha {dato.Fecha}, " + $"en hoja {dato.Sheet}, filas {dato.Rows} no pudieron ser procesadas.\n" + $">Verificar archivo."; entry.OutPut += msg; entry.Observaciones++; await _hubContext .Clients.All .SendAsync("Update", "log", msg) .ConfigureAwait(false); status = "warning"; await _hubContext .Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); continue; } } } datos.Add(dato); //context.Add(dato); //try //{ //context.SaveChanges(); entry.Agregadas++; await _hubContext .Clients.All .SendAsync("Update", "agregada", entry.Agregadas) .ConfigureAwait(false); //context.Entries.Update(entry); //} //catch //{ // //Buscadores de Empresas // //http://www.genealog.cl // //https://www.mercantil.com // //https://www.smartx.cl // //Buscador de personas // //https://www.nombrerutyfirma.cl // msg = $">W: Declaración de {dato.Dato} N°{dato.Id}, con fecha {dato.Fecha}, en hoja {dato.Sheet}, filas {dato.Rows} no pudieron ser procesadas. Verificar archivo."; // await _hubContext // .Clients.All // .SendAsync("Update", "log", msg) // .ConfigureAwait(false); // entry.OutPut += msg; // var centre = await _context.Centre.FindAsync(dato.CentreId) // .ConfigureAwait(false); // if (centre == null) // { // msg = $">Centro {dato.CentreId} no existe en base de datos."; // await _hubContext // .Clients.All // .SendAsync("Update", "log", msg) // .ConfigureAwait(false); // entry.OutPut += msg; // } // entry.OutPut += msg; // entry.Observaciones++; // status = "warning"; // await _hubContext // .Clients.All // .SendAsync("Update", "status", status) // .ConfigureAwait(false); // continue; //} } else { var updated = AddChanges(find, dato); if (updated != find) { updates.Add(updated); //context.Update(updated); //try //{ //context.SaveChanges(); entry.Actualizadas++; await _hubContext .Clients.All .SendAsync("Update", "agregada", entry.Agregadas) .ConfigureAwait(false); //context.Entries.Update(entry); //} //catch //{ // msg = $">Unknown error: Declaración de {dato.Dato} N°{dato.Id}, con fecha {dato.Fecha}, en hoja {dato.Sheet}, filas {dato.Rows} no pudieron ser procesadas. Verificar archivo."; // await _hubContext // .Clients.All // .SendAsync("Update", "log", msg) // .ConfigureAwait(false); // entry.OutPut += msg; // entry.Observaciones++; // status = "warning"; // await _hubContext // .Clients.All // .SendAsync("Update", "status", status) // .ConfigureAwait(false); // continue; //} } } pgr += pgrP; await _hubContext.Clients.All .SendAsync("Update", "progress", pgr) .ConfigureAwait(false); await _hubContext.Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); } await _context.Centre.AddRangeAsync(centros).ConfigureAwait(false); await _context.Origen.AddRangeAsync(origenes).ConfigureAwait(false); await _context.Planilla.AddRangeAsync(datos).ConfigureAwait(false); _context.Planilla.UpdateRange(updates); //context.BulkInsert(centros); //context.BulkInsert(origenes); //context.BulkInsert(datos); //context.BulkUpdate(updates); status = "success"; await _hubContext.Clients.All .SendAsync("Update", "progress", 100) .ConfigureAwait(false); await _hubContext.Clients.All .SendAsync("Update", "status", status) .ConfigureAwait(false); msg = $">{entry.Agregadas} añadidos" + (entry.Actualizadas != 0 ? $"y {entry.Actualizadas} registros actualizados " : " ") + "exitosamente."; entry.OutPut += msg; entry.Success = true; await _hubContext.Clients.All.SendAsync("Update", "log", msg) .ConfigureAwait(false); _context.ProdEntry.Update(entry); await _context.SaveChangesAsync().ConfigureAwait(false); }