public async Task <InvoiceData> Facturar(Order order) { var invoiceData = new InvoiceData(); try { FECAEResponse factura = await FECAESolicitarAsync(order); invoiceData = _mapper.Map <FECAEResponse.FECAECabResponse, InvoiceData>(factura.FeCabResp); if (factura.Errs != null) { invoiceData.AddInvoiceDetailRange(factura.Errs.Select(x => new InvoiceDetail("Error", invoiceData, x))); } if (factura.Events != null) { invoiceData.AddInvoiceDetailRange(factura.Errs.Select(x => new InvoiceDetail("Evento", invoiceData, x))); } if (factura.FeDetResp != null) { var obs = new List <FECAEResponse.CodeMessage>(); foreach (var ob in factura.FeDetResp.Where(o => o.Observaciones != null)) { obs.AddRange(ob.Observaciones); } invoiceData.AddInvoiceDetailRange(obs.Select(x => new InvoiceDetail("Observacion", invoiceData, x))); invoiceData.AddCaeRange(factura.FeDetResp.Select(x => { var cae = _mapper.Map <FECAEResponse.FECAEDetResponse, Cae>(x); cae.InvoiceData = invoiceData; return(cae); })); } } catch (Exception ex) { var errs = new List <FECAEResponse.CodeMessage> { new FECAEResponse.CodeMessage { Code = ex.HResult, Msg = ex.Message } }; invoiceData.AddInvoiceDetailRange(errs.Select(x => new InvoiceDetail("Excepción", invoiceData, x))); } finally { invoiceData.Order = order; invoiceData.OrderId = order.OrderId; invoiceData.Created = _calendar.LocalTime(); } await _dbCtx.InvoiceData.AddAsync(invoiceData); await _dbCtx.SaveChangesAsync(); return(invoiceData); }