public int Add(int NOTA_COBROId, int FACTURAId, int MONTO_PENDIENTE)
        {
            Init();
            try
            {
                 using (LQCEEntities context = new LQCEEntities())
                {
                    RepositorioNOTA_COBRO _repositorioNOTA_COBRO = new RepositorioNOTA_COBRO(context);
                    NOTA_COBRO _objNOTA_COBRO = _repositorioNOTA_COBRO.GetById(NOTA_COBROId);
                    if(Equals(_objNOTA_COBRO,null))
                    {
                        throw new Exception(String.Concat("No se ha encontrado NOTA_COBRO con Id =",NOTA_COBROId.ToString()));
                    }

                    RepositorioFACTURA _repositorioFACTURA = new RepositorioFACTURA(context);
                    FACTURA _objFACTURA = _repositorioFACTURA.GetById(FACTURAId);
                    if(Equals(_objFACTURA,null))
                    {
                        throw new Exception(String.Concat("No se ha encontrado FACTURA con Id =",FACTURAId.ToString()));
                    }

                    NOTA_COBRO_DETALLE _NOTA_COBRO_DETALLE = new NOTA_COBRO_DETALLE();

                    //properties

                    _NOTA_COBRO_DETALLE.MONTO_PENDIENTE = MONTO_PENDIENTE;
                    _NOTA_COBRO_DETALLE.ACTIVO = true;

                    //parents

                    _NOTA_COBRO_DETALLE.NOTA_COBRO = _objNOTA_COBRO;
                    _NOTA_COBRO_DETALLE.FACTURA = _objFACTURA;

                    context.AddObject("NOTA_COBRO_DETALLE",_NOTA_COBRO_DETALLE);
                    context.SaveChanges();

                    return _NOTA_COBRO_DETALLE.ID;
                }
            }
            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;
            }
        }