private void btnAceptar_Click(object sender, EventArgs e)
        {
            int existeNullCodeQR = 0;
            fecha = "";
            fechafin = "";

            cnx = new SqlConnection(cdn);
            cmd = new SqlCommand();
            cmd.Connection = cnx;
            CalculoNomina.Core.NominaHelper nh = new CalculoNomina.Core.NominaHelper();
            nh.Command = cmd;

            for (int i = 0; i < lstvPeriodos.SelectedItems.Count; i++)
            {
                fecha = lstvPeriodos.SelectedItems[i].Text;
                fechafin = lstvPeriodos.SelectedItems[i].SubItems[1].Text;
            }

            try
            {
                cnx.Open();
                existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date);
                cnx.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show("Error: Al obtener existencia de nulos Code QR. " + error.Message, "Error");
                cnx.Dispose();
                return;
            }

            if (existeNullCodeQR != 0)
            {
                List<CalculoNomina.Core.CodigoBidimensional> lstXml = new List<CalculoNomina.Core.CodigoBidimensional>();
                try
                {
                    cnx.Open();
                    lstXml = nh.obtenerListaQr(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date);
                    cnx.Close();
                }
                catch (Exception error)
                {
                    MessageBox.Show("Error: Al obtener el listado de XMLs." + error.Message, "Error");
                    cnx.Dispose();
                    return;
                }

                string codigoQR = "";
                string[] valores = null;
                string numero = "";
                string vEntero = "";
                string vDecimal = "";

                for (int i = 0; i < lstXml.Count; i++)
                {
                    numero = lstXml[i].tt.ToString();
                    valores = numero.Split('.');
                    vEntero = valores[0];
                    vDecimal = valores[1];
                    codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstXml[i].re, lstXml[i].rr,
                        vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstXml[i].uuid);
                    var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                    var qrCode = qrEncoder.Encode(codigoQR);
                    var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White);

                    using (var stream = new FileStream(lstXml[i].uuid + ".png", FileMode.Create))
                        renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);

                    Bitmap bmp = new Bitmap(lstXml[i].uuid + ".png");
                    Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp);
                    bmp.Dispose();
                    File.Delete(lstXml[i].uuid + ".png");
                    try
                    {
                        cnx.Open();
                        nh.actualizaXml(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date, lstXml[i].idtrabajador, qr);
                        cnx.Close();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error: Al actualizar el código QR.", "Error");
                        cnx.Dispose();
                        return;
                    }
                }
            }

            if (todos)
            {
                for (int i = 0; i < lstvPeriodos.SelectedItems.Count; i++)
                    fecha = lstvPeriodos.SelectedItems[i].Text;
                idEmpleados = "";
                frmVisorReportes vr = new frmVisorReportes();
                vr._tipoNomina = (cmbTipoNomina.SelectedIndex == 0 ? GLOBALES.NORMAL : GLOBALES.EXTRAORDINARIO_NORMAL);
                vr._departamentos = idDepartamentos;
                vr._empleados = idEmpleados;
                vr._todos = todos;
                vr._noReporte = 10;
                vr._inicioPeriodo = DateTime.Parse(fecha).Date;
                vr._periodo = periodo;
                vr.Show();
            }
            else {
                idEmpleados = "";
                for (int i = 0; i < lstvEmpleados.Items.Count; i++)
                {
                    if (lstvEmpleados.Items[i].Checked)
                        idEmpleados += lstvEmpleados.Items[i].Text + ",";
                }

                fecha = "";
                if (idEmpleados != "")
                {
                    for (int i = 0; i < lstvPeriodos.SelectedItems.Count; i++)
                        fecha = lstvPeriodos.SelectedItems[i].Text;
                    idEmpleados = idEmpleados.Substring(0, idEmpleados.Length - 1);
                    frmVisorReportes vr = new frmVisorReportes();
                    vr._tipoNomina = (cmbTipoNomina.SelectedIndex == 0 ? GLOBALES.NORMAL : GLOBALES.EXTRAORDINARIO_NORMAL);
                    vr._departamentos = idDepartamentos;
                    vr._empleados = idEmpleados;
                    vr._todos = todos;
                    vr._noReporte = 10;
                    vr._periodo = periodo;
                    vr._inicioPeriodo = DateTime.Parse(fecha).Date;
                    vr.Show();
                }
            }
        }
        private void workerEnvio_DoWork(object sender, DoWorkEventArgs e)
        {
            int existeNullCodeQR = 0;

            cnx = new SqlConnection(cdn);
            cmd = new SqlCommand();
            cmd.Connection = cnx;

            CalculoNomina.Core.NominaHelper nh = new CalculoNomina.Core.NominaHelper();
            nh.Command = cmd;

            workerEnvio.ReportProgress(0, "Generando códigos QR.");

            try
            {
                cnx.Open();
                existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date);
                cnx.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show("Error: Al obtener existencia de nulos Code QR." + error.Message, "Error");
                cnx.Dispose();
                return;
            }

            if (existeNullCodeQR != 0)
            {
                List<CalculoNomina.Core.CodigoBidimensional> lstQR = new List<CalculoNomina.Core.CodigoBidimensional>();
                try
                {
                    cnx.Open();
                    lstQR = nh.obtenerListaQr(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date);
                    cnx.Close();
                }
                catch (Exception error)
                {
                    MessageBox.Show("Error: Al obtener el listado de los XML." + error.Message, "Error");
                    cnx.Dispose();
                    return;
                }

                string codigoQR = "";
                string[] valores = null;
                string numero = "";
                string vEntero = "";
                string vDecimal = "";

                for (int i = 0; i < lstQR.Count; i++)
                {
                    numero = lstQR[i].tt.ToString();
                    valores = numero.Split('.');
                    vEntero = valores[0];
                    vDecimal = valores[1];
                    codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstQR[i].re, lstQR[i].rr,
                        vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstQR[i].uuid);
                    var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                    var qrCode = qrEncoder.Encode(codigoQR);
                    var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White);

                    using (var stream = new FileStream(lstQR[i].uuid + ".png", FileMode.Create))
                        renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);

                    Bitmap bmp = new Bitmap(lstQR[i].uuid + ".png");
                    Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp);
                    bmp.Dispose();
                    File.Delete(lstQR[i].uuid + ".png");
                    try
                    {
                        cnx.Open();
                        nh.actualizaXml(GLOBALES.IDEMPRESA, DateTime.Parse(fecha).Date, DateTime.Parse(fechafin).Date, lstQR[i].idtrabajador, qr);
                        cnx.Close();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error: Al actualizar el código QR.", "Error");
                        cnx.Dispose();
                        return;
                    }
                }
            }

            int existeRecibo = 0;
            if (fecha != "")
            {
                for (int i = 0; i < dgvEmpleados.Rows.Count; i++)
                {

                    try
                    {
                        cnx.Open();
                        existeRecibo = (int)nh.existeXMLTrabajador(GLOBALES.IDEMPRESA, int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()),
                            DateTime.Parse(fecha).Date);
                        cnx.Close();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error: Al obtener existencia del XML", "Error");
                        cnx.Dispose();
                        return;
                    }

                    if (existeRecibo != 0)
                    {
                        dsReportes.NominaRecibosDataTable dtImpresionNomina = new dsReportes.NominaRecibosDataTable();
                        SqlDataAdapter daImpresionNomina = new SqlDataAdapter();
                        cmd.CommandText = "exec stp_rptNominaImpresionTrabajador @idempresa, @fechainicio, @tiponomina, @idtrabajador, @periodo";
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("idempresa", GLOBALES.IDEMPRESA);
                        cmd.Parameters.AddWithValue("fechainicio", DateTime.Parse(fecha).Date);
                        cmd.Parameters.AddWithValue("tiponomina", tipoNomina);
                        cmd.Parameters.AddWithValue("idtrabajador", int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()));
                        cmd.Parameters.AddWithValue("periodo", periodo);
                        cmd.CommandTimeout = 300;
                        daImpresionNomina.SelectCommand = cmd;
                        daImpresionNomina.Fill(dtImpresionNomina);

                        ReportDataSource rd = new ReportDataSource();
                        rd.Value = dtImpresionNomina;
                        rd.Name = "dsNominaRecibo";

                        Visor.LocalReport.DataSources.Clear();
                        Visor.LocalReport.DataSources.Add(rd);

                        Visor.LocalReport.ReportEmbeddedResource = "rptNominaRecibos.rdlc";
                        Visor.LocalReport.ReportPath = @"rptNominaRecibos.rdlc";

                        Warning[] warnings;
                        string[] streamids;
                        string mimeType;
                        string encoding;
                        string extension;

                        byte[] bytes = Visor.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);

                        if (!Directory.Exists(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString()))
                            Directory.CreateDirectory(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString());

                        using (FileStream fs = new FileStream(string.Format(@"{0}\{1}.{2}",
                            ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString(),
                            dgvEmpleados.Rows[i].Cells["nombrecompleto"].Value.ToString() + "_" + DateTime.Parse(fecha).ToString("yyyyMMdd"),
                            "pdf"), FileMode.Create))
                        {
                            fs.Write(bytes, 0, bytes.Length);
                            fs.Flush();
                            fs.Close();
                            fs.Dispose();
                        }

                        List<CalculoNomina.Core.XmlCabecera> lstXml = new List<CalculoNomina.Core.XmlCabecera>();
                        try
                        {
                            cnx.Open();
                            lstXml = nh.obtenerXmlTrabajador(GLOBALES.IDEMPRESA, int.Parse(dgvEmpleados.Rows[i].Cells["idtrabajador"].Value.ToString()),
                                DateTime.Parse(fecha).Date);
                            cnx.Close();
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Error: Al obtener el XML del Trabajador", "Error");
                            cnx.Dispose();
                            return;
                        }

                        using (StreamWriter sw = new StreamWriter(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString() + "\\" + dgvEmpleados.Rows[i].Cells["nombrecompleto"].Value.ToString() + "_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + ".xml"))
                        {
                            sw.WriteLine(lstXml[0].xml);
                        }
                        workerEnvio.ReportProgress(i, "Recibo generado.");
                    }
                    else
                    {
                        workerEnvio.ReportProgress(i, "Recibo no existe.");
                    }
                }

                try
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        if (File.Exists(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip"))
                            File.Delete(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip");
                        zip.AddDirectory(ruta + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA.ToString() + "\\");
                        zip.Save(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip");
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error: Al crear el archivo comprimido.", "Error");
                }

                MailMessage email = new MailMessage();
                SmtpClient smtp = new SmtpClient();
                Attachment comprimido = new Attachment(ruta + "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd") + "_" + GLOBALES.IDEMPRESA + ".zip");
                email.IsBodyHtml = true;
                email.From = new MailAddress(correoEnvio, "Recibos electrónicos de nómina");
                email.To.Add(txtCorreoElectronico.Text);
                email.Subject = "RecibosNomina_" + DateTime.Parse(fecha).ToString("yyyyMMdd");
                email.Body = "Correo automatico enviado por el sistema de administración de nómina. \r\n \r\n No responder.";
                email.Priority = MailPriority.Normal;
                email.Attachments.Add(comprimido);
                smtp.Host = servidorEnvio;
                smtp.Port = puertoEnvio;
                smtp.EnableSsl = usaSSL;

                smtp.Credentials = new NetworkCredential(correoEnvio, passwordEnvio);
                try
                {
                    workerEnvio.ReportProgress(0, "Enviando recibos de nómina");
                    smtp.Send(email);
                    smtp.Dispose();
                    comprimido.Dispose();
                }
                catch (Exception msg)
                {
                    MessageBox.Show("Error al enviar el correo: " + msg.Message, "Error");
                }
            }
        }
Beispiel #3
0
        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (!_ReportePreNomina)
            {
                if (noReporte != 6 && noReporte != 9)
                {
                    if (noReporte == 8)
                    {
                        int existeNullCodeQR = 0;
                        cnx = new SqlConnection(cdn);
                        cmd = new SqlCommand();
                        cmd.Connection = cnx;
                        nh = new CalculoNomina.Core.NominaHelper();
                        nh.Command = cmd;

                        #region EXISTENCIA DE NULOS EN TABLA xmlCabecera
                        try
                        {
                            cnx.Open();
                            existeNullCodeQR = nh.existeNullQR(GLOBALES.IDEMPRESA, dtpInicioPeriodo.Value.Date, dtpFinPeriodo.Value.Date);
                            cnx.Close();
                        }
                        catch (Exception error)
                        {
                            MessageBox.Show("Error: Al obtener existencia de nulos Code QR." + error.Message, "Error");
                            cnx.Dispose();
                            return;
                        }
                        #endregion

                        #region GENERACION DE CODIGO QR SI EXISTEN NULOS
                        if (existeNullCodeQR != 0)
                        {
                            List<CalculoNomina.Core.CodigoBidimensional> lstXml = new List<CalculoNomina.Core.CodigoBidimensional>();
                            try
                            {
                                cnx.Open();
                                lstXml = nh.obtenerListaQr(GLOBALES.IDEMPRESA, dtpInicioPeriodo.Value.Date, dtpFinPeriodo.Value.Date);
                                cnx.Close();
                            }
                            catch (Exception error)
                            {
                                MessageBox.Show("Error: Al obtener el listado de los XML." + error.Message, "Error");
                                cnx.Dispose();
                                return;
                            }

                            string codigoQR = "";
                            string[] valores = null;
                            string numero = "";
                            string vEntero = "";
                            string vDecimal = "";
                            for (int i = 0; i < lstXml.Count; i++)
                            {
                                numero = lstXml[i].tt.ToString();
                                valores = numero.Split('.');
                                vEntero = valores[0];
                                vDecimal = valores[1];
                                codigoQR = string.Format("?re={0}&rr={1}&tt={2}.{3}&id={4}", lstXml[i].re, lstXml[i].rr,
                                    vEntero.PadLeft(10, '0'), vDecimal.PadRight(6, '0'), lstXml[i].uuid);
                                var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                                var qrCode = qrEncoder.Encode(codigoQR);
                                var renderer = new GraphicsRenderer(new FixedModuleSize(2, QuietZoneModules.Two), Brushes.Black, Brushes.White);

                                using (var stream = new FileStream(lstXml[i].uuid + ".png", FileMode.Create))
                                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);

                                Bitmap bmp = new Bitmap(lstXml[i].uuid + ".png");
                                Byte[] qr = GLOBALES.IMAGEN_BYTES(bmp);
                                bmp.Dispose();
                                File.Delete(lstXml[i].uuid + ".png");
                                try
                                {
                                    cnx.Open();
                                    nh.actualizaXml(GLOBALES.IDEMPRESA, dtpInicioPeriodo.Value.Date, dtpFinPeriodo.Value.Date, lstXml[i].idtrabajador, qr);
                                    cnx.Close();
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("Error: Al actualizar el código QR.", "Error");
                                    cnx.Dispose();
                                    return;
                                }
                            }
                        }
                        #endregion
                    }

                    frmVisorReportes vr = new frmVisorReportes();
                    vr._inicioPeriodo = dtpInicioPeriodo.Value;
                    vr._finPeriodo = dtpFinPeriodo.Value;
                    if (_ReportePreNomina)
                        vr._tipoNomina = _tipoNomina;
                    else
                        vr._tipoNomina = tipoNomina;
                    vr._noReporte = noReporte;
                    vr._deptoInicio = int.Parse(cmbDeptoInicial.SelectedValue.ToString());
                    vr._deptoFin = int.Parse(cmbDeptoFinal.SelectedValue.ToString());
                    vr._empleadoInicio = int.Parse(cmbEmpleadoInicial.SelectedValue.ToString());
                    vr._empleadoFin = int.Parse(cmbEmpleadoFinal.SelectedValue.ToString());
                    vr._netoCero = netocero;
                    vr._orden = orden;
                    vr._periodo = periodo;
                    vr.Show();
                }
                else
                {
                    if (noReporte == 6)
                        excelTabular();
                    if (noReporte == 9)
                        excelGravadosExentos();
                }
            }
            else
            {
                int empleadoInicial = 0, empleadoFinal = 0;
                if (_noReporte == 9 || _noReporte == 1)
                {
                    empleadoInicial = int.Parse(cmbEmpleadoInicial.SelectedValue.ToString());
                    empleadoFinal = int.Parse(cmbEmpleadoFinal.SelectedValue.ToString());
                }
                if (OnReporte != null)
                    OnReporte(netocero, orden, _noReporte, empleadoInicial, empleadoFinal);
            }
        }