Esempio n. 1
0
        private SPList GetDocumentLibraryFromUrl(string documentLibraryUrl, string username)
        {
            SPWeb oWeb = null;

            Uri webUrl = new Uri(new Uri(Context.Request.Url.ToString()), documentLibraryUrl);

            oWeb = new SPSite(webUrl.OriginalString).OpenWeb();
            if (!String.IsNullOrEmpty(username))
            {
                SPUserToken userToken = oWeb.SiteUsers[username].UserToken;
                oWeb.Dispose();
                SPSite site = new SPSite(webUrl.OriginalString, userToken);
                oWeb = site.OpenWeb();
            }
            SPList documentLibrary = oWeb.GetList(webUrl.OriginalString);

            if (documentLibrary.BaseType == SPBaseType.DocumentLibrary)
            {
                return(documentLibrary);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Obtains a document library object from the given URL
        /// </summary>
        /// <param name="documentLibraryUrl">The doucment library URL</param>
        /// <returns>SPList object if the URL is correct, otherwise null</returns>
        private SPList  GetDocumentLibraryFromUrl(string documentLibraryUrl)
        {
            Uri   webUrl = new Uri(new Uri(Context.Request.Url.ToString()), documentLibraryUrl);
            SPWeb oWeb   = new SPSite(webUrl.OriginalString).OpenWeb();

            SPList documentLibrary = oWeb.GetList(webUrl.OriginalString);

            if (documentLibrary.BaseType == SPBaseType.DocumentLibrary)
            {
                return(documentLibrary);
            }
            else
            {
                return(null);
            }
        }
        public void NumerarFacturas(int ID_FACTURACION, int ID_TIPO_FACTURA, bool NUMERAR_TODAS,
            int? CORRELATIVO_DESDE, int? CORRELATIVO_HASTA, int NUMERO_FACTURA_INICIAL)
        {
            Init();
            ListaDetalleFactura = new List<DTO_REPORTE_DETALLEFACTURA_PRESTACION>();
            try
            {
                using (LQCEEntities context = new LQCEEntities())
                {
                    RepositorioFACTURA _RepositorioFACTURA = new RepositorioFACTURA(context);

                    var q = _RepositorioFACTURA.GetByFilterWithReferences(null, ID_FACTURACION, ID_TIPO_FACTURA,
                        null, "", null, null, null, "", "", "", "", null, null, "", "", "", null);

                    if (!NUMERAR_TODAS)
                    {
                        if (!CORRELATIVO_DESDE.HasValue)
                            throw new Exception("Debe señalar factura inicial a facturar");
                        if (!CORRELATIVO_HASTA.HasValue)
                            throw new Exception("Debe señalar factura final a facturar");
                        if (CORRELATIVO_DESDE.Value > CORRELATIVO_HASTA.Value)
                            throw new Exception("El rango de facturas está mal definido, el valor inicial es mayor al valor final");

                        q = q.Where(f => f.CORRELATIVO >= CORRELATIVO_DESDE.Value && f.CORRELATIVO <= CORRELATIVO_HASTA.Value);
                    }

                    if (q.Any(f => f.NUMERO_FACTURA.HasValue))
                        throw new Exception("Ya existen facturas numeradas en el rango seleccionado");

                    int NUMERO_FACTURA_FINAL = NUMERO_FACTURA_INICIAL + q.Count() - 1;

                    var q2 = _RepositorioFACTURA.GetByFilterWithReferences(null, null, ID_TIPO_FACTURA,
                        null, "", null, null, null, null, null, "", "", null, null, "", "", "", null);
                    if (q2.Any(f => f.NUMERO_FACTURA.HasValue
                        && f.NUMERO_FACTURA >= NUMERO_FACTURA_INICIAL
                        && f.NUMERO_FACTURA <= NUMERO_FACTURA_FINAL))
                        throw new Exception("Ya existen facturas numeradas con los numeros de facturas indicados");

                    int NUEVO_NUMERO_FACTURA = NUMERO_FACTURA_INICIAL;
                    foreach (var _FACTURA in q.OrderBy(f => f.CORRELATIVO).ToList())
                    {
                        if (_FACTURA.NUMERO_FACTURA.HasValue)
                            throw new Exception("Factura ya está numerada");

                        _FACTURA.NUMERO_FACTURA = NUEVO_NUMERO_FACTURA;
                        context.ApplyPropertyChanges("FACTURA", _FACTURA);

                        NUEVO_NUMERO_FACTURA++;
                    }
                    context.SaveChanges();

                    try
                    {
                        foreach (var _FACTURA in q.OrderBy(f => f.CORRELATIVO).ToList())
                        {
                            // PENDIENTE: Generar PDFs
                            var LISTA_DTO_REPORTE_FACTURA = GetReporteFacturaByID_FACTURA(_FACTURA.ID);

                            ListaDetalleFactura = GetReporteDetalleFacturaByID_FACTURACION(_FACTURA.ID);

                            string deviceInfo =
                                          "<DeviceInfo>" +
                                          "  <OutputFormat>PDF</OutputFormat>" +
                                         "  <PageWidth>8.2in</PageWidth>" +
                                      "  <PageHeight>11.7in</PageHeight>" +
                                      "  <MarginTop>0in</MarginTop>" +
                                      "  <MarginLeft>0in</MarginLeft>" +
                                      "  <MarginRight>0in</MarginRight>" +
                                      "  <MarginBottom>0in</MarginBottom>" +
                                          "</DeviceInfo>";
                            Warning[] warnings;
                            m_streams_matriz = new List<Stream>();
                            m_streams_DetalleFactura = new List<Stream>();

                            // m_streams_individual = new List<Stream>();

                            // Documento 1: Un archivo por factura con fondo
                            var tf = from f in LISTA_DTO_REPORTE_FACTURA
                                     group f by f.NOMBRE_REPORTE_FACTURA_INDIVIDUAL into g
                                     select g;

                            foreach (var facturas in tf)
                            {
                                Hashtable propiedades = new Hashtable();
                                propiedades.Add("Fecha de Documento", _FACTURA.FACTURACION.FECHA_FACTURACION);
                                propiedades.Add("Tipo de Documento", "Factura " + facturas.FirstOrDefault().NOMBRE_TIPO_FACTURA);
                                propiedades.Add("Formato", "Individual");
                                propiedades.Add("RUT Cliente", facturas.FirstOrDefault().RUT_CLIENTE);
                                propiedades.Add("Nombre Cliente", facturas.FirstOrDefault().NOMBRE_CLIENTE);

                                ReportViewer _ReportViewer = new ReportViewer();
                                _ReportViewer.ProcessingMode = ProcessingMode.Local;
                                _ReportViewer.LocalReport.ShowDetailedSubreportMessages = true;
                                _ReportViewer.LocalReport.DataSources.Clear();
                                _ReportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", facturas));

                                _ReportViewer.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte." + facturas.Key;

                                _ReportViewer.LocalReport.Render("PDF", deviceInfo, CreateStream, out warnings);
                                foreach (Stream stream in m_streams_matriz)
                                    stream.Position = 0;

                                using (SPWeb spWeb = new SPSite(Settings.Default.SP_WEB).OpenWeb())
                                {
                                    SPList spList = spWeb.GetList(Settings.Default.SP_LIBRERIA_FACTURAS);
                                    string strNombreFactura = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + _FACTURA.NUMERO_FACTURA.Value.ToString() + "_" + facturas.Key + ".pdf";
                                    spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreFactura, m_streams_matriz[0], propiedades, true);
                                    spList.Update();
                                }
                            }

                            // Documento 2: Un archivo por cada detalles de facturas
                            List<DTO_REPORTE_DETALLEFACTURA_FACTURA> LISTA_DTO_REPORTE_DETALLEFACTURA_FACTURA =
                                (from df in ListaDetalleFactura
                                 group df by df.ID_FACTURA into g
                                 select new DTO_REPORTE_DETALLEFACTURA_FACTURA
                                 {
                                     ID_FACTURA = g.Key,
                                     ID_CLIENTE = g.FirstOrDefault().ID_CLIENTE,
                                     NOMBRE_CLIENTE = g.FirstOrDefault().NOMBRE_CLIENTE,
                                     RUT_CLIENTE = g.FirstOrDefault().RUT_CLIENTE,
                                     DETALLE = g.FirstOrDefault().DETALLE,
                                     SUMA_PENDIENTE = g.Where(p => p.ESTADO_PENDIENTE == "INPAGO" || p.ESTADO_PREVISION == "INPAGO").Sum(p => p.MONTO_TOTAL)
                                 }).ToList();

                            Hashtable propiedadesDetalle = new Hashtable();
                            propiedadesDetalle.Add("Fecha de Documento", _FACTURA.FACTURACION.FECHA_FACTURACION);
                            propiedadesDetalle.Add("Tipo de Documento", "Detalle de Factura");
                            propiedadesDetalle.Add("Formato", "Individual");
                            propiedadesDetalle.Add("RUT Cliente", _FACTURA.RUT_CLIENTE);
                            propiedadesDetalle.Add("Nombre Cliente", _FACTURA.NOMBRE_CLIENTE);

                            ReportViewer _ReportViewerDetalle = new ReportViewer();
                            _ReportViewerDetalle.ProcessingMode = ProcessingMode.Local;
                            _ReportViewerDetalle.LocalReport.ShowDetailedSubreportMessages = true;
                            _ReportViewerDetalle.LocalReport.DataSources.Clear();
                            _ReportViewerDetalle.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", LISTA_DTO_REPORTE_DETALLEFACTURA_FACTURA));
                            _ReportViewerDetalle.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(ReporteDetalleFactura_SubreportProcessingEventHandler);
                            _ReportViewerDetalle.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte.DetalleFactura.rdlc";

                            _ReportViewerDetalle.LocalReport.Render("PDF", deviceInfo, CreateStreamDetalleFactura, out warnings);
                            foreach (Stream stream in m_streams_DetalleFactura)
                                stream.Position = 0;

                            using (SPWeb spWeb = new SPSite(Settings.Default.SP_WEB).OpenWeb())
                            {
                                SPList spList = spWeb.GetList(Settings.Default.SP_LIBRERIA_FACTURAS);
                                string strNombreFactura = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + _FACTURA.NUMERO_FACTURA.Value.ToString() + "_DetalleFactura.pdf";
                                spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreFactura, m_streams_DetalleFactura[0], propiedadesDetalle, true);
                                spList.Update();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // En caso de error, al generar los PDF se eliminan los registros de las facturas
                        foreach (var _FACTURA in q.OrderBy(f => f.CORRELATIVO).ToList())
                        {

                            _FACTURA.NUMERO_FACTURA = null;
                            context.ApplyPropertyChanges("FACTURA", _FACTURA);
                        }
                        context.SaveChanges();
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                Error = ex.Message;
                throw ex;
            }
        }
        public void EmitirNotasCobros(DateTime FechaFacturacionDesde, DateTime FechaFacturacionHasta,
            int IdTipoCobro, int? IdCliente)
        {
            Init();
            try
            {
                using (LQCEEntities context = new LQCEEntities())
                {
                    RepositorioFACTURACION _RepositorioFACTURACION = new RepositorioFACTURACION(context);
                    RepositorioTIPO_COBRO _RepositorioTIPO_COBRO = new RepositorioTIPO_COBRO(context);
                    RepositorioFACTURA _RepositorioFACTURA = new RepositorioFACTURA(context);
                    RepositorioCLIENTE _RepositorioCLIENTE = new RepositorioCLIENTE(context);
                    RepositorioVISTA_REPORTE_FACTURA _RepositorioVISTA_REPORTE_FACTURA = new RepositorioVISTA_REPORTE_FACTURA(context);

                    TIPO_COBRO _TIPO_COBRO = _RepositorioTIPO_COBRO.GetById(IdTipoCobro);
                    if (_TIPO_COBRO == null)
                        throw new Exception("No se encuentra información del tipo de cobro");

                    COBRO _COBRO = new COBRO();
                    _COBRO.FECHA_COBRO = DateTime.Now;
                    _COBRO.TIPO_COBRO = _TIPO_COBRO;
                    _COBRO.ACTIVO = true;
                    context.AddToCOBRO(_COBRO);

                    var cliente_facturas = (from f in _RepositorioFACTURACION.GetFacturasPorNotificar(FechaFacturacionDesde,
                        FechaFacturacionHasta, IdTipoCobro, IdCliente)
                                            group f by f.ID_CLIENTE into g
                                            select new
                                            {
                                                IdCliente = g.Key,
                                                Facturas = g
                                            }).ToList();

                    if (!cliente_facturas.Any())
                        throw new Exception("No hay facturas que notificar");

                    int correlativo = 1;
                    foreach (var cf in cliente_facturas)
                    {
                        CLIENTE _CLIENTE = _RepositorioCLIENTE.GetById(cf.IdCliente);
                        if (_CLIENTE == null)
                            throw new Exception("No se encuentra información del cliente");

                        NOTA_COBRO _NOTA_COBRO = new NOTA_COBRO();
                        _NOTA_COBRO.COBRO = _COBRO;
                        _NOTA_COBRO.CORRELATIVO = correlativo;
                        _NOTA_COBRO.CLIENTE = _CLIENTE;
                        _NOTA_COBRO.ACTIVO = true;
                        context.AddToNOTA_COBRO(_NOTA_COBRO);

                        foreach (var f in cf.Facturas)
                        {
                            FACTURA _FACTURA = _RepositorioFACTURA.GetById(f.ID);
                            if (_FACTURA == null)
                                throw new Exception("No se encuentra información de la factura ");

                            VISTA_REPORTE_FACTURA _VISTA_REPORTE_FACTURA = _RepositorioVISTA_REPORTE_FACTURA.GetById(f.ID);
                            if (_VISTA_REPORTE_FACTURA == null)
                                throw new Exception("No se encuentra información de la factura ");

                            NOTA_COBRO_DETALLE _NOTA_COBRO_DETALLE = new NOTA_COBRO_DETALLE();
                            _NOTA_COBRO_DETALLE.NOTA_COBRO = _NOTA_COBRO;
                            _NOTA_COBRO_DETALLE.FACTURA = _FACTURA;
                            if (_FACTURA.PAGADA.HasValue && _FACTURA.PAGADA.Value == true)
                            {
                                _NOTA_COBRO_DETALLE.MONTO_PENDIENTE = 0;
                            }
                            else
                            {
                                _NOTA_COBRO_DETALLE.MONTO_PENDIENTE = _VISTA_REPORTE_FACTURA.SALDO_DEUDOR ?? 0;
                            }
                            _NOTA_COBRO_DETALLE.ACTIVO = true;
                            context.AddToNOTA_COBRO_DETALLE(_NOTA_COBRO_DETALLE);
                        }

                        correlativo++;
                    }

                    context.SaveChanges();

                    try
                    {
                        ListaNotaCobro = GetReporteNotaCobroByID_COBRO(context, _COBRO.ID);

                        string deviceInfo =
                                      "<DeviceInfo>" +
                                      "  <OutputFormat>PDF</OutputFormat>" +
                                      "  <PageWidth>8.2in</PageWidth>" +
                                      "  <PageHeight>11.7in</PageHeight>" +
                                      "  <MarginTop>0in</MarginTop>" +
                                      "  <MarginLeft>0in</MarginLeft>" +
                                      "  <MarginRight>0in</MarginRight>" +
                                      "  <MarginBottom>0in</MarginBottom>" +
                                      "</DeviceInfo>";
                        Warning[] warnings;
                        m_streams_NotaCobro = new List<Stream>();

                        List<DTO_REPORTE_NOTA_COBRO> ListaNotaCobroEncabezado = (from nc in ListaNotaCobro
                                                                                 group nc by nc.CORRELATIVO into g
                                                                                 select new DTO_REPORTE_NOTA_COBRO
                                                                                 {
                                                                                     ID_COBRO = g.FirstOrDefault().ID_COBRO,
                                                                                     ID_CLIENTE = g.FirstOrDefault().ID_CLIENTE,
                                                                                     CORRELATIVO = g.Key,
                                                                                     NOMBRE_CLIENTE = g.FirstOrDefault().NOMBRE_CLIENTE,
                                                                                     RUT_CLIENTE = g.FirstOrDefault().RUT_CLIENTE,
                                                                                     NOMBRE_REPORTE = g.FirstOrDefault().NOMBRE_REPORTE,
                                                                                 }).ToList();

                        // Documento 1: Un archivo con todas las notas de cobro emitidas
                        Hashtable propiedades = new Hashtable();
                        propiedades.Add("Fecha de Documento", _COBRO.FECHA_COBRO);
                        propiedades.Add("Tipo de Documento", "Nota de Cobro " + ListaNotaCobroEncabezado.FirstOrDefault().NOMBRE_REPORTE);
                        propiedades.Add("Formato", "Consolidado");

                        ReportViewer _ReportViewer = new ReportViewer();
                        _ReportViewer.ProcessingMode = ProcessingMode.Local;
                        _ReportViewer.LocalReport.ShowDetailedSubreportMessages = true;
                        _ReportViewer.LocalReport.DataSources.Clear();
                        _ReportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ListaNotaCobroEncabezado));
                        _ReportViewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(ReporteNotaCobro_SubreportProcessingEventHandler);
                        _ReportViewer.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte." + ListaNotaCobroEncabezado.FirstOrDefault().NOMBRE_REPORTE;

                        _ReportViewer.LocalReport.Render("PDF", deviceInfo, CreateStreamNotaCobro, out warnings);
                        foreach (Stream stream in m_streams_NotaCobro)
                            stream.Position = 0;

                        using (SPWeb spWeb = new SPSite(Settings.Default.SP_WEB).OpenWeb())
                        {
                            SPList spList = spWeb.GetList(Settings.Default.SP_LIBRERIA_FACTURAS);
                            string strNombreFactura = DateTime.Now.ToString("yyyyMMddhhmmss") + "_NotaCobro_" + _COBRO.TIPO_COBRO.NOMBRE + ".pdf";
                            spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreFactura, m_streams_NotaCobro[0], propiedades, true);
                            spList.Update();
                        }

                        foreach (var item in ListaNotaCobroEncabezado)
                        {
                            m_streams_NotaCobroIndividual = new List<Stream>();
                            // Documento 2: Un archivo por cada detalles de facturas
                            List<DTO_REPORTE_NOTA_COBRO> LISTA_DTO_REPORTE_NOTA_COBRO2 = new List<DTO_REPORTE_NOTA_COBRO>();
                            LISTA_DTO_REPORTE_NOTA_COBRO2.Add(item);

                            Hashtable propiedadesDetalle = new Hashtable();
                            propiedadesDetalle.Add("Fecha de Documento", _COBRO.FECHA_COBRO);
                            propiedadesDetalle.Add("Tipo de Documento", "Nota de Cobro " + item.NOMBRE_REPORTE);
                            propiedadesDetalle.Add("Formato", "Individual");
                            propiedadesDetalle.Add("RUT Cliente", item.RUT_CLIENTE);
                            propiedadesDetalle.Add("Nombre Cliente", item.NOMBRE_CLIENTE);

                            ReportViewer _ReportViewerDetalle = new ReportViewer();
                            _ReportViewerDetalle.ProcessingMode = ProcessingMode.Local;
                            _ReportViewerDetalle.LocalReport.ShowDetailedSubreportMessages = true;
                            _ReportViewerDetalle.LocalReport.DataSources.Clear();
                            _ReportViewerDetalle.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", LISTA_DTO_REPORTE_NOTA_COBRO2));
                            _ReportViewerDetalle.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(ReporteNotaCobro_SubreportProcessingEventHandler);
                            _ReportViewerDetalle.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte." + item.NOMBRE_REPORTE;

                            _ReportViewerDetalle.LocalReport.Render("PDF", deviceInfo, CreateStreamNotaCobroIndividual, out warnings);
                            foreach (Stream stream in m_streams_NotaCobroIndividual)
                                stream.Position = 0;

                            using (SPWeb spWeb = new SPSite(Settings.Default.SP_WEB).OpenWeb())
                            {
                                SPList spList = spWeb.GetList(Settings.Default.SP_LIBRERIA_FACTURAS);
                                string strNombreFactura = DateTime.Now.ToString("yyyyMMddhhmmss") + "_NotaCobroIndividual_" + _COBRO.TIPO_COBRO.NOMBRE + "_" + item.NOMBRE_CLIENTE + ".pdf";
                                spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreFactura, m_streams_NotaCobroIndividual[0], propiedadesDetalle, true);
                                spList.Update();
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        RepositorioCOBRO _RepositorioCOBRO = new RepositorioCOBRO(context);
                        COBRO _NUEVO_COBRO = _RepositorioCOBRO.GetByIdWithReferences(_COBRO.ID);

                        _NUEVO_COBRO.ACTIVO = false;
                        foreach (var _NOTA_COBRO in _NUEVO_COBRO.NOTA_COBRO)
                        {
                            _NOTA_COBRO.ACTIVO = false;
                            foreach (var _NOTA_COBRO_DETALLE in _NOTA_COBRO.NOTA_COBRO_DETALLE)
                            {
                                _NOTA_COBRO_DETALLE.ACTIVO = false;
                                context.ApplyPropertyChanges("NOTA_COBRO_DETALLE", _NOTA_COBRO_DETALLE);
                            }
                            context.ApplyPropertyChanges("NOTA_COBRO", _NOTA_COBRO);
                        }
                        context.ApplyPropertyChanges("COBRO", _NUEVO_COBRO);
                        context.SaveChanges();
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                Error = ex.Message;
                throw ex;
            }
        }
        public void EmitirFacturas(List<DTO_EMISION_FACTURA> ListaClientesFacturar, DateTime FechaDesde,
            DateTime FechaHasta)
        {
            Init();
            ListaDetalleFactura = new List<DTO_REPORTE_DETALLEFACTURA_PRESTACION>();
            try
            {
                using (LQCEEntities context = new LQCEEntities())
                {
                    RepositorioFACTURACION _RepositorioFACTURACION = new RepositorioFACTURACION(context);
                    RepositorioCLIENTE _RepositorioCLIENTE = new RepositorioCLIENTE(context);
                    RepositorioPRESTACION _RepositorioPRESTACION = new RepositorioPRESTACION(context);

                    FACTURACION _FACTURACION = new FACTURACION();
                    _FACTURACION.FECHA_FACTURACION = DateTime.Now;
                    _FACTURACION.ACTIVO = true;
                    context.AddToFACTURACION(_FACTURACION);

                    int correlativo = 1;
                    foreach (var item in ListaClientesFacturar)
                    {
                        CLIENTE _CLIENTE = _RepositorioCLIENTE.GetByIdWithReferences(item.ID_CLIENTE);
                        if (_CLIENTE == null)
                            throw new Exception("No se encuentra información del cliente");

                        var prestaciones = _RepositorioFACTURACION.GetPrestacionesPorFacturar(FechaDesde, FechaHasta, item.ID_CLIENTE).ToList();

                        FACTURA _FACTURA = new FACTURA();
                        _FACTURA.FACTURACION = _FACTURACION;
                        _FACTURA.CORRELATIVO = correlativo;
                        _FACTURA.CLIENTE = _CLIENTE;
                        _FACTURA.NUMERO_FACTURA = null;
                        _FACTURA.RUT_LABORATORIO = _CLIENTE.TIPO_FACTURA.RUT_FACTURA;
                        _FACTURA.ACTIVO = true;
                        _FACTURA.DESCUENTO = item.DESCUENTO;
                        _FACTURA.NOMBRE_CLIENTE = _CLIENTE.NOMBRE;
                        _FACTURA.RUT_CLIENTE = _CLIENTE.RUT;
                        _FACTURA.DIRECCION = _CLIENTE.DIRECCION;
                        if (_CLIENTE.COMUNA != null)
                        {
                            _FACTURA.NOMBRE_COMUNA = _CLIENTE.COMUNA.NOMBRE;
                        }
                        _FACTURA.FONO = _CLIENTE.FONO;
                        _FACTURA.GIRO = _CLIENTE.GIRO;
                        _FACTURA.DETALLE = "Exámenes realizados del " + FechaDesde.ToString("dd MMMM yyyy") + " al " + FechaHasta.ToString("dd MMMM yyyy");
                        _FACTURA.TIPO_FACTURA = _CLIENTE.TIPO_FACTURA;

                        context.AddToFACTURA(_FACTURA);

                        int suma_total = 0;
                        foreach (var prestacion in prestaciones)
                        {
                            PRESTACION _PRESTACION = _RepositorioPRESTACION.GetById(prestacion.ID);
                            if (_PRESTACION == null)
                                throw new Exception("No se encuentra información de la prestación");

                            int total = (int)(prestacion.TOTAL * (1 - (double)item.DESCUENTO / 100.0));
                            suma_total += total;

                            FACTURA_DETALLE _FACTURA_DETALLE = new FACTURA_DETALLE();
                            _FACTURA_DETALLE.FACTURA = _FACTURA;
                            _FACTURA_DETALLE.PRESTACION = _PRESTACION;
                            _FACTURA_DETALLE.MONTO_TOTAL = total;
                            _FACTURA_DETALLE.MONTO_COBRADO = 0;
                            _FACTURA_DETALLE.ACTIVO = true;
                            context.AddToFACTURA_DETALLE(_FACTURA_DETALLE);
                        }

                        if (_CLIENTE.TIPO_FACTURA.AFECTO_IVA)
                        {
                            if (_CLIENTE.TIPO_PRESTACION.ID == (int)Enum.ENUM_TIPO_PRESTACION.Humanas)
                            {
                                _FACTURA.NETO = suma_total;
                                _FACTURA.IVA = (int)(suma_total * 0.19);
                                _FACTURA.TOTAL = (int)(suma_total * 1.19);
                            }
                            else
                            {
                                _FACTURA.NETO = (int)(suma_total / 1.19);
                                _FACTURA.IVA = suma_total - (int)(suma_total / 1.19);
                                _FACTURA.TOTAL = suma_total;
                            }
                        }
                        else
                        {
                            _FACTURA.NETO = suma_total;
                            _FACTURA.IVA = 0;
                            _FACTURA.TOTAL = suma_total;
                        }
                        //context.ApplyPropertyChanges("FACTURA", _FACTURA);
                        correlativo++;
                    }
                    context.SaveChanges();

                    try
                    {
                        var LISTA_DTO_REPORTE_FACTURA = GetReporteFacturaByID_FACTURACION(_FACTURACION.ID);

                        ListaDetalleFactura = GetReporteDetalleFacturaByID_FACTURACION(_FACTURACION.ID);

                        string deviceInfo =
                                      "<DeviceInfo>" +
                                      "  <OutputFormat>PDF</OutputFormat>" +
                                      "  <PageWidth>21cm</PageWidth>" +
                                      "  <PageHeight>29.7cm</PageHeight>" +
                                      "  <MarginTop>1cm</MarginTop>" +
                                      "  <MarginLeft>0.5cm</MarginLeft>" +
                                      "  <MarginRight>0.5cm</MarginRight>" +
                                      "  <MarginBottom>1cm</MarginBottom>" +
                                      "</DeviceInfo>";
                        Warning[] warnings;
                        m_streams_matriz = new List<Stream>();
                        m_streams_DetalleFactura = new List<Stream>();

                        string deviceInfoDireccion =
                                     "<DeviceInfo>" +
                                     "  <OutputFormat>PDF</OutputFormat>" +
                                     "  <PageWidth>11in</PageWidth>" +
                                     "  <PageHeight>1.3in</PageHeight>" +
                                     "  <MarginTop>0.5in</MarginTop>" +
                                     "  <MarginLeft>1in</MarginLeft>" +
                                     "  <MarginRight>1in</MarginRight>" +
                                     "  <MarginBottom>0.5in</MarginBottom>" +
                                     "</DeviceInfo>";
                        Warning[] warningsDireccion;
                        m_streams_Direccion = new List<Stream>();

                        // Documento 1: Un archivo con todas las facturas sin fondo para imprimir en matriz de punto
                        var tf = from f in LISTA_DTO_REPORTE_FACTURA
                                 group f by f.NOMBRE_REPORTE_FACTURA into g
                                 select g;

                        foreach (var facturas in tf)
                        {
                            Hashtable propiedades = new Hashtable();
                            propiedades.Add("Fecha de Documento", _FACTURACION.FECHA_FACTURACION);
                            propiedades.Add("Tipo de Documento", "Factura " + facturas.FirstOrDefault().NOMBRE_TIPO_FACTURA);
                            propiedades.Add("Formato", "Consolidado");

                            Hashtable propiedadesDireccion = new Hashtable();
                            propiedadesDireccion.Add("Fecha de Documento", _FACTURACION.FECHA_FACTURACION);
                            propiedadesDireccion.Add("Tipo de Documento", "Direcciones " + facturas.FirstOrDefault().NOMBRE_TIPO_FACTURA);
                            propiedadesDireccion.Add("Formato", "Consolidado");

                            ReportViewer _ReportViewer = new ReportViewer();
                            _ReportViewer.ProcessingMode = ProcessingMode.Local;
                            _ReportViewer.LocalReport.ShowDetailedSubreportMessages = true;
                            _ReportViewer.LocalReport.DataSources.Clear();
                            _ReportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", facturas));
                            _ReportViewer.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte." + facturas.Key;
                            _ReportViewer.LocalReport.Render("PDF", deviceInfo, CreateStream, out warnings);
                            foreach (Stream stream in m_streams_matriz)
                                stream.Position = 0;

                            ReportViewer _ReportViewerDireccion = new ReportViewer();
                            _ReportViewerDireccion.ProcessingMode = ProcessingMode.Local;
                            _ReportViewerDireccion.LocalReport.DataSources.Clear();
                            _ReportViewerDireccion.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", facturas));
                            _ReportViewerDireccion.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte.DireccionFactura.rdlc";
                            _ReportViewerDireccion.LocalReport.Render("PDF", deviceInfoDireccion, CreateStreamDireccion, out warningsDireccion);
                            foreach (Stream stream in m_streams_Direccion)
                                stream.Position = 0;

                            using (SPWeb spWeb = new SPSite(Settings.Default.SP_WEB).OpenWeb())
                            {
                                SPList spList = spWeb.GetList(Settings.Default.SP_LIBRERIA_FACTURAS);

                                string strNombreFactura = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + facturas.Key + ".pdf";
                                spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreFactura, m_streams_matriz[0], propiedades, true);
                                spList.Update();

                                string strNombreDirecciones = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + facturas.Key + " - Direcciones.pdf";
                                spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreDirecciones, m_streams_Direccion[0], propiedadesDireccion, true);
                                spList.Update();
                            }
                        }

                        // Documento 2: Un archivo con todos los detalles de facturas
                        List<DTO_REPORTE_DETALLEFACTURA_FACTURA> LISTA_DTO_REPORTE_DETALLEFACTURA_FACTURA =
                            (from df in ListaDetalleFactura
                             group df by df.ID_FACTURA into g
                             select new DTO_REPORTE_DETALLEFACTURA_FACTURA
                             {
                                 ID_FACTURA = g.Key,
                                 ID_CLIENTE = g.FirstOrDefault().ID_CLIENTE,
                                 NOMBRE_CLIENTE = g.FirstOrDefault().NOMBRE_CLIENTE,
                                 RUT_CLIENTE = g.FirstOrDefault().RUT_CLIENTE,
                                 DETALLE = g.FirstOrDefault().DETALLE,
                                 SUMA_PENDIENTE = g.Where(p => p.ESTADO_PENDIENTE == "INPAGO" || p.ESTADO_PREVISION == "INPAGO").Sum(p => p.MONTO_TOTAL)
                             }).ToList();

                        Hashtable propiedadesDetalle = new Hashtable();
                        propiedadesDetalle.Add("Fecha de Documento", _FACTURACION.FECHA_FACTURACION);
                        propiedadesDetalle.Add("Tipo de Documento", "Detalle de Factura");
                        propiedadesDetalle.Add("Formato", "Consolidado");

                        ReportViewer _ReportViewerDetalle = new ReportViewer();
                        _ReportViewerDetalle.ProcessingMode = ProcessingMode.Local;
                        _ReportViewerDetalle.LocalReport.ShowDetailedSubreportMessages = true;
                        _ReportViewerDetalle.LocalReport.DataSources.Clear();
                        _ReportViewerDetalle.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", LISTA_DTO_REPORTE_DETALLEFACTURA_FACTURA));
                        _ReportViewerDetalle.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(ReporteDetalleFactura_SubreportProcessingEventHandler);
                        _ReportViewerDetalle.LocalReport.ReportEmbeddedResource = "LQCE.Transaccion.Reporte.DetalleFactura.rdlc";

                        _ReportViewerDetalle.LocalReport.Render("PDF", deviceInfo, CreateStreamDetalleFactura, out warnings);
                        foreach (Stream stream in m_streams_DetalleFactura)
                            stream.Position = 0;

                        using (SPWeb spWeb = new SPSite(Settings.Default.SP_WEB).OpenWeb())
                        {
                            SPList spList = spWeb.GetList(Settings.Default.SP_LIBRERIA_FACTURAS);
                            string strNombreFactura = DateTime.Now.ToString("yyyyMMddhhmmss") + "_DetalleFactura.pdf";
                            spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + strNombreFactura, m_streams_DetalleFactura[0], propiedadesDetalle, true);
                            spList.Update();
                        }
                    }
                    catch (Exception ex)
                    {
                        // En caso de error, al generar los PDF se eliminan los registros de las facturas
                        _FACTURACION.ACTIVO = false;
                        foreach (var _FACTURA in _FACTURACION.FACTURA)
                        {
                            _FACTURA.ACTIVO = false;
                            foreach (var _FACTURA_DETALLE in _FACTURA.FACTURA_DETALLE)
                            {
                                _FACTURA_DETALLE.ACTIVO = false;
                                context.ApplyPropertyChanges("FACTURA_DETALLE", _FACTURA_DETALLE);
                            }
                            context.ApplyPropertyChanges("FACTURA", _FACTURA);
                        }
                        context.ApplyPropertyChanges("FACTURACION", _FACTURACION);
                        context.SaveChanges();
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                Error = ex.Message;
                throw ex;
            }
        }