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;
            }
        }
Пример #2
0
 public List<FACTURA> GetByFilterWithReferences(int? CLIENTEId = null, int? FACTURACIONId = null, int? TIPO_FACTURAId = null, int? CORRELATIVO = null, string RUT_LABORATORIO = "", int? NETO = null, int? IVA = null, int? TOTAL = null, string NOMBRE_CLIENTE = "", string RUT_CLIENTE = "", string DIRECCION = "", string NOMBRE_COMUNA = "", int? NUMERO_FACTURA = null, int? DESCUENTO = null, string FONO = "", string GIRO = "", string DETALLE = "", bool? PAGADA = null)
 {
     Init();
     try
     {
          using (LQCEEntities context = new LQCEEntities())
         {
             RepositorioFACTURA repositorio = new RepositorioFACTURA(context);
             return repositorio.GetByFilterWithReferences(CLIENTEId, FACTURACIONId, TIPO_FACTURAId, CORRELATIVO, RUT_LABORATORIO, NETO, IVA, TOTAL, NOMBRE_CLIENTE, RUT_CLIENTE, DIRECCION, NOMBRE_COMUNA, NUMERO_FACTURA, DESCUENTO, FONO, GIRO, DETALLE, PAGADA).OrderBy(i => i.ID).ToList();
         }
     }
     catch (Exception ex)
     {
          ISException.RegisterExcepcion(ex);
         Error = ex.Message;
         throw ex;
     }
 }
        public void BorrarNumeracionFacturas(int ID_FACTURACION, int ID_TIPO_FACTURA, int CORRELATIVO_DESDE, int CORRELATIVO_HASTA)
        {
            Init();
            //ListaDetalleFactura = new List<DTO_REPORTE_DETALLEFACTURA_PRESTACION>();
            try
            {
                using (LQCEEntities context = new LQCEEntities())
                {
                    if (CORRELATIVO_DESDE > CORRELATIVO_HASTA)
                        throw new Exception("El rango de facturas está mal definido, el valor inicial es mayor al valor final");

                    RepositorioFACTURA _RepositorioFACTURA = new RepositorioFACTURA(context);

                    var q = _RepositorioFACTURA.GetByFilterWithReferences(null, ID_FACTURACION, ID_TIPO_FACTURA,
                        null, "", null, null, null, "", "", "", "", null, null, "", "", "", null);
                    q = q.Where(f => f.CORRELATIVO >= CORRELATIVO_DESDE && f.CORRELATIVO <= CORRELATIVO_HASTA);

                    if (q.Any(f => f.NOTA_COBRO_DETALLE.Any(n => n.ACTIVO)))
                        throw new Exception("Ya existen facturas cobradas al cliente en el rango señalado");

                    if (q.Any(f => f.PAGADA.HasValue && f.PAGADA.Value == true))
                        throw new Exception("Ya existen facturas pagadas en el rango señalado");

                    if (q.Any(f => f.NOTA_CREDITO.Any(nc => nc.ACTIVO)))
                        throw new Exception("Existen facturas con notas de crédito en el rango señalado");

                    foreach (var _FACTURA in q.OrderBy(f => f.CORRELATIVO).ToList())
                    {
                        if (_FACTURA.NUMERO_FACTURA.HasValue)
                        {
                            _FACTURA.NUMERO_FACTURA = null;
                            context.ApplyPropertyChanges("FACTURA", _FACTURA);
                        }
                    }
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                Error = ex.Message;
                throw ex;
            }
        }