using CoreLibrary.Extenders.StringManipulation; using ECV; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.pdf.codec.wmf; using Microsoft.SqlServer.Server; //using Font = iTextSharp.text.Font; using Microsoft.VisualBasic; using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SQLite; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Printing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; using static System.Net.Mime.MediaTypeNames; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; using Font = System.Drawing.Font; using Image = System.Drawing.Image; using TextBox = System.Windows.Forms.TextBox; namespace CKUERA { public partial class Ventas : Form { public Ventas() { InitializeComponent(); this.KeyDown += new KeyEventHandler(Ventas_KeyDown); this.KeyPreview = true; } public static int CliRegistrado = 1; public static int VieneDeRUC = 0; public static double valorMoneda2 = 0; public static double valorMoneda3 = 0; public static double valorMoneda4 = 0; public static string operacion2 = ""; public static string operacion3 = ""; public static string operacion4 = ""; public static string simboloMoneda2 = ""; public static string simboloMoneda3 = ""; public static string simboloMoneda4 = ""; public static string faltante1 = ""; public static string faltante2 = ""; public static string faltante3 = ""; public static string faltante4 = ""; public static double faltanteVal1; public static double faltanteVal2; public static double faltanteVal3; public static double faltanteVal4; public static double entregaVal; private void Ventas_Resize(object sender, EventArgs e) { Lab_Cabecera.Width = this.Width; Lab_Cabecera.Top = 0; Lab_Cabecera.Left = 0; Lab_Cabecera.Height = 32; if (WindowState == (FormWindowState)1) { WindowState = (FormWindowState)0; } Principal fp = new Principal(); this.Top = fp.Top+ 32; this.Left = 242; //Label6.Top = 144; //Label6.Left = 9; //Label6.Height = this.Height - (Label6.Top+48); Entrega_text.Top = this.Height - (Entrega_text.Height+54); Entrega_titulo_label.Top = Entrega_text.Top - Entrega_titulo_label.Height; Vuelto_label.Top = this.Height - (Entrega_text.Height + 54); VUELTO_TITULO_label.Top = Entrega_text.Top - Entrega_titulo_label.Height; TOTAL_label.Top = this.Height - (Entrega_text.Height + 54); Total_titulo_label.Top = Entrega_text.Top - Entrega_titulo_label.Height; Total_titulo_label.Text = "Total " + Global.SIMB_; Entrega_titulo_label.Text = "Entrega " + Global.SIMB_; VUELTO_TITULO_label.Text = "Vuelto " + Global.SIMB_; DataG1.Left = 7; DataG1.Top =144; DataG1.Height = Entrega_titulo_label.Top - DataG1.Top-6; //Label6.Height - 70; DataG1.Width = 534; pictureBox1.Top = Total_titulo_label.Top - (pictureBox1.Height - (Total_titulo_label.Height+32)); DataG3.Top = RAZON_TBox.Top + RAZON_TBox.Height + 1; //DataG3.Top;//LISTA DE CLIENTES DataG3.Left = RAZON_TBox.Left;//LISTA DE CLIENTES en_linea.Top = 43; en_linea.Left = 936; en_linea.Height = label15.Top-50;//en_linea.Height = TOTAL_label.Top - 4; en_linea.Width = this.Width - (en_linea.Left + 8); en_linea.BackColor = DataG2.BackgroundColor; en_linea.ForeColor = this.BackColor; en_linea.BorderStyle = BorderStyle.Fixed3D; label10.Width = en_linea.Width - 2; label10.Top = en_linea.Top + 1; label10.Left = en_linea.Left+1; DataG2.Top = DataG1.Top + 20; DataG2.Width = DataG2.Width + en_linea.Width+7; DataG2.Height = pictureBox1.Top - (DataG2.Top); label15.Width = label15.Width + en_linea.Width +3; pictureBox1.Width = DataG2.Width; Ayuda_text.Top = DataG1.Top+41; Ayuda_text.Left = DataG1.Left+20; Ayuda_text.Height = DataG1.Height-60; Ayuda_text.Width = DataG1.Width-40; Ayuda_text.ForeColor = Global.ColorSistema; Cerrar.Left = this.Width - (Cerrar.Width+5); panel_VueltoTotal.Left = VUELTO_TITULO_label.Left-2; panel_VueltoTotal.Top = VUELTO_TITULO_label.Top - panel_VueltoTotal.Height-4; chec_vuelto2.Top = lab_vuelto2.Top+2; chec_vuelto2.Left = lab_vuelto2.Left+1; chec_vuelto3.Top = lab_vuelto3.Top + 2; chec_vuelto3.Left = lab_vuelto3.Left + 1; chec_vuelto4.Top = lab_vuelto4.Top + 2; chec_vuelto4.Left = lab_vuelto4.Left + 1; chec_vuelto1.Top = VUELTO_TITULO_label.Top + 2; chec_vuelto1.Left = VUELTO_TITULO_label.Left + 1; } private void Ventas_Load(object sender, EventArgs e) { try { Bitmap bitmap = new Bitmap("FONDO.png"); this.BackgroundImage = bitmap; } catch { } Principal principal = new Principal(); principal.VBETA(); //this.Top = 32; this.BackColor = Global.ColorSistema; Entrega_titulo_label.BackColor = this.BackColor; Entrega_text.BackColor = this.BackColor; Vuelto_label.BackColor = this.BackColor; VUELTO_TITULO_label.BackColor = this.BackColor; TOTAL_label.BackColor = this.BackColor; Total_titulo_label.BackColor = this.BackColor; DataG1.ColumnHeadersDefaultCellStyle.BackColor = this.BackColor; DataG2.ColumnHeadersDefaultCellStyle.BackColor = this.BackColor; DataG1.DefaultCellStyle.SelectionBackColor = Global.ColorSistema; DataG2.DefaultCellStyle.SelectionBackColor = Global.ColorSistema; DataG3.DefaultCellStyle.SelectionBackColor = Global.ColorSistema; label15.BackColor= Global.ColorFuente; label15.ForeColor= Global.ColorSistema; Opt_Precio1.BackColor = Global.ColorFuente; Opt_Precio1.ForeColor = Global.ColorSistema; Opt_Precio2.BackColor = Global.ColorFuente; Opt_Precio2.ForeColor = Global.ColorSistema; Opt_Precio3.BackColor = Global.ColorFuente; Opt_Precio3.ForeColor = Global.ColorSistema; Boton1.BackColor = this.BackColor; Boton2.BackColor = this.BackColor; Boton3.BackColor = this.BackColor; Boton4.BackColor = this.BackColor; Boton4.BackColor = this.BackColor; Btn_Devolucion.BackColor = this.BackColor; label13.BackColor = this.BackColor; en_linea.ForeColor = this.BackColor; TextBox1.BackColor = this.BackColor; TextBox1.ForeColor = Global.ColorFuente; TextBox2.BackColor = this.BackColor; TextBox2.ForeColor = Global.ColorFuente; TextBox3.BackColor = this.BackColor; TextBox3.ForeColor = Global.ColorFuente; TextBox4.BackColor = this.BackColor; TextBox4.ForeColor = Global.ColorFuente; RAZON_TBox.BackColor = this.BackColor; RAZON_TBox.ForeColor = Global.ColorFuente; RUC_TBox.BackColor = this.BackColor; RUC_TBox.ForeColor = Global.ColorFuente; checMon2.Text = Global.simboloMoneda2; checMon3.Text = Global.simboloMoneda3; checMon4.Text = Global.simboloMoneda4; en_linea.Top=43; en_linea.Left=936; panel1.BackColor = en_linea.BackColor; Presu_Conf presu_Conf = new Presu_Conf(); presu_Conf.Presu_Conf_Load(null, null); if (Global.CerrarVenta == true)//Esta órden se da en óptica, se pone FALSE para NO reportar { Cierre_Pendiente();//CONSULTA SI HAY CIERRE DE VENTA PENDIENTE } Global.CerrarVenta = true;//Se devuelve true en caso que se haya puesto en FALSE MostrarGridVenta(); Espera_lab.Text = ""; cuenta_espera(); TextBox1.Select(); Global.Venta_Hab = 1; //Moneda_ecuperar();//Muestra denominación de las monedas lab_vuelto2.Text = "Vuelto " + Global.simboloMoneda2; lab_vuelto3.Text = "Vuelto " + Global.simboloMoneda3; lab_vuelto4.Text = "Vuelto " + Global.simboloMoneda4; lab_total2.Text = "Total " + Global.simboloMoneda2; lab_total3.Text = "Total " + Global.simboloMoneda3; lab_total4.Text = "Total " + Global.simboloMoneda4; Lab_deno1.Text = Global.denominacion1; Lab_deno2.Text = Global.denominacion2; Lab_deno3.Text = Global.denominacion3; Lab_deno4.Text = Global.denominacion4; valorMoneda2= Global.valorMoneda2; valorMoneda3= Global.valorMoneda3; valorMoneda4= Global.valorMoneda4; operacion2= Global.operacion2; operacion3= Global.operacion3; operacion4= Global.operacion4; if (Global.US_MODIFICA_PRECIO == 0) { TextBox3.ReadOnly=true; }//PERMISO DE MODIFICAR PRECIO (0=NO) { string name = "iconos\\cerrar_venta.png"; try { Boton1.Image = System.Drawing.Image.FromFile(name); } catch (Exception) { } } { string name = "iconos\\quitar_de_la_lista.png"; try { Boton2.Image = System.Drawing.Image.FromFile(name); } catch (Exception) { } } { string name = "iconos\\cancelar.png"; try { Boton3.Image = System.Drawing.Image.FromFile(name); } catch (Exception) { } } { string name = "iconos\\espera.png"; try { Boton4.Image = System.Drawing.Image.FromFile(name); } catch (Exception) { } } { string name = "iconos\\devolver.png"; try { Btn_Devolucion.Image = System.Drawing.Image.FromFile(name); } catch (Exception) { } } { string name = "imagen.png"; try { pictureBox1.ErrorImage = System.Drawing.Image.FromFile(name); } catch (Exception) { } } { string name = "imagen.png"; try { pictureBox1.InitialImage = System.Drawing.Image.FromFile(name); } catch (Exception) { } } //MOSTRAR RUTA de IMAGENES try { SQLiteDataReader RS1 = null; string SQL1 = "SELECT ruta_img FROM config" + Global.NUM_caja + " LIMIT 1;"; SQLiteCommand SECC = new SQLiteCommand(SQL1, Global.conexion); RS1 = SECC.ExecuteReader(); if (RS1.HasRows == true) { while (RS1.Read()) { Global.ruta_img = RS1.GetString(0); } } } catch { MessageBox.Show("La Ruta de Imagenes es incorrecta. \nVerifique la Configuración." + Global.ruta_img); } CargarVendedores(); timer2.Start(); if (int.Parse(Global.version) > 1) //si es versión 2 o más { //panelPrecios.Enabled = true; //Precios 2 y 3 checMon2.Enabled = true; checMon3.Enabled = true; checMon4.Enabled = true; } TOTAL_label_TextChanged(null, null); } private void Cierre_Pendiente() { string Usuario = Global.USUARIO_SIST; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/consultar_cierre.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼", Usuario)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } if (devuelve.Length > 0) { { //if (double.Parse(c[0]) > 0 || double.Parse(c[0]) < 0) { Cierre fc = new Cierre(); fc.ShowDialog(); } } } } public void Devolver_color_Bot() { Boton1.BackColor = this.BackColor;// Color.FromArgb(43, 146, 230); Boton2.BackColor = this.BackColor;// Color.FromArgb(43, 146, 230); Boton3.BackColor = this.BackColor;// Color.FromArgb(43, 146, 230); Boton4.BackColor = this.BackColor;// Color.FromArgb(43, 146, 230); Btn_Devolucion.BackColor = this.BackColor;// Color.FromArgb(43, 146, 230); } private void Boton1_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); Boton1.BackColor = Global.ColorMouseMuve; Ayuda_text.Text = "\"Fin o Esc\" \nEl botón \"Fin\" es cuando se desea ir cerrando la venta. También responde con la tecla \"Esc\". \nRecomendamos siempre usar el teclado para una operación más ágil."; } private void Ventas_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); if (m == 1) { this.SetDesktopLocation(MousePosition.X - mx, MousePosition.Y - my); } } private void Label6_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void CheckBox1_MouseMove(object sender, MouseEventArgs e)//FACTURAR { Devolver_color_Bot(); Ayuda_text.Text = "\"Factura / Ticket\" \nAl marcar esta casilla el sistema se perapara a confeccionar una Factura en PDF. Si no está marcada, el sistema intentará imprimir un ticket de hoja continua de 7.5 cm de ancho. También responde con las teclas combinadas \"Alt+F\". \nRecomendamos siempre usar el teclado para una operación más ágil.\n\nLo primero es cargar la lista que se desee facturar, luego al hacer clic en \"Fin\" o al presionar \"Esc\" de su teclado, el cursor del mouse enfocará en los campos Cliente y RUC respectivamente, si todavía están vacíos, deberá llenar y al hacer clic de nuevo en \"Fin\" o \"Esc\" de su teclado, la lista que tenga en pantalla se convertirá en una página PDF que usted podrá imprimir. La hoja a utilizar para la impresión es de tamaño A4."; } private void CheckBox2_MouseMove(object sender, MouseEventArgs e)//CRÉDITO { Devolver_color_Bot(); Ayuda_text.Text = "\"Crédito\" \nAl marcar esta casilla el sistema se perapara a cerrar la venta, pero a Crédito.\n\nPara comenzar a usar esta función es necesario registrar el Cliente a quien vender a Crédito. Si no está marcada, el sistema venderá al Contado. También responde con las teclas combinadas \"Alt+C\". \nRecomendamos siempre usar el teclado para una operación más ágil.\n\nLo primero es cargar la lista que se desee facturar, luego al hacer clic en \"Fin\" o al presionar \"Esc\" de su teclado, el cursor del mouse enfocará en los campos Cliente y RUC respectivamente, si todavía están vacíos, deberá llenar y al hacer clic de nuevo en \"Fin\" o \"Esc\" de su teclado, la lista que tenga en pantalla se convertirá en una página PDF que usted podrá imprimir. La hoja a utilizar para la impresión es de tamaño A4."; } private void TextBox1_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void TextBox4_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void TextBox2_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void TextBox5_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void TextBox3_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void TextBox6_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void Label2_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); } private void Boton2_Click(object sender, EventArgs e)//QUITAR { if (Entrega_text.Enabled == false) { MessageBox.Show("Hay una venta en proceso, cierrela primero."); return; } if (ID_LABEL.Text == "") { MessageBox.Show("Seleccione un artículo y vuelva a intentar.", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Principal fp = new Principal(); string ID = ID_LABEL.Text; string Usuario = Global.USUARIO_SIST; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/quitar_temporal.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}", ID, Usuario)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } MostrarGridVenta(); Sumar(); ID_LABEL.Text = ""; } private void CambiarPrecioTemp() { Principal fp = new Principal(); string ID = ID_LABEL.Text; string Usuario = Global.USUARIO_SIST; double Precio = double.Parse(TextBox1.Text); if (Precio == 0)//PRECIO CERO { MessageBox.Show("Este artículo no puede tener ''Precio Cero''.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/cambiar_precio.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}", ID, Usuario,Precio)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } if(devuelve.Trim()== "Cambiado ok") { MostrarGridVenta(); Sumar(); ID_LABEL.Text = ""; TextBox1.Text = ""; } } public void Boton3_Click(object sender, EventArgs e) { if (Entrega_text.Enabled == false) { MessageBox.Show("Hay una venta en proceso, cierrela primero."); return; } cancelar();//CANCELAR } public void Cancelar() { try { string Usuario = Global.USUARIO_SIST; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/cancelar_venta.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", Usuario)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } MostrarGridVenta(); items_Label.Text = ""; } catch { MessageBox.Show("No hay respuesta del Servidor.", "Uff... Lo sentimos", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Boton2_MouseMove(object sender, MouseEventArgs e)//QUITAR { Devolver_color_Bot(); Boton2.BackColor = Global.ColorMouseMuve; Ayuda_text.Text = "\"Quitar\" \nEste botón extrae un item de la lista que está a punto de facturar o presupuestar. Tabién funciona con las teclas combinadas \"Alt + Q\". \nRecomendamos siempre usar el teclado para una operación más ágil."; } private void Boton3_MouseMove(object sender, MouseEventArgs e)//CANCELAR { Devolver_color_Bot(); Boton3.BackColor = Global.ColorMouseMuve; Ayuda_text.Text = "\"Cancelar\" \nEste botón borra toda la lista cargada. También responde con las teclas combinadas \"Alt + L\". \nRecomendamos siempre usar el teclado para una operación más ágil."; } private void Boton4_MouseMove(object sender, MouseEventArgs e)//ESPERA { Devolver_color_Bot(); Boton4.BackColor = Global.ColorMouseMuve; Ayuda_text.Text = "\"Espera\" \nEste botón envía a espera una lista que está a punto de facturar o presupuestar. También responde con las teclas combinadas \"Alt+E\". \nRecomendamos siempre usar el teclado para una operación más ágil.\n\nASÍ FUNCIONA; Ejemplo: Una lista cargada no puede facturarse porque el cliente se olvidó del dinero o tarjeta para pagar, se irá a traer, pero hay una cola de clientes que desean ser atendidos;\n1- Hacer clic en \"Espera\" o \"Alt+E\"\n2- Escriba en el campo Cliente un nombre cualquiera Ej.: \"Pedro\"\n3- Otra vez clic en \"Espera\" o \"Alt+E\" y la lista ya fue a Espera.\n\nCÓMO RECUPERAR ESPERA:\n1- Hacer clic en \"Espera\" o \"Alt+E\"\n2- Escriba en el campo Cliente las iniciales del nombre de un cliente Espera Ej.: \"Ped\", aparecerá una lista de clientes en espera con esas iniciales.\n3- Seleccione uno con un clic.\n4- Otra vez clic en \"Espera\" o \"Alt+E\" y la lista ya se recupera."; } private void Ventas_Activated(object sender, EventArgs e) { //this.Top = 32; Principal fp = new Principal(); this.Width = 1098; this.Top = fp.Top + 32; this.Left = 252; this.Width = 1099; checPresu.Checked = Global.Presupuestar; checFacturar.Checked = Global.Facturar; checCred_o_Cont.Checked = Global.FCredito; checCon_pag.Checked = Global.CPagare; MostrarGridVenta(); } public void Limpiar() { //VACÍA LOS CONTROLES TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; Entrega_text.Text = ""; Vuelto_label.Text = ""; TOTAL_label.Text = "0"; ID_LABEL.Text = ""; checPresu.Checked = false; Global.Condicion = ""; Global.VCredito = false; Global.RazonS = ""; Global.RUC = ""; Global.Tel_Cliente = ""; Global.ID_cliente = 0; Global.SALDO_CLI = 0; Global.Con_Pagare = false; Global.COND = ""; Global.DIRECCION_F = ""; Global.no_imp_ticket = 0; Global.Presupuestar=false; Global.Facturar=false; Global.FCredito=false; Global.CPagare=false; Global.Objeto = ""; Global.SeccEscri = ""; Global.NumEscri = ""; Global.Protocolo = ""; Global.Contri = ""; Global.Vendedor = ""; Global.ID_vendedor = 0; Global.RegistrarLV = 0; Global.NUM_FACT = ""; Global.viene_de = 0; panelVendedores.Enabled = false; combo_Vendedor.Text = ""; TextBox1.Enabled = true; TextBox2.Enabled = true; TextBox3.Enabled = true; TextBox4.Enabled = true; VieneDeRUC = 0; chec_vuelto4.Checked = false; chec_vuelto3.Checked = false; chec_vuelto2.Checked = false; chec_vuelto1.Checked = false; cuenta_en_linea(); labelFACTURAR.Visible = false; checFacturar.BackColor = Global.ColorSistema; timer1.Enabled = false; timer1.Stop(); Opt_Precio1.Text = "<&1: "; Opt_Precio2.Text = "<&2: "; Opt_Precio3.Text = "<&3: "; } //BOTÓN LISTAR private void Listar_Click(object sender, EventArgs e)//BOTÓN ENTER { if (panel_VueltoTotal.Visible == true) { return; } try//CAMBIAR PRECIO EN TEMPORAL { double d = double.Parse(TextBox1.Text); if (ID_LABEL.Text.Trim() != "") { CambiarPrecioTemp(); } } catch { } cuenta_en_linea(); string s = ""; if (TextBox1.Text.Length < 7 & TextBox1.Text.Length > 0) { if (TextBox1.Text.Substring(0, 1) == "-") { s = "-"; TextBox1.Text = TextBox1.Text.Substring(1,TextBox1.Text.Length-1); } while (!(TextBox1.Text.Length == 7)) { TextBox1.Text = "0" + TextBox1.Text; } if (s == "-") { TextBox1.Text = "-" + TextBox1.Text; } } if (DataG3.Visible == true)// CARGAR RUC Y OTROS DATOS CON ENTER { string razon = DataG3.CurrentRow.Cells[0].Value.ToString();//RAZÓN SOCIAL string ruc = DataG3.CurrentRow.Cells[1].Value.ToString();//RUC string id_cli = DataG3.CurrentRow.Cells[4].Value.ToString();//ID DEL CLIENTE string cel_deu = DataG3.CurrentRow.Cells[3].Value.ToString();//TELEFONO DEL CLIENTE if (Global.venta_enLinea == 0)//SI NO ES VENTA EN LÍENA { RAZON_TBox.Text = razon;//RAZÓN SOCIAL RUC_TBox.Text = ruc;//RUC ID_CLIENTE_LB.Text = id_cli;//ID DEL CLIENTE Global.Cel_DeuP = cel_deu;//TELEFONO DEL CLIENTE DataG3.Visible = false; TextBox1.Select();//ENFOCA EN CÓDIGO if (Global.espera == 1)//SI ES ESPERA { RAZON_TBox.Text = DataG3.CurrentRow.Cells[0].Value.ToString();//RAZÓN SOCIAL RUC_TBox.Text = DataG3.CurrentRow.Cells[1].Value.ToString();//RUC DataG3.Visible = false; TextBox1.Select();//ENFOCA EN CÓDIGO button3_Click(sender, e);//ESPERA } } else//SI ES VENTA EN LÍNEA { RAZON_TBox.Text = DataG3.CurrentRow.Cells[0].Value.ToString();//RAZÓN SOCIAL RUC_TBox.Text = DataG3.CurrentRow.Cells[1].Value.ToString();//RUC Global.Num_Pedido = DataG3.CurrentRow.Cells[2].Value.ToString();//NÚMERO DE PEDIDO DataG3.Visible = false; TextBox1.Select();//ENFOCA EN CÓDIGO Venta_lineaClick(); } } if (TextBox1.Text.Length == 13)//SI ES DE BALANZA 2000032115202 { //BALANZA PESABLE if (TextBox1.Text.Substring(0, 2) == Global.Balanza_K)//SI LAS INICIALES SON CORRECTAS { if (int.Parse(TextBox1.Text.Substring(7, 2)) < 30)//SI EL PESO ES MENOS DE 30 { float cant = float.Parse(TextBox1.Text.Substring(7, 5)) / 1000; TextBox4.Text = string.Format("{0:0.###}", cant); TextBox1.Text = TextBox1.Text.Substring(0, 7); } } //BALANZA POR UNIDAD 2400032000022 if (TextBox1.Text.Substring(0, 2) == Global.Balanza_U)//SI LAS INICIALES SON CORRECTAS { if (int.Parse(TextBox1.Text.Substring(7, 2)) < 2)//SI LA CANTIDAD ES MENOS DE 2000 { int cant = int.Parse(TextBox1.Text.Substring(7, 5)); TextBox4.Text = string.Format("{0:0.###}", cant); TextBox1.Text = TextBox1.Text.Substring(0, 7); } } } if (TextBox1.Text == "")//SI CÓDIGO ESTÁ VACÍO { TextBox1.Select();//ENFOCA Y SE DETIENE EN... return; } //SI ES POR PRECIO if (TextBox1.Text.Substring(TextBox1.Text.Length - 1, 1) == ",") { TextBox3.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1);//PRECIO TextBox2.Select(); if (TextBox1.Text.Substring(0,1) == "-") { if (TextBox2.Text.Length < 1)//SI ESTÁ VACÍO { TextBox2.Text = "DESCUENTO"; TextBox2.SelectAll(); return; } } if (TextBox2.Text.Length < 1)//SI NO SE PONE UN NOMBRE NO PASA { TextBox2.Select(); return; } if (TextBox3.Text.Length < 1)//SI NO HAY UN PRECIO NO PASA { TextBox3.Select(); return; } //SI CANTIDAD ES VACÍO... if (TextBox4.Text == "" | TextBox4.Text == "0") { TextBox4.Text = "1"; } //VENDE POR PRECIO SI ESTÁ ACTIVO if (Global.US_VEN_X_PRECIO == 1) { Vende_por_precio(); } else { MessageBox.Show("No tiene permiso para vender por precio.","ATENCIÓN",MessageBoxButtons.OK, MessageBoxIcon.Information); TextBox1.Text = ""; TextBox1.Select(); } return; } //CONSULTA PRODUCTOS //string Codigo = TextBox1.Text; string devuelve = ""; //if (ID_LABEL.Text == "")//SI ES QUE YA NO CARGÓ { this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/consultar_prod_x_cod.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", TextBox1.Text)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); this.Cursor = Cursors.Default; string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("ERROR"); if (re == true) { MessageBox.Show(devuelve); return; } if (devuelve != "") { Global.si = devuelve; } else { MessageBox.Show(TextBox1.Text + " No está registrado.","NO REGISTRADO",MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } //LLENA LOS (DATOS A CARGAR) EN TEMPORAL { string[] c = Global.si.Split('▲'); ID_LABEL.Text = c[0];//ID TextBox2.Text = c[1];//DESCRIPCION TextBox1.Text = c[2];//CODIGO double COMPRAX = double.Parse(c[3].ToString()); string RECX = c[4].ToString(); if (double.Parse(c[5].ToString())<=0)//PRECIO CERO { MessageBox.Show("Este artículo tiene ''Precio Cero''. No puede listarse.\nVaya a Regsistro de Productos y cambie su precio a un valor correcto.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (TextBox3.Text == "")//USADO EN MODIFICAR PRECIO { TextBox3.Text = string.Format("{0:0.##}", double.Parse(c[5].ToString()));//VENTA } string PROVX = c[6].ToString();//PROV string OTROX = c[9].ToString();//OTRO string SECCX = c[10].ToString();//SECC string SUB_SECCX = c[11].ToString();//SUB_SECC string MARCAX = c[12].ToString();//MARCA int IVAX = int.Parse(c[13].ToString());//IVA float Venta2 = float.Parse(c[17].ToString());//VENTA2 float Venta3 = float.Parse(c[18].ToString());//VENTA3 float Apartir2 = float.Parse(c[19].ToString());//APARTIR DE... APLICA PRECIO2 float Apartir3 = float.Parse(c[20].ToString());//APARTIR DE... APLICA PRECIO3 Opt_Precio3.Text = "<&3: " + double.Parse(c[18]).ToString("0.##"); Opt_Precio2.Text = "<&2: " + double.Parse(c[17]).ToString("0.##"); Opt_Precio1.Text = "<&1: " + double.Parse(c[5]).ToString("0.##"); if (Opt_Precio2.Checked == true) //PRECIO 2 { TextBox3.Text = double.Parse(c[17]).ToString("0.##"); } if (Opt_Precio3.Checked == true) //PRECIO 3 { TextBox3.Text = double.Parse(c[18]).ToString("0.##"); } if (TextBox4.Text == "" | TextBox4.Text == "0") { //SI ESTÁ CONFIGURADO QUE EL PRODUCTO SE VENDA POR DEFECTO 1... if (c[14].ToString() == "1") { TextBox4.Text = "1"; } } //SI CANTIDAD ES VACÍO SE DETIENE if (TextBox4.Text == "" | TextBox4.Text == "0") { TextBox4.Text = "1"; TextBox4.Select(); return; } //CONSULTA SI YA EXISTE EN TEMPORAL Y EDITA, O DEJA CARGAR NUEVO string Cantidad = TextBox4.Text; string UsuarioSist = Global.USUARIO_SIST; string Precio = TextBox3.Text; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq2 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/temporal_update_o_insert.php"); rq2.Method = "POST"; byte[] byteArray2 = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}", TextBox1.Text, Cantidad, UsuarioSist, Precio)); rq2.ContentType = "application/x-www-form-urlencoded"; rq2.ContentLength = byteArray2.Length; Stream stream2 = rq2.GetRequestStream(); stream2.Write(byteArray2, 0, byteArray2.Length); stream2.Close(); // WebResponse response2 = rq2.GetResponse(); stream2 = response2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string devuelve2 = reader2.ReadToEnd(); reader2.Close(); stream2.Close(); response2.Close(); //string[] c2 = devuelve2.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve2); return; } //precio automático 2 y 3 aplica sólo si no es manualmente precios 2 y 3 if (int.Parse(Global.version) > 1) { if(Global.US_MODIFICA_PRECIO == 0) { if (Opt_Precio2.Checked == false) { if (Opt_Precio3.Checked == false) { Apartirde(); } } } } Limpiar(); MostrarGridVenta(); Sumar(); TextBox1.Select(); } } public void Apartirde()//VALIDA LA CANTIDAD VENDIDA PARA APLICAR PRECIOS MENORES (PRECIO 2 Y/O 3) { string UsuarioSist = Global.USUARIO_SIST; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq2 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/precios_menores.php"); rq2.Method = "POST"; byte[] byteArray2 = Encoding.UTF8.GetBytes(string.Format("nu={0}", UsuarioSist)); rq2.ContentType = "application/x-www-form-urlencoded"; rq2.ContentLength = byteArray2.Length; Stream stream2 = rq2.GetRequestStream(); stream2.Write(byteArray2, 0, byteArray2.Length); stream2.Close(); // WebResponse response2 = rq2.GetResponse(); stream2 = response2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string devuelve2 = reader2.ReadToEnd(); reader2.Close(); stream2.Close(); response2.Close(); string[] c2 = devuelve2.Split('▲'); if (c2.Length > 100) { MessageBox.Show(devuelve2); return; } } public void Vende_por_precio()//SI ES POR PRECIO { //ESCRIBE UN SEUDO CODIGO... TextBox1.Text = DateTime.Now.ToString("yy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd") + DateTime.Now.ToString("HH") + DateTime.Now.ToString("mm") + DateTime.Now.ToString("ss") + "0"; string Codigo = TextBox1.Text; string Cantidad = TextBox4.Text; string UsuarioSist = Global.USUARIO_SIST; string Precio = TextBox3.Text; if (double.Parse(Precio) == 0)//PRECIO CERO { MessageBox.Show("Este artículo no puede tener ''Precio Cero''. Escriba un valor correcto.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox1.Select(); return; } string Descrip = TextBox2.Text.ToUpper(); this.Cursor = Cursors.WaitCursor; HttpWebRequest rq2 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/vender_x_precio.php"); rq2.Method = "POST"; byte[] byteArray2 = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}", Codigo, Cantidad, UsuarioSist, Precio, Descrip)); rq2.ContentType = "application/x-www-form-urlencoded"; rq2.ContentLength = byteArray2.Length; Stream stream2 = rq2.GetRequestStream(); stream2.Write(byteArray2, 0, byteArray2.Length); stream2.Close(); // WebResponse response2 = rq2.GetResponse(); stream2 = response2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string devuelve2 = reader2.ReadToEnd(); reader2.Close(); stream2.Close(); response2.Close(); //string[] c2 = devuelve2.Split('▲'); this.Cursor = Cursors.Default; if (devuelve2.Length > 100) { MessageBox.Show(devuelve2); return; } Limpiar(); MostrarGridVenta(); Sumar(); TextBox1.Select(); } private void AlertaFacturar() { timer1.Start(); timer1.Enabled = true; } static int items = 0; public void MostrarGridVenta() { items = 0; //AVISAR QUE HAY QUE FACTURAR YA if (Global.FACTURA_TIPO == "7.5 Para TMU200") { try { int i = int.Parse(items_Label.Text.Substring(0, 2)); if (i > 23) { labelFACTURAR.Visible = true; AlertaFacturar(); } } catch { } } DataG1.Rows.Clear(); //MOSTRAR TEMPORAL EN DATAGRID DE VENTA string UsuarioSis = Global.USUARIO_SIST; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/mostrar_en_ventas.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼", UsuarioSis)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } //int items = 0; if (devuelve != "") { DataG2.Visible = true; foreach (var line in devuelve.Split('↔')) { var valores = line.Split('▲'); if (valores[0] != "") { string montox = string.Format("{0:0.##}", double.Parse(valores[5].ToString())); string preciox = string.Format("{0:0.##}", double.Parse(valores[4].ToString())); DataG1.Rows.Add(valores[0], valores[1], valores[2], valores[3], preciox, montox, valores[6], valores[7], valores[8]);//RS.GetString(5)); //NÚMERO CANTIDAD DE ITEM'S items += +1; items_Label.Text = items.ToString() + " items"; } } combo_Vendedor.Text = DataG1.CurrentRow.Cells[7].Value.ToString() + " | " + DataG1.CurrentRow.Cells[8].Value.ToString(); Ayuda_text.Visible=false; } else { Ayuda_text.Visible = true; } DataG1.Columns[0].Width = 0; DataG1.Columns[1].Width = 90; DataG1.Columns[2].Width = 50; DataG1.Columns[3].Width = 254; DataG1.Columns[4].Width = 60; DataG1.Columns[5].Width = 60; DataG1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; DataG1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; DataG1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight; DataG1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight; DataG1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; DataG1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; DataG1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; DataG1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Sumar(); } public void cuenta_espera() { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/cuenta_espera.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼", "")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains(" 100) { MessageBox.Show(devuelve); return; } if (devuelve.Trim() != "") { int Esp_en_linea = 0; foreach (var line in devuelve.Trim().Split('↔')) { var valores = line.Trim().Split('▲'); if (valores[0] != "") { //LIMITA NÚMERO DE NOMBRE DE CLIENTE A 15 int N = valores[0].ToString().Length; if (N > 15) { N = 15; } //LIMITA NÚMERO DE RUC A 5 int R = valores[1].ToString().Length; if (R > 5) { R = 5; } if (en_linea.Height > 16) {//SI LA PANTALLA ES MENOR en_linea.Text = en_linea.Text + "\n" + valores[0].ToString().Substring(0, N) + "," + valores[1].ToString().Substring(0, R); } else { if (en_linea.Text == "") { en_linea.Text = "VL:"; } en_linea.Text = en_linea.Text + " | " + valores[0].ToString().Substring(0, N) + "," + valores[1].ToString().Substring(0, R); } Esp_en_linea += +1;//NÚMERO DE VENTAS EN LÍNEA } } //MUESTRA LA CANTIDAD DE ITEMS if (Esp_en_linea > 1) { label10.Text = Esp_en_linea.ToString() + " Ventas en línea "; } else { label10.Text = Esp_en_linea.ToString() + " Venta en línea "; } } } catch { MessageBox.Show("No hay respuesta del servidor.","Uff... ¡qué pena!",MessageBoxButtons.OK,MessageBoxIcon.Error); } } public void ConsultarPrecios() { try { DataG2.Rows.Clear(); string filtro = TextBox2.Text; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/consultar_precios.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}", filtro, Global.num_esta, Global.ConSuc)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("> { new KeyValuePair("apiKey", Global.FE_ApiKey),//"097AAA69-D2F5-4928-8674-D086FD5A6B4B"), new KeyValuePair("tenantId", Global.FE_TenantId),//"marcialestechevera"), new KeyValuePair("tenantPunto",Global.FE_Punto),//"001-001"), new KeyValuePair("cliente", Global.FE_Razon),// "MARCIAL ESTECHE VERA"), new KeyValuePair("email", Global.FE_email), //"marcial@esteche.com"), // <-- corregido new KeyValuePair("data", DatosAenviar) // <-- corregido }; // Crear el contenido de la solicitud var contenido = new FormUrlEncodedContent(datos); // Realizar la solicitud POST HttpResponseMessage response = await httpClient.PostAsync(url, contenido); if (response.IsSuccessStatusCode) { string resultado = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(resultado)) { if (resultado.Contains("Estado: success"))//SI LA FACTURA FUE APROBADA ACTUALIZAR NUM DE FACT { Match match = Regex.Match(resultado, @"\b\d{44}\b"); if (match.Success) { CDC = match.Value; } RegistrarVenta();//INSERTA LOS DATOS DE VENTA A LA TABLA VENTAS button2_Click(null,null);//Cancelar ActualizaNumFactura(); BorraTemporal();//BORRA LA TABLA TEMPORAL //if (Global.EnviarWhVentas == 1) { EnviarWhats(); } BajarPDF_FactElectronica();//Baja y guarda la factura cancelar();//CANCELAR MostrarGridVenta(); Cursor.Current = Cursors.Default; //SOLO PARA PRUEBA //richTextBox1.Visible = true; //richTextBox1.Text = resultado; } else { MessageBox.Show(resultado, "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Information); Cursor.Current = Cursors.Default; //SOLO PARA PRUEBA //richTextBox1.Visible = true; //richTextBox1.Text = resultado; } } } else { MessageBox.Show("Error en la solicitud HTTP", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); Cursor.Current = Cursors.Default; } } } private void BajarPDF_FactElectronica() { string elPDF = Global.FE_URL + "factu_vb6/" + Global.FE_TenantId + "/factura_" + CDC + ".pdf"; string destino = @"C:\DOC_PDF\FACTURAS_PDF\" + "factura_" + CDC + ".pdf"; using (WebClient cliente = new WebClient()) { try { cliente.DownloadFile(elPDF, destino); Process.Start(destino); Cursor.Current = Cursors.Default; label14.Visible = false; } catch (Exception ex) { MessageBox.Show("Error al descargar el archivo: " + ex.Message); Cursor.Current = Cursors.Default; } } } private void EnviarWhats() { if (Global.Tel_Cliente.Length > 8) { string Telefono = ""; if (Global.Tel_Cliente.Length < 12)//SI NO ES FORMATO INTERNACONAL { if (Global.Tel_WhatsApp.Length >= 9) { Telefono = Global.Tel_WhatsApp.Substring(0, 3) + Global.Tel_Cliente.Substring(Global.Tel_Cliente.Length - 9); } } else//SI ES FORMATO INTERNACONAL { Telefono = Global.Tel_Cliente; } Principal principal = new Principal(); string mensaje = "Estimad@\n*" + Global.RazonS + "*\n" + "Muchas gracias por operar con nosotros. El monto es de\n*" + Global.SIMB_ + " " + double.Parse(TOTAL_label.Text).ToString("#,##0.##") + ".-*\n\n" + "Vuelva pronto, aquí le esperamos.\n\n" + "Atentemente,\n*_" + Global.Nom_EMPRESA + "_*\n" + Global.Tel_EMPRESA + "\n\n_*NO RESPONDER.* Este es un mensaje automático. Si desea puede ponerse en contacto a través del teléfono de la empresa._"; principal.EnviarWhatsApp(Global.ID_WhatsApp, mensaje, Telefono); principal.Espera(); } } public void RegistrarVenta()// y FACTURA ELECTRÓNICA { //FECHA DateTime fecha = DateTime.Now; string fechax = fecha.ToString("yyyy-MM-dd"); //HORA DateTime hora = DateTime.Now; string horax = hora.ToString("HH:mm:ss"); string Condix = ""; string horaz = hora.ToString("HHmmss"); if (Global.VCredito == true) { Global.COND = "CREDITO"; Condix = "2"; } else { Global.COND = "CONTADO"; Condix = "1"; } if (Global.autoimp == 1) { Global.RegistrarLV = 1; } string UsuSis = Global.USUARIO_SIST; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/registrar_venta.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}▼{6}▼{7}▼{8}▼{9}▼{10}▼{11}▼{12}▼{13}", UsuSis, fechax, horax, Global.RazonS, Global.RUC, Global.DIRECCION_F, Global.NUM_FACT, Global.COND, Global.NUM_caja, Global.Vendedor, Global.ID_vendedor, Global.Limite, Global.RegistrarLV, Global.ID_cliente)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } //SI LA VENTA ES A CRÉDITO if (Global.VCredito == true) { Registrar_credito(); } } public void TipoDocCliente(string Doc) { string Num, NumIden; if (Doc.Length > 4)// SI RUC ES MAS QUE 4 CARACTERES { if (Doc.Substring(Doc.Length - 2, 1) == "-") //SI ES RUC { Num = "11"; //Iden = "RUC (11)"; //RUC NumIden = Doc.Substring(0, Doc.Length - 2); Global.FE_TipoDoc = "0"; Global.FE_TipoOper = "B2B"; } else { Num = "12"; //Iden = "CEDULA DE IDENTIDAD (12)"; //CEDULA NumIden = Doc.Trim(); Global.FE_TipoDoc = "1"; Global.FE_TipoOper = "B2C"; } if (Doc.Substring(Doc.Length - 4, 4).ToString().Trim().Length == 0) { Num = "13"; //Iden = "PASAPORTE (13)"; //"PASAPORTE " NumIden = Doc.Trim(); Global.FE_TipoDoc = "2"; Global.FE_TipoOper = "B2F"; } if (Doc.Substring(Doc.Length - 4, 4).ToString().Trim().Length == 1) { Num = "14"; //Iden = "CEDULA EXTRANJERA (14)"; //" CEDULA EXTRANJERA " NumIden = Doc.Trim(); Global.FE_TipoDoc = "3"; Global.FE_TipoOper = "B2F"; } if (Doc.Substring(Doc.Length - 4, 4).ToString().Trim().Length == 2) { Num = "16"; //Iden = "CEDULA DIPLOMATICA (16)"; //" CEDULA DIPLOMATICA " NumIden = Doc.Trim(); Global.FE_TipoDoc = "6"; Global.FE_TipoOper = "B2F"; } if (Doc.Substring(Doc.Length - 4, 4).ToString().Trim().Length == 3) { Num = "17"; //Iden = "IDENTIFICACION TRIBUTARIA (17)"; //" CEDULA EXTRANJERA " NumIden = Doc.Trim(); Global.FE_TipoDoc = "1"; Global.FE_TipoOper = "B2C"; //1 = “Cédula paraguaya” //2 = “Pasaporte” //3 = “Cédula extranjera” //4 = “Carnet de residencia” //5 = “Innominado” //6 = “Tarjeta Diplomática de exoneración fiscal” } } else { Num = "15"; //Iden = "SIN NOMBRE (15)";//SIN NOMBRE NumIden = "X"; Global.FE_TipoDoc = ""; Global.FE_NumDoc = ""; Global.FE_TipoOper = "B2C"; } Global.TipoDocCliente = Num; } public void Registrar_credito() { //FECHA DateTime fecha = DateTime.Now; string fechax = fecha.ToString("yyyy-MM-dd"); //HORA DateTime hora = DateTime.Now; string horax = hora.ToString("HH:mm:ss"); Global.COND = "CRÉDITO"; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/registrar_credito.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}▼{6}▼{7}▼{8}▼{9}▼{10}", Global.USUARIO_SIST, fechax, horax, Global.RazonS, Global.RUC, Global.DIRECCION_F, Global.NUM_FACT, Global.COND, Global.NUM_caja, Global.ID_cliente, Global.Limite)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); if (devuelve.Length > 100) { MessageBox.Show(devuelve); return; } } public void BorraTemporal() { bool s = Global.Facturar; string ruta; ruta= "http://" + Global._host + "/ecv/borrar_temporal_y_pedidos.php"; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(ruta); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}", Global.USUARIO_SIST, Global.Num_Pedido, Global.Facturar, Global.Limite)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); if (devuelve.Length > 100) { MessageBox.Show(devuelve); return; } } private void Boton4_Click(object sender, EventArgs e) { if (Entrega_text.Enabled == false) { MessageBox.Show("Hay una venta en proceso, cierrela primero."); return; } button3_Click(sender, e);//espera Sumar(); } //GUARDA CLIENTE public void GuardarCliente() { RUC_TBox.Text = RUC_TBox.Text.ToUpper();//RUC EN MAYÚSCULAS POR SI TIENE XX HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/guardar_cliente.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}", Global.RazonS, Global.RUC)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); if (devuelve.Length > 100) { MessageBox.Show(devuelve); return; } RAZON_TBox.Text = ""; RUC_TBox.Text = ""; } //public void BETA() //{ // if (Global.beta != "") // { // Text = "Esta es una versión BETA. Dejará de funcionar el " + (int.Parse(Global.beta.Substring(6, 2)) + 1).ToString() + "-" + Global.beta.Substring(4, 2) + "-" + Global.beta.Substring(0, 4); // MessageBox.Show(Text); // if (int.Parse(Global.beta) == int.Parse(DateTime.Now.ToString("yyyyMMdd"))) // { // Text = "Este es el último día de Prueba. Mañana dejará de funcionar."; // MessageBox.Show(Text); // } // if (int.Parse(Global.beta) < int.Parse(DateTime.Now.ToString("yyyyMMdd"))) // { // Text = "Terminó el día de prueba. Dejará de funcionar."; // MessageBox.Show(Text); // Close(); // return; // } // } //} private void imprimirTicket2() { string num_ticket=""; string aimprimir = ""; Global.Totalx = TOTAL_label.Text; //CONSULTAR NÚMERO DE FACTURA if (Global.num_esta == null) { Global.num_esta = "0"; } int num_esta_ = int.Parse(Global.num_esta); SQLiteDataReader RSnF = null; string SQLnF = "SELECT NUM_FACT FROM CONFIG" + Global.NUM_caja + ";"; SQLiteCommand CMDnF = new SQLiteCommand(SQLnF, Global.conexion); RSnF = CMDnF.ExecuteReader(); if (RSnF.HasRows == true) { RSnF.Read(); num_ticket = int.Parse(Global.NUM_caja).ToString("0") + RSnF.GetInt32(0).ToString(); Global.Num_Pedido = num_ticket; } RSnF.Close(); double TotalX = double.Parse(Global.Totalx); string SimboloX = Global.SIMB_; foreach (DataGridViewRow dgvRenglon in DataG1.Rows) { string codigo = dgvRenglon.Cells[1].Value.ToString() + " "; string descrip = dgvRenglon.Cells[3].Value.ToString() + " "; string cant = dgvRenglon.Cells[2].Value.ToString() + " "; string preciox = dgvRenglon.Cells[4].Value.ToString(); string montox = dgvRenglon.Cells[5].Value.ToString(); string precio = " " + string.Format("{0:0.##}", float.Parse(preciox)); string monto = " " + string.Format("{0:0.##}", float.Parse(montox)); //////////////////////////////////////////////////////////////////// if (Global.impFactEn == 2)//Facturar en moneda 2 { if (Global.operacion2 == "Multiplicar") { precio = " " + string.Format("{0:0.##}", float.Parse(preciox) * Global.valorMoneda2);//hoy 23/07/2024 monto = " " + string.Format("{0:0.##}", float.Parse(montox) * Global.valorMoneda2);//hoy 23/07/2024 TotalX = double.Parse(Global.Totalx) * Global.valorMoneda2; SimboloX = Global.simboloMoneda2; } if (Global.operacion2 == "Dividir") { precio = " " + string.Format("{0:0.##}", float.Parse(preciox) / Global.valorMoneda2);//hoy 23/07/2024 monto = " " + string.Format("{0:0.##}", float.Parse(montox) / Global.valorMoneda2);//hoy 23/07/2024 TotalX = double.Parse(Global.Totalx) / Global.valorMoneda2; SimboloX = Global.simboloMoneda2; } } if (Global.impFactEn == 3)//Facturar en moneda 3 { if (Global.operacion3 == "Multiplicar") { precio = " " + string.Format("{0:0.##}", float.Parse(preciox) * Global.valorMoneda3);//hoy 24/07/2024 monto = " " + string.Format("{0:0.##}", float.Parse(montox) * Global.valorMoneda3);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) * Global.valorMoneda3; SimboloX = Global.simboloMoneda3; } if (Global.operacion3 == "Dividir") { precio = " " + string.Format("{0:0.##}", float.Parse(preciox) / Global.valorMoneda3);//hoy 24/07/2024 monto = " " + string.Format("{0:0.##}", float.Parse(montox) / Global.valorMoneda3);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) / Global.valorMoneda3; SimboloX = Global.simboloMoneda3; } } if (Global.impFactEn == 4)//Facturar en moneda 4 { if (Global.operacion4 == "Multiplicar") { precio = " " + string.Format("{0:0.##}", float.Parse(preciox) * Global.valorMoneda4);//hoy 24/07/2024 monto = " " + string.Format("{0:0.##}", float.Parse(montox) * Global.valorMoneda4);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) * Global.valorMoneda4; SimboloX = Global.simboloMoneda4; } if (Global.operacion4 == "Dividir") { precio = " " + string.Format("{0:0.##}", float.Parse(preciox) / Global.valorMoneda4);//hoy 24/07/2024 monto = " " + string.Format("{0:0.##}", float.Parse(montox) / Global.valorMoneda4);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) / Global.valorMoneda4; SimboloX = Global.simboloMoneda4; } } //////////////////////////////////////////////////////////////////// aimprimir = aimprimir + codigo.Substring(0,13) + "|" + descrip.Substring(0, 26) + "\n" + descrip.Substring(26, 13) + "|" + cant.Substring(0, 5) + "|" + precio.Substring(precio.Length-9, 9) + "|" + monto.Substring(monto.Length - 10, 10) + "\n"; } if (Global.BlocNota == 1)//CON BLOCK DE NOTA { string totalDes = SimboloX + " " + TotalX; Global.T_Construido = "NOTA DE PEDIDO No. " + num_ticket + "\nFECHA: " + DateTime.Now.ToString() + "\nVOX: " + Global.NUM_caja + " | VENDEDOR: " + Global.Vendedor + "\n----------------------------------------" + "\nARTICULOS |CANT | PRECIO| MONTO" + "\n----------------------------------------\n" + aimprimir + "----------------------------------------\n" + totalDes + "\n" + "----------------------------------------\n" + "PIDA SU FACTURA EN LA CAJA.\n.\n.\n.\n.\n.\n.\n."; //CREAR ARCHIVO Y GUARDAR string ruta = @"C:\\TICKET\PEDIDO_" + Global.Num_Pedido + ".txt"; var escritor = new StreamWriter(ruta); escritor.WriteLine(Global.T_Construido); escritor.Close(); //IMPRIME EL ARCHIVO CREADO ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "print"; // Seleccionar el programa para imprimir PDF por defecto info.FileName = ruta;//@"TICKET.TXT"; // Ruta hacia el fichero que quieres imprimir info.CreateNoWindow = true; // Hacerlo sin mostrar ventana info.WindowStyle = ProcessWindowStyle.Hidden; // Y de forma oculta Process p = new Process(); p.StartInfo = info; p.Start(); // Lanza el proceso try { p.WaitForInputIdle(); } catch { } System.Threading.Thread.Sleep(3000); // Espera 3 segundos } else //NO CON BLOCK DE NOTA { string totalDes = SimboloX + " " + TotalX; Global.T_Construido = "NOTA DE PEDIDO No. " + num_ticket + "\nFECHA: " + DateTime.Now.ToString() + "\nVOX: " + Global.NUM_caja + " | VENDEDOR: " + Global.USUARIO_SIST + "\n----------------------------------------" + "\nARTICULOS |CANT | PRECIO| MONTO" + "\n----------------------------------------\n" + aimprimir + "----------------------------------------\n" + totalDes + "\n" + "----------------------------------------\n" + "PIDA SU FACTURA EN LA CAJA.\n.\n.\n.\n.\n.\n.\n."; PrintTicket(); } ActualizaNumFactura(); } private void button1_Click(object sender, EventArgs e) //CERRAR VENTA (ESC) { if (Global.cobra_o_no == 1) //NO COBRA, SÓLO VENDE { //SI ES CON VENDEDORES if (Global.Presupuestar == false)//SI ES VENTA { if (int.Parse(Global.version) >= 2) { if (Global.ConVendedor == 1) { panelVendedores.Enabled = true; } else { panelVendedores.Enabled = false; } } } //SI ES CON VENDEDORES if (panelVendedores.Enabled == true) { try { if (combo_Vendedor.Text.Length < 4 || combo_Vendedor.Text.Substring(0,7)=="NINGUNO") { combo_Vendedor.Select(); return; } if (combo_Vendedor.Text.Length > 3)//SI EL COMBO DEL VENDEDOR ESTÁ VALIDADO { var x = combo_Vendedor.Text.Split('|');//VENDEDOR E ID DEL VENDEDOR Global.Vendedor = x[0]; Global.ID_vendedor = int.Parse(x[1]); } } catch { MessageBox.Show(combo_Vendedor.Text + " No parece ser un vendedor registrado.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } button3_Click(null, null);//ESPERA return;//NO COBRA, SÓLO VENDE } if (Global.NomClienteObli == 1) //Nombre de cliente obligatorio 2422901 { if (RAZON_TBox.Text == "") { RAZON_TBox.Focus(); return; } if (RUC_TBox.Text == "") { RUC_TBox.Focus(); return; } } label10.Text = " Ventas en línea "; //Vuelto: pide que se marque if (panel_VueltoTotal.Visible == true) { if (Vuelto_label.Text.Length > 0) { if (double.Parse(Vuelto_label.Text) > 0) { if (VUELTO_TITULO_label.Text.Substring(0, 6) == "Vuelto") { if (chec_vuelto1.Checked == false) { if (chec_vuelto2.Checked == false) { if (chec_vuelto3.Checked == false) { if (chec_vuelto4.Checked == false) { MessageBox.Show("Seleccione un tipo de moneda para vuelto."); return; } } } } } } } } //llama faltante if (double.Parse(Global.version) > 1) { if (Entrega_text.Text.Length > 0) { if (double.Parse(Entrega_text.Text) < double.Parse(TOTAL_label.Text)) { Faltante faltante = new Faltante(this); faltante.ShowDialog(); return; } } } // FACTURAR SIEMPRE if (Global.Presupuestar == false) { if (Global.FacturarSiempre == 1) { checFacturar.Checked = true; Global.Presupuestar = false; Global.Facturar = true; if (RAZON_TBox.Text == "") { RAZON_TBox.Select(); return; } if (RUC_TBox.Text == "") { RAZON_TBox.Select(); return; } } } if (Global.Facturar == true & Global.autoimp==0)//SI ESTÁ MARCADO "FACTURAR" LIMITAR EL REGISTRO DE VENTAS { if (Global.Lv == 1) //GENERAR LIBRO DE VENTAS { if (Global.NUM_FACT == null) { FacturaNum facturaNum = new FacturaNum(); facturaNum.ShowDialog(); return; } else { if (Global.NUM_FACT.Length < 1) { FacturaNum facturaNum = new FacturaNum(); facturaNum.ShowDialog(); return; } } } if (Global.FACTURA_TIPO == "A4 Doble, 16 items, Ori. - Dup." || Global.FACTURA_TIPO == "A4 Doble, 12 items, Ori. - Dup." || Global.FACTURA_TIPO == "") { Global.Limite = 16; } if (Global.FACTURA_TIPO == "A4 Entero, Escribanía, Orginal") { Global.Limite = 37; } if (Global.FACTURA_TIPO == "7.5 Para TMU200") { Global.Limite = 1000; } if (Global.FACTURA_TIPO == "Factura Electrónica") { Global.Limite = 1000; } } else//DE LO CONTRARIO SACAR TICKET NO LIMITAR (1000) { Global.Limite = 1000; } //SI ES CON VENDEDORES if (Global.Presupuestar == false)//SI ES VENTA { if (int.Parse(Global.version) >= 2) { if (Global.ConVendedor == 1) { panelVendedores.Enabled = true; } else { panelVendedores.Enabled = false; } } } //SI ES CON VENDEDORES if (panelVendedores.Enabled == true) { try { if (combo_Vendedor.Text.Length < 4) { combo_Vendedor.Select(); return; } if (combo_Vendedor.Text.Length > 3)//SI EL COMBO DEL VENDEDOR ESTÁ VALIDADO { var x = combo_Vendedor.Text.Split('|');//VENDEDOR E ID DEL VENDEDOR Global.Vendedor = x[0]; Global.ID_vendedor = int.Parse(x[1]); } } catch { MessageBox.Show(combo_Vendedor.Text + " No parece ser un vendedor registrado.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (Global.FACTURA_TIPO == "A4 Entero, Escribanía, Orginal") {// SI NO SE COMPLETARION LOS CAMPOS DEL FORM OBJETO, VUELVE A PEDIR if (Global.Objeto == "") { Objeto objeto = new Objeto(); objeto.ShowDialog(); return; } if (Global.NumEscri == "") { Objeto objeto = new Objeto(); objeto.ShowDialog(); return; } if (Global.Protocolo == "") { Objeto objeto = new Objeto(); objeto.ShowDialog(); return; } if (Global.SeccEscri == "") { Objeto objeto = new Objeto(); objeto.ShowDialog(); return; } if (Global.Contri == "") { Objeto objeto = new Objeto(); objeto.ShowDialog(); return; } } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/consulta_temporal.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", Global.USUARIO_SIST)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); //MessageBox.Show(devuelve.Trim().Length.ToString()); if (devuelve.Length > 100) { MessageBox.Show(devuelve); return; } if (devuelve.Trim().Length < 2) { MessageBox.Show("No hay una lista para cerrar.", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); TextBox1.Select(); return; } if (checFacturar.Checked == true || checPresu.Checked == true)//SI ESTÁ EN FACTURAR o PRESUPUESTAR { if (RAZON_TBox.Text == "")//SI ESTÁ VACÍO "RAZÓN SOCIAL" { label9.Left = RAZON_TBox.Left; label9.Text = "Escriba un Nombre de Cliente..."; label9.ForeColor = Color.White; RAZON_TBox.BackColor = Color.Red; RAZON_TBox.ForeColor = Color.White; RAZON_TBox.Select(); return; } if (RUC_TBox.Text == "")//SI ESTÁ VACÍO RUC { RUC_TBox.Select(); return; } } Global.RazonS = RAZON_TBox.Text; Global.RUC = RUC_TBox.Text; Global.Totalx = this.TOTAL_label.Text; if (checPresu.Checked == true) { Global.presu = 1; } else { Global.presu = 0; } if (checCred_o_Cont.Checked == false)//SI ES AL CONTADO { if (checPresu.Checked==false)//SI ES FACTURA { Global.Condi = "Contado |X| Crédito | |"; } else//SI ES PRESUPUESTO { Global.Condi = "PRESUPUESTO"; Entrega_text.Text = TOTAL_label.Text; } Global.Condicion = "CONTADO"; if (Entrega_text.Text == "") { Entrega_text.Select(); return; } else { if (double.Parse(Entrega_text.Text) >= double.Parse(TOTAL_label.Text)) { Global.Entregax = this.Entrega_text.Text; Global.Vueltox = this.Vuelto_label.Text; CerrarVenta(); } else { Entrega_text.Select(); return; } } } else//SI ES A CRÉDITO { Global.Entregax = "0";//VACIAR ENTREGA Global.Vueltox = "0";//VACIAR VUELTO if (RAZON_TBox.Text == "")//SI ESTÁ VACÍO RAZÓN SOCIAL... { RAZON_TBox.Select(); return; } if (RUC_TBox.Text == "")//SI ESTÁ VACÍO RUC... { RUC_TBox.Select(); return; } Global.Condicion = "CREDITO"; try { Global.Condi = "Contado | | Crédito |X|"; Global.VCredito = true; Global.ID_cliente = int.Parse(ID_CLIENTE_LB.Text); CerrarVenta(); } catch (Exception) { MessageBox.Show("Este cliente todavía no está registrado.\nRegísterlo y vuelva a intentar.", "¡ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } Global.MontoP = TOTAL_label.Text; MostrarGridVenta();//REFRESCA EL GRID DE VENTA GuardarCliente(); TextBox1.Select(); //Si no es FE Cancelar if (Global.FACTURA_TIPO != "Factura Electrónica") cancelar();//Cancelar Opt_Precio1.Checked = true; } private void Ventas_FormClosing(object sender, FormClosingEventArgs e) { //Cierre_Pendiente(); ////e.Cancel = true; } public void button2_Click(object sender, EventArgs e)//CANCELAR { if (Entrega_text.Enabled == false) { MessageBox.Show("Hay una venta en proceso, cierrela primero."); return; } cancelar(); } private void cancelar() { Inicio inicio = new Inicio(); Cancelar();//BORRA TEMPORAL Limpiar();//LIMPIA LOS CONTROLES RAZON_TBox.Text = ""; RUC_TBox.Text = ""; ID_LABEL.Text = ""; NO_buscar.Checked = false; checFacturar.Checked = false; checFacturar.Enabled = true; checCred_o_Cont.Checked = false; checCred_o_Cont.Enabled = true; checCon_pag.Checked = false; checCon_pag.Enabled = true; checPresu.Enabled = true; TextBox1.Select(); DataG3.Visible = false; no_imp_ticket.Checked = false; CliRegistrado = 1; Btn_Buscar_RUC.Visible = false; Global.espera = 0; Global.venta_enLinea = 0; Global.ventaNormal = 0; Global.Num_Pedido = ""; Entrega_text.Enabled = true; panel_VueltoTotal.Visible = false; Lab_Cabecera.Enabled = true; checMon2.Checked= false; checMon3.Checked = false; checMon4.Checked = false; Global.impFactEn = 0; } private void TextBox1_Validated(object sender, EventArgs e) { //if (TextBox1.Text.Length < 7 & TextBox1.Text.Length > 0) //{ // while (!(TextBox1.Text.Length == 7)) // { // TextBox1.Text = "0" + TextBox1.Text; // } //} } private void Sumar() { try { { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/sumar.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", Global.USUARIO_SIST)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); foreach (var line in devuelve.Trim().Split('↔')) { if (string.IsNullOrWhiteSpace(line)) continue; var valores = line.Split('▲'); TOTAL_label.Text = double.Parse(valores[0]).ToString("#,##0.##"); //VALIDA SI HAY VENTA double d = double.Parse(valores[0]); Global.ventaNormal = double.Parse(d.ToString()); if (valores[0] == "") { Global.ventaNormal = 0; } } //MessageBox.Show(devuelve); } } catch (Exception) { Global.ventaNormal = 0;//SI RESULTADO ES NULL PONE CERO } } private void Entrega_text_TextChanged(object sender, EventArgs e) { if (Entrega_text.Text.Length > 0) { entregaVal = double.Parse(Entrega_text.Text); } string txt = Entrega_text.Text; int i = 15; if (txt.Length > i) { MessageBox.Show("No se permite mayor a " + i + " dígitos", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Warning); txt = txt.Substring(0, i); Entrega_text.Text = txt; } Principal fp = new Principal(); try { if (TOTAL_label.Text.Length > 0 & Entrega_text.Text.Length > 0) { //MOSTRAR VUELTO double vueltox = double.Parse(Entrega_text.Text) - double.Parse(TOTAL_label.Text); //SIN DECIMALES Vuelto_label.Text = string.Format("{0:#,##0.##}", vueltox); //MOSTRAR ENTREGA CON FORMATO double entregax = double.Parse(Entrega_text.Text); //Entrega_text.Text = string.Format("{0:#,##0.##}", entregax); //Entrega_text.SelectionStart = Entrega_text.Text.Length + 1; //DETERMINA EL TITULO DEL VUELTO O FALTANTE string DETERMINA = Vuelto_label.Text; if (DETERMINA.Substring(0, 1) == "-") { VUELTO_TITULO_label.Text = "Faltante " + Global.SIMB_; //Vuelto_label.BackColor = Color.FromArgb(192, 0, 0); //VUELTO_TITULO_label.BackColor = Color.FromArgb(192, 0, 0); } else { VUELTO_TITULO_label.Text = "Vuelto " + Global.SIMB_; //Vuelto_label.BackColor = this.BackColor;//fp.Label1.BackColor; //VUELTO_TITULO_label.BackColor = this.BackColor;//fp.Label1.BackColor; } } } catch(Exception) { } colorVueltos(); } public void faltante1Escribir() { Entrega_text.Text = (entregaVal + faltanteVal1).ToString("0.##"); Entrega_text.Enabled= false; Lab_Cabecera.Enabled= false; Inicio inicio = new Inicio(); } public void faltante2Escribir() { string UsuSis = Global.USUARIO_SIST; double simbolo1 = 0; double simbolo2 = 0; string fecha = DateTime.Now.ToString("yyyy-MM-dd"); string hora = DateTime.Now.ToString("HH:mm:ss"); if (operacion2 == "Dividir") { Entrega_text.Text = (entregaVal + (faltanteVal2 * valorMoneda2)).ToString("0.##"); simbolo1 = -(faltanteVal2 * valorMoneda2); simbolo2 = (faltanteVal2); Entrega_text.Enabled = false; Lab_Cabecera.Enabled = false; Inicio inicio = new Inicio(); } if (operacion2 == "Multiplicar") { Entrega_text.Text = (entregaVal + (faltanteVal2 / valorMoneda2)).ToString("0.##"); simbolo1 = -(faltanteVal2 / valorMoneda2); simbolo2 = (faltanteVal2); Entrega_text.Enabled = false; Lab_Cabecera.Enabled = false; Inicio inicio = new Inicio(); } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/divisas_registrar2.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}", UsuSis, simbolo1, simbolo2, fecha, hora, "faltante")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } } public void faltante3Escribir() { string UsuSis = Global.USUARIO_SIST; double simbolo1 = 0; double simbolo3 = 0; string fecha = DateTime.Now.ToString("yyyy-MM-dd"); string hora = DateTime.Now.ToString("HH:mm:ss"); if (operacion3 == "Dividir") { Entrega_text.Text = (entregaVal + (faltanteVal3 * valorMoneda3)).ToString("0.##"); simbolo1 = -(faltanteVal3 * valorMoneda3); simbolo3 = (faltanteVal3); Entrega_text.Enabled = false; Lab_Cabecera.Enabled = false; Inicio inicio = new Inicio(); } if (operacion3 == "Multiplicar") { Entrega_text.Text = (entregaVal + (faltanteVal3 / valorMoneda3)).ToString("0.##"); simbolo1 = -(faltanteVal3 / valorMoneda3); simbolo3 = (faltanteVal3); Entrega_text.Enabled = false; Lab_Cabecera.Enabled = false; Inicio inicio = new Inicio(); } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/divisas_registrar3.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}", UsuSis, simbolo1, simbolo3, fecha, hora, "faltante")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } } public void faltante4Escribir() { string UsuSis = Global.USUARIO_SIST; double simbolo1 = 0; double simbolo4 = 0; string fecha = DateTime.Now.ToString("yyyy-MM-dd"); string hora = DateTime.Now.ToString("HH:mm:ss"); if (operacion4 == "Dividir") { Entrega_text.Text = (entregaVal + (faltanteVal4 * valorMoneda4)).ToString("0.##"); simbolo1 = -(faltanteVal4 * valorMoneda4); simbolo4 = (faltanteVal4); Entrega_text.Enabled = false; Lab_Cabecera.Enabled = false; Inicio inicio = new Inicio(); } if (operacion4 == "Multiplicar") { Entrega_text.Text = (entregaVal + (faltanteVal4 / valorMoneda4)).ToString("0.##"); simbolo1 = -(faltanteVal4 / valorMoneda4); simbolo4 = (faltanteVal4); Entrega_text.Enabled = false; Lab_Cabecera.Enabled = false; Inicio inicio = new Inicio(); } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/divisas_registrar4.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}", UsuSis, simbolo1, simbolo4, fecha, hora, "faltante")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } } public void colorVueltos() { lab_vuelto4.BackColor = Color.Green; lab_vueltoVal4.BackColor = lab_vuelto4.BackColor; lab_vuelto3.BackColor = Color.Blue; lab_vueltoVal3.BackColor = lab_vuelto3.BackColor; lab_vuelto2.BackColor = Color.Maroon; lab_vueltoVal2.BackColor = lab_vuelto2.BackColor;//Color.Green; Color.Blue; Color.Maroon; } private void colorTotal() { lab_total4.BackColor = lab_vuelto4.BackColor; lab_totalVal4.BackColor = lab_total4.BackColor; lab_total3.BackColor = lab_vuelto3.BackColor; lab_totalVal3.BackColor = lab_total3.BackColor; lab_total2.BackColor = lab_vuelto2.BackColor; lab_totalVal2.BackColor = lab_total2.BackColor; } private void Entrega_text_Enter(object sender, EventArgs e) { colorVueltos(); colorTotal(); Entrega_text.BackColor = Color.FromArgb(192,0,0); Entrega_titulo_label.BackColor= Color.FromArgb(192, 0, 0); if (double.Parse(Global.version) > 1) panel_VueltoTotal.Visible = true; } private void Entrega_text_Leave(object sender, EventArgs e) { Principal fp = new Principal(); Entrega_titulo_label.BackColor = this.BackColor; Entrega_text.BackColor = this.BackColor; try { if (double.Parse(Entrega_text.Text) < double.Parse(TOTAL_label.Text)) { panel_VueltoTotal.Visible = false; } } catch { panel_VueltoTotal.Visible = false; } } private void DataG1_Click(object sender, EventArgs e) { if (DataG1.CurrentRow==null) { TextBox1.Select(); return; } else { ID_LABEL.Text = DataG1.CurrentRow.Cells[0].Value.ToString(); TextBox1.Select(); } } private void CheckBox1_CheckedChanged(object sender, EventArgs e) { //if (Entrega_text.Enabled == false) //{ // MessageBox.Show("Hay una venta en proceso, cierrela primero."); // return; //} if (checFacturar.Checked == true) { checPresu.Checked = false; Global.Presupuestar = false; Global.Facturar = true; RAZON_TBox.Select(); } else { Global.Facturar = false; TextBox1.Select(); } } private void TextBox2_TextChanged(object sender, EventArgs e) { if (TextBox2.TextLength < 1) { TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; } TextBox2.Text = TextBox2.Text.Replace("&", "y"); TextBox2.Text = TextBox2.Text.Replace("'", "`"); TextBox2.Text = TextBox2.Text.Replace(";", ","); TextBox2.Text = TextBox2.Text.Replace("\\", ","); if (Regex.IsMatch(TextBox2.Text, "[^a-zA-Z0-9-/_() .,áéíóúÁÉÍÓÚñÑ%`]")) { MessageBox.Show("En el campo escrito existe caracter especial no admitido. Reemplace y vuelva a presionar ENTER.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Information); TextBox2.Select(); return; } string txt = TextBox2.Text; int i = 150; if (txt.Length > i) { MessageBox.Show("No se permite mayor a " + i + " dógitos", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Warning); txt = txt.Substring(0, i); TextBox2.Text = txt; } TextBox2.SelectionStart = TextBox2.TextLength+1; ConsultarPrecios(); } private void DataG2_Click(object sender, EventArgs e) { if(DataG2.CurrentRow == null) { } else { ID_LABEL.Text = ""; TextBox4.Text = ""; Opt_Precio1.Text = "<&1: "; Opt_Precio2.Text = "<&2: "; Opt_Precio3.Text = "<&3: "; TextBox1.Text = DataG2.CurrentRow.Cells[0].Value.ToString(); TextBox3.Text = DataG2.CurrentRow.Cells[2].Value.ToString(); Opt_Precio1.Text = "<&1: " + DataG2.CurrentRow.Cells[2].Value.ToString(); Opt_Precio2.Text = "<&2: " + DataG2.CurrentRow.Cells[15].Value.ToString(); Opt_Precio3.Text = "<&3: " + DataG2.CurrentRow.Cells[16].Value.ToString(); } } public void ConsultarRUC() { try { int i = int.Parse(RUC_TBox.Text); } catch { MessageBox.Show("Debe escribir sólo números."); RUC_TBox.Select(); return; } if (RUC_TBox.Text.Trim() == "") { RUC_TBox.Select(); return; } string archivo = "ruc" + RUC_TBox.Text.Trim().Substring(RUC_TBox.TextLength - 1, 1) + ".txt"; try { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(Global._host_serv + "/api/c_sharp.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}", archivo, RUC_TBox.Text)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (devuelve != "") { CliRegistrado = 0; //DataG3.Visible = true; foreach (var line in devuelve.Trim().Split('↔')) { var v = line.Trim().Split('|'); if (v[0] != "") { // DataG3.Rows.Add(v[1], v[0] + "-" + v[2], "0", "0", "0"); if (Global.FACTURA_TIPO != "Factura Electrónica") { RAZON_TBox.Text = v[1]; } else { Clientes clientes = new Clientes(); clientes.TextBox1.Text = v[1]; clientes.TextBox2.Text = v[2]; clientes.ShowDialog(); } } } CliRegistrado = 1; } } catch { MessageBox.Show("No hay conexión con el SSEL (Servidor de Servicios En Línea)", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void RUC_TBox_TextChanged(object sender, EventArgs e) { if (Regex.IsMatch(RUC_TBox.Text, "[^A-Za-z0-9- ]")) { RUC_TBox.Text = ""; RUC_TBox.Select(); return; } if (RUC_TBox.TextLength > 0) { if (RUC_TBox.Text.Substring(0, 1) == "-") { RUC_TBox.Text = ""; } } if (RUC_TBox.TextLength > 2)// SI RUC = 1233456-00 { try { string[] v; v = RUC_TBox.Text.Split('-'); if (v[1].Length > 1) { RUC_TBox.Text = ""; } } catch { } } string txt = RUC_TBox.Text; int i = 15; if (txt.Length > i) { MessageBox.Show("No se permite mayor a " + i + " dígitos", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Warning); txt = txt.Substring(0, i); RUC_TBox.Text = txt; } if (NO_buscar.Checked == false) { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/buscar_por_ruc.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", RUC_TBox.Text)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); if (devuelve.ToUpper().Contains(" 1)//Si la versión es 2 en adelante... //{ if (operacion2 == "Dividir")//Moneda 2 { double totalMone2 = double.Parse(TOTAL_label.Text) / valorMoneda2; lab_totalVal2.Text = totalMone2.ToString("0.##"); } else // Multiplica { double totalMone2 = double.Parse(TOTAL_label.Text) * valorMoneda2; lab_totalVal2.Text = totalMone2.ToString("0.##"); } if (operacion3 == "Dividir")//Moneda 3 { double totalMone3 = double.Parse(TOTAL_label.Text) / valorMoneda3; lab_totalVal3.Text = totalMone3.ToString("0.##"); } else // Multiplica { double totalMone3 = double.Parse(TOTAL_label.Text) * valorMoneda3; lab_totalVal3.Text = totalMone3.ToString("0.##"); } if (operacion4 == "Dividir")//Moneda 4 { double totalMone4 = double.Parse(TOTAL_label.Text) / valorMoneda4; lab_totalVal4.Text = totalMone4.ToString("0.##"); } else // Multiplica { double totalMone4 = double.Parse(TOTAL_label.Text) * valorMoneda4; lab_totalVal4.Text = totalMone4.ToString("0.##"); } //} //else { lab_totalVal2.Text = "No disp."; lab_totalVal3.Text = "No disp."; lab_totalVal4.Text = "No disp."; } } private void RAZON_TBox_TextChanged_1(object sender, EventArgs e) { if (CliRegistrado == 0) { return; }//SI NO ESTÁ REGISTRADO EL CLIENTE SE DETIENE if (VieneDeRUC == 1) { return; }//SI LA BUSQUEDA VIENE DE RUC.TEXT SE DETIENE if (Global.cobra_o_no == 1) //SOLO VENDE NO COBRA { if(Global.ventaNormal == 0)//TEMPORAL SIN REGISTRO { mostrarClienteEspera(); } return; } //if (NO_buscar.Checked == true) { return; } RAZON_TBox.Text = RAZON_TBox.Text.Replace("&", "y"); RAZON_TBox.Text = RAZON_TBox.Text.Replace("'", "`"); RAZON_TBox.Text = RAZON_TBox.Text.Replace(";", ","); RAZON_TBox.Text = RAZON_TBox.Text.Replace("\\", ","); RAZON_TBox.SelectionStart = RAZON_TBox.Text.Length + 1; if (Regex.IsMatch(RAZON_TBox.Text, "[^a-zA-Z0-9-/_() .,áéíóúÁÉÍÓÚñÑ`°]")) { MessageBox.Show("En el campo escrito existe caracter especial no admitido. Reemplace y vuelva a presionar ENTER.", "ATENCIÓN", MessageBoxButtons.OK, MessageBoxIcon.Information); RAZON_TBox.Select(); return; } if (RAZON_TBox.Text == "") { DataG3.Visible = false; return; } else { Ayuda_text.Visible = false; } if (RAZON_TBox.Text.Length > 0) { label9.Visible = false; } RAZON_TBox.Text = RAZON_TBox.Text.Replace(",", "."); DataG3.Rows.Clear(); //int i = 0; if (NO_buscar.Checked == false || checPresu.Checked== true)//SI ES UNA VENTA O PRESUPUESTO Y NO ESPERA { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/buscar_por_razon_s.php"); rq.Method = "POST"; //WebRequest.Create("http://" + Global._host + " byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", RAZON_TBox.Text.Trim())); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("ERROR"); if (re == true) { MessageBox.Show(devuelve); return; } int i = 0; if (devuelve != "") { foreach (var line in devuelve.Split('↔')) { if (line == "")//si la última línea está vacía, continua al siguiente proceso { continue; } var v = line.Split('▲'); DataG3.Visible = true; DataG3.Rows.Add(v[0].ToUpper(), v[1].ToUpper(), v[2].ToUpper(), v[3], v[4]); DataG3.Columns[0].Width = 365; DataG3.Columns[1].Width = 76; DataG3.Columns[2].Width = 0; DataG3.Columns[3].Width = 0; DataG3.Columns[4].Width = 0; i = i + 1; } } else { DataG3.Visible = false; RAZON_TBox.Text = ""; RUC_TBox.Select(); } DataG3.Rows.Add("0", "0", "0", "0", "0"); DataG3.Height = 27 * i; } else//SI NO ES VENTA (SI ES ESPERA O VENTA EN LÍNEA) { if (Global.ventaNormal > 0) { return; }//SI HAY REGISTRO EN EL TEMPORAL... SE DETIENE if (Global.venta_enLinea == 0)//SI ES ESPERA { mostrarClienteEspera(); } else//SI ES VENTAS EN LÍNEA { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/buscar_por_v_enlinea.php"); rq.Method = "POST"; //WebRequest.Create("http://" + Global._host + " byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}", "","1", RAZON_TBox.Text.Trim())); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("ERROR"); if (re == true) { MessageBox.Show(devuelve); return; } if (devuelve.Trim() != "") { foreach (var line in devuelve.Trim().Split('↔')) { if (line.Trim() == "")//si la última línea está vacía, continua al siguiente proceso { continue; } var v = line.Split('▲'); DataG3.Visible = true; DataG3.Rows.Add(v[0].ToUpper(), v[1].ToUpper(), v[2], "X","X"); DataG3.Columns[0].Width = 365; DataG3.Columns[1].Width = 76; DataG3.Columns[2].Width = 0; DataG3.Columns[3].Width = 0; DataG3.Columns[4].Width = 0; } } else { DataG3.Visible = false; } } } } private void mostrarClienteEspera() { DataG3.Rows.Clear(); DataG3.Visible = true; string Cliente = RAZON_TBox.Text; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/mostrarClienteEspera.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼", Cliente)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains(" i) { MessageBox.Show("No se permite mayor a " + i + " dógitos", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Warning); txt = txt.Substring(0, i); TextBox4.Text = txt; } try { double c = double.Parse(TextBox4.Text); }catch { TextBox4.Text = ""; } } private void TextBox4_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // solo 1 punto decimal if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } private void TextBox3_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // solo 1 punto decimal if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } private void Cred_o_Cont_CheckedChanged(object sender, EventArgs e) { //if (Entrega_text.Enabled == false) //{ // MessageBox.Show("Hay una venta en proceso, cierrela primero."); // return; //} if (checCred_o_Cont.Checked == true) { //checCon_pag.Checked = true; RAZON_TBox.Select(); checPresu.Checked = false; Global.Presupuestar = false; //Global.CPagare = true; Global.FCredito= true; } else { checCon_pag.Checked = false; //Global.CPagare = false; Global.FCredito = false; TextBox1.Select(); } } private void Con_pag_CheckedChanged(object sender, EventArgs e) { //if (Entrega_text.Enabled == false) //{ // MessageBox.Show("Hay una venta en proceso, cierrela primero."); // return; //} if (checCon_pag.Checked == true) { checPresu.Checked = false; Global.Presupuestar = false; Global.CPagare= true; } else { Global.CPagare = false; } } private void TextBox3_TextChanged(object sender, EventArgs e) { string txt = TextBox3.Text; int i = 10; if (txt.Length > i) { MessageBox.Show("No se permite mayor a " + i + " dógitos", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Warning); txt = txt.Substring(0, i); TextBox3.Text = txt; } if (txt.Length < 1) { Txt_PrecioMoneda2.Text = ""; Txt_PrecioMoneda3.Text = ""; Txt_PrecioMoneda4.Text = ""; return; } if (double.Parse(Global.version) > 1)//Si la versión es 2 en adelante... { if (operacion2 == "Dividir")//Moneda 2 { double precioMone2 = double.Parse(txt) / valorMoneda2; Txt_PrecioMoneda2.Text = precioMone2.ToString("0.##"); } else // Multiplica { double precioMone2 = double.Parse(txt) * valorMoneda2; Txt_PrecioMoneda2.Text = precioMone2.ToString("0.##"); } if (operacion3 == "Dividir")//Moneda 3 { double precioMone3 = double.Parse(txt) / valorMoneda3; Txt_PrecioMoneda3.Text = precioMone3.ToString("0.##"); } else // Multiplica { double precioMone3 = double.Parse(txt) * valorMoneda3; Txt_PrecioMoneda3.Text = precioMone3.ToString("0.##"); } if (operacion4 == "Dividir")//Moneda 4 { double precioMone4 = double.Parse(txt) / valorMoneda4; Txt_PrecioMoneda4.Text = precioMone4.ToString("0.##"); } else // Multiplica { double precioMone4 = double.Parse(txt) * valorMoneda4; Txt_PrecioMoneda4.Text = precioMone4.ToString("0.##"); } } else { Txt_PrecioMoneda2.Text = "No disp."; Txt_PrecioMoneda3.Text = "No disp."; Txt_PrecioMoneda3.Text = "No disp."; Txt_PrecioMoneda4.Text = "No disp."; } } private void Entrega_text_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // solo 1 punto decimal if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } private void Imprimir(object sender, PrintPageEventArgs e) { if (Global.no_imp_ticket == 0)//IMPRIMIR TICKET si es 0 { System.Drawing.Font font = new System.Drawing.Font("Lucida Console", 9); int ancho = 350; int y = 20; int alto = 12;//Global.altura + 305; string s; string[] rows; s = Global.T_Construido; rows = s.Split('\n'); int v = 0; while (v-1 < rows.GetUpperBound(0)) { e.Graphics.DrawString(rows[v].ToString(), font, Brushes.Black, new RectangleF(0, y += 15, ancho, alto)); v = v + 1; } } } public void PrintTicket() { printDocument1 = new System.Drawing.Printing.PrintDocument(); PrinterSettings ps = new PrinterSettings(); printDocument1.PrinterSettings = ps; printDocument1.PrintPage += Imprimir; printDocument1.Print(); } private void button3_Click(object sender, EventArgs e)//ESPERA { if (Entrega_text.Enabled == false) { MessageBox.Show("Hay una venta en proceso, cierrela primero."); return; } Global.espera = 1; if (Global.ventaNormal > 0)//TEMPORAL OCUPADO, PUEDE PASAR A ESPERA { if (Global.esperaImprime == 1)//IMPRIME ESPERA { imprimirTicket2(); RAZON_TBox.Text = Global.Num_Pedido; } } if (RAZON_TBox.Text == "")//SI ESTÁ VACÍO "RAZÓN SOCIAL" { NO_buscar.Checked = true;//NO BUSCAR EN TABLA CLIENTES, SÓLO EN ESPERA RAZON_TBox.BackColor = Color.Red; RAZON_TBox.ForeColor = Color.White; RAZON_TBox.Select(); return; } else { if (Global.ventaNormal > 0)//TEMPORAL OCUPADO, PUEDE PASAR A ESPERA { if (Global.esperaImprime ==0)//NO IMPRIME ESPERA { //AGREGA CÓDIGO FECHA A CADA CLIENTE ESPERA, SÓLO SI ES PARA ENVIAR RAZON_TBox.Text = RAZON_TBox.Text.Trim().ToUpper() + " - " + DateTime.Now.ToString("yyMMddHHmmss"); } } } Sumar();//PARA AGREGAR UN VALOR A venta NORMAL if (Global.ventaNormal > 0)//TEMPORAL OCUPADO, PUEDE PASAR A ESPERA { //CARGAR TEMPORAL A ESPERA string UsuarioSis = Global.USUARIO_SIST; string clienteEspera = RAZON_TBox.Text; string vendedor = Global.Vendedor; int id_vendedor = Global.ID_vendedor; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/espera_enviar.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼", UsuarioSis,clienteEspera, vendedor, id_vendedor)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } cancelar(); cuenta_espera(); } else//TEMPORAL LIBRE ESPERA PUEDE RECUPERARSE { NO_buscar.Checked = true;//NO BUSCAR EN TABLA CLIENTES, SÓLO EN ESPERA string cliente = RAZON_TBox.Text; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/espera_recibir.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼", cliente,Global.USUARIO_SIST)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } MostrarGridVenta(); cuenta_espera(); RAZON_TBox.Text = ""; RUC_TBox.Text = ""; TextBox1.Select(); } } private void TextBox1_Validating(object sender, CancelEventArgs e) { //SI NO ES NUMERICO Y PRETENDE VENDER POR PRECIO if (TextBox1.Text.Length > 0) { if (TextBox1.Text.Substring(TextBox1.Text.Length - 1, 1) == ",") { double numeric=0; if (double.TryParse(TextBox1.Text.Substring(0, TextBox1.Text.Length - 1), out numeric)) { } else { TextBox1.Text = ""; TextBox1.Select(); } } } } private void TextBox1_TextChanged(object sender, EventArgs e) { try { //Borrar el código si no es vender por precio if (TextBox1.Text.Substring(0,4)!= DateAndTime.Now.ToString("yyMM")) { TextBox3.Text = ""; } if (int.Parse(TextBox1.Text.Substring(0, 1)) > 0) { if (TextBox1.Text.Substring(TextBox1.TextLength - 1, 1) == "-") { double p = double.Parse(TextBox1.Text.Substring(0, TextBox1.TextLength - 1)); double t = double.Parse(TOTAL_label.Text); double d = (t * p) / 100; TextBox2.Text = "DESCUENTO DE " + p.ToString() + "%"; TextBox1.Text = "-" + d.ToString() + ","; Listar_Click(null, null); return; } } } catch { } if (TextBox1.Text.ToUpper() == "AYUDA") { //EJECUTA EL ANYDESK Process.Start("ayuda.exe"); this.WindowState = (FormWindowState)1; ; } try { //FILTRAR BUSQUEDA if (TextBox2.TextLength < 1) { if (TextBox1.Text.Substring(TextBox1.TextLength - 1, 1) == " ") { TextBox2.Text = TextBox1.Text.Trim(); TextBox1.Text = ""; TextBox2.Select(); TextBox2.SelectionStart = TextBox2.TextLength +1; return; } } } catch { } string txt = TextBox1.Text; int i = 15; if (txt.Length > i) { MessageBox.Show("No se permite mayor a " + i + " dógitos", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Warning); txt = txt.Substring(0, i); TextBox1.Text = txt; } //MUESTRA LA IMAGEN try { //pictureBox1.Image = Image.FromFile(Global.ruta_img + "\\" + TextBox1.Text + ".jpg"); pictureBox1.ImageLocation = "http://" + Global._host + "/ecv/imagenes/" + TextBox1.Text + ".jpg"; } catch (Exception) { pictureBox1.Image = pictureBox1.ErrorImage; } } private void Venta_lineaClick() { if (en_linea.Height == label15.Top - 50) { en_linea.Height = TOTAL_label.Top - 11;//medida larga } else { en_linea.Height = label15.Top - 50;//medida corta } Global.venta_enLinea = 1; Sumar();//SUMA PARA VALIDAR SI HAY VENTA EN CURSO O NO if (Global.ventaNormal > 0) { NO_buscar.Checked = false; } else { NO_buscar.Checked = true; } if (RAZON_TBox.Text == "") { label9.Left = RAZON_TBox.Left; label9.Text = "Escriba un Nombre."; RAZON_TBox.BackColor = Color.Red; RAZON_TBox.ForeColor = Color.White; RAZON_TBox.Select(); return; } if (RUC_TBox.Text == "") { RUC_TBox.Text = "XX"; } //ELIMINAR VENTA EN LÍNEA if (Global.ventaNormal > 0)//SI HAY UN MONTO SUPERIOR A CERO { try { if (float.Parse(Global.Num_Pedido) > 0)//SI HAY UNA VENTA EN LÍNEA EN PROCESO { DialogResult result = MessageBox.Show("Esta a punto de eliminar LA VENTA EN LÍNEA N° " + Global.Num_Pedido + ". ¿Confirma que realmente desea eliminar?", "¿ESTÁ SEGURO/A?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { return; } else { BorraTemporal();//BORRRA TEMPORAL Y PEDIDOS POR NÚMERO label10.Text = "Ventas en línea"; MostrarGridVenta(); Sumar(); TextBox1.Select(); NO_buscar.Checked = false; Global.venta_enLinea = 0; Global.Num_Pedido = ""; //button2_Click(null,null); cancelar(); } } } catch (Exception) { } } //VENTAS EN LÍNEA if (Global.ventaNormal == 0)//SI NO HAY VENTA EN CURSO... { NO_buscar.Checked = true; string Usuario = Global.USUARIO_SIST; string RazonS = RAZON_TBox.Text; string Ruc = RUC_TBox.Text; string NumPed = Global.Num_Pedido; this.Cursor = Cursors.WaitCursor; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/insert_de_pedidos_a_temporal.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼", Usuario, RazonS, Ruc, NumPed)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string[] c = devuelve.Split('▲'); this.Cursor = Cursors.Default; if (c[0].Length > 100) { MessageBox.Show(devuelve); return; } MostrarGridVenta(); Sumar(); TextBox1.Select(); NO_buscar.Checked = false; Global.venta_enLinea = 0; } } private void label10_Click(object sender, EventArgs e) { //Venta_lineaClick(); 021454569 Int. 147 Venta_lineaClick(); } private void Ventas_FormClosed(object sender, FormClosedEventArgs e) { Global.Venta_Hab = 0; Inicio inicio = new Inicio(); } private void NO_cerrar_Click(object sender, EventArgs e) { Cierre_Pendiente(); this.Close(); } private void Cantidad_Click(object sender, EventArgs e) { TextBox4.Select(); } private void Boton5_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); Btn_Devolucion.BackColor = Global.ColorMouseMuve; } int m, mx, my; private void Ventas_MouseDown(object sender, MouseEventArgs e) { m = 1; mx = e.X; my = e.Y; } private void checPresu_CheckedChanged(object sender, EventArgs e) { //if (Entrega_text.Enabled == false) //{ // checPresu.Checked = false; // MessageBox.Show("Hay una venta en proceso, cierrela primero."); // return; //} if (checPresu.Checked == true) { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/consulta_temporal.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", Global.USUARIO_SIST)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); if (devuelve.Length > 100) { MessageBox.Show(devuelve); return; } if (devuelve.Trim().Length < 2) { checFacturar.Checked = false; checCon_pag.Checked = false; checCred_o_Cont.Checked = false; Global.Presupuestar = false; Global.Facturar = false; Global.FCredito = false; Global.CPagare = false; checPresu.Checked = false; TextBox1.Select(); MessageBox.Show("Debe crear primero una lista a presupuestar y luego marcar \"Presupuestar\".", "¡ATENCIÓN!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } checFacturar.Checked = false; checCon_pag.Checked = false; checCred_o_Cont.Checked = false; Global.Presupuestar = true; Global.Facturar = false; Global.FCredito = false; Global.CPagare=false; TextBox1.Enabled= false; TextBox2.Enabled= false; TextBox3.Enabled= false; TextBox4.Enabled= false; RAZON_TBox.Select(); } else { Global.Presupuestar = false; TextBox1.Enabled = true; TextBox2.Enabled = true; TextBox3.Enabled = true; TextBox4.Enabled = true; TextBox1.Select(); } } private void checPresu_MouseHover(object sender, EventArgs e)//Presupuesto { Ayuda_text.Text = "\"Presupuesto\" \nAl marcar esta casilla el sistema se perapara a confeccionar un Presupuesto. También responde con las teclas combinadas \"Alt+P\". \nRecomendamos siempre usar el teclado para una operación más ágil.\n\nLo primero es cargar la lista que se desee presupuestar, luego al hacer clic en \"Fin\" o al presionar \"Esc\" de su teclado, el cursor del mouse enfocará en los campos Cliente y RUC respectivamente, si todavía están vacíos, deberá llenar y al hacer clic de nuevo en \"Fin\" o \"Esc\" de su teclado, la lista que tenga en pantalla se convertirá en una página PDF que usted podrá imprimir, como lo hiciera con la factura, pero será un presupuesto. La hoja a utilizar para la impresión es de tamaño A4."; } private void checCon_pag_MouseMove(object sender, MouseEventArgs e)//Con Pagaré { Ayuda_text.Text = "\"Con Pagaré\" \nAl marcar esta casilla el sistema se perapara a cerrar la venta y luego mostrar un formulario que debe ser llenado en algunos campos donde el cursor irá enfocando a medida que se presione la tecla ENTER.\n\nPara comenzar a usar esta función es necesario CONFIGURAR, para ello, vaya al menú principal, entre en Pagaré y luego clic en Configuración. También responde con las teclas combinadas \"Alt+A\". \nRecomendamos siempre usar el teclado para una operación más ágil."; } private void Btn_Devolucion_Click(object sender, EventArgs e) { if (Entrega_text.Enabled == false) { MessageBox.Show("Hay una venta en proceso, cierrela primero."); return; } if (DataG1.Rows.Count == 0) { MessageBox.Show("No hay item a devolver. Primero debe listar y luego hacer clic en Devolver.","ATENCIÓN",MessageBoxButtons.OK, MessageBoxIcon.Information); TextBox1.Select(); return; } DialogResult result = MessageBox.Show("¿Realmente desea Devolver?", "¿ESTÁ SEGURO/A?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) return; //FECHA DateTime fecha = DateTime.Now; string fechax = fecha.ToString("yyyy-MM-dd"); //HORA DateTime hora = DateTime.Now; string horax = hora.ToString("HH:mm:ss"); if (Global.VCredito == true) { Global.COND = "CREDITO"; } else { Global.COND = "CONTADO"; } string UsuSis = Global.USUARIO_SIST; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/devolucion.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}▼{6}▼{7}▼{8}", UsuSis, fechax, horax, Global.RazonS, Global.RUC, Global.DIRECCION_F, Global.NUM_FACT, Global.COND, Global.NUM_caja)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); if (devuelve.Length > 100) { MessageBox.Show(devuelve); return; } MostrarGridVenta(); } private void BTN_Devo_Click(object sender, EventArgs e) { Btn_Devolucion_Click(sender, e); } private void Btn_Devolucion_MouseMove(object sender, MouseEventArgs e) { Devolver_color_Bot(); Btn_Devolucion.BackColor = Global.ColorMouseMuve; Ayuda_text.Text = "\"Devolución\" \nEste botón devuelve artículo/s vendido/s, reponiendo el stock y registrando cantidad negativa en el reporte de Ventas de los artículos devueltos. También responde con las teclas combinadas \"Alt+D\". \nRecomendamos siempre usar el teclado para una operación más ágil.\n\nASÍ FUNCIONA:\n1- Listar el/los artículo/s como si fuera a vender.\n2- Hacer clic en \"Devolución\" o \"Alt+D\"\n3- Aceptar el mensaje de confirmación y listo."; } private void Ventas_MouseUp(object sender, MouseEventArgs e) { m = 0; } private void Barra_sup_MouseUp(object sender, MouseEventArgs e) { m = 0; } private void CargarVendedores() { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/vendedores_consultar.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼", "")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains(" 100) { //MENSAJE DE ERROR MessageBox.Show(devuelve1); } //ARREGLO PARA CREAR TICKET HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/crear_ticket.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", Global.USUARIO_SIST)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("ERROR"); if (re == true) { MessageBox.Show(devuelve); return; //nova; } bool IsConnected = false; //CABECERA COMIENZA ASÍ DateTime fecha = DateTime.Now; string hoy = fecha.ToString("dd-MM-yyyy, HH:mm:ss"); string textImp; textImp = "CONDICION DE VENTA: " + Global.Condicion + "\n" + "No. INTERNO: " + Global.NUM_FACT + "\n" + "CLIENTE: " + Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + "FECHA: " + hoy + "\n" + "CAJA " + Global.NUM_caja + " " + Global.USUARIO_SIST + "\n" + "----------------------------------------" + "\n" + "ARTICULOS |IVA|CANT | PRECIO| MONTO" + "\n"; double TotalExento = 0; double Total5 = 0; double Total10 = 0; if (devuelve != "") { foreach (var line in devuelve.Split('↔')) { if (line == "")//si la última línea está vacía, continua al siguiente proceso { continue; } var v = line.Split('▲'); string Cantx = v[0] + " "; string Artx = v[1].ToUpper() + " "; //SIN DECIMALES string Precx = " " + string.Format("{0:0.##}", float.Parse(v[2])); string Monx = " " + string.Format("{0:0.##}", float.Parse(v[3])); string IVA = string.Format("{0:00}", float.Parse(v[4])) + "%"; //EL CUERPOR (contenido del ticket) textImp = textImp + Artx.Substring(0, 14) + "|" + IVA + "|" + Cantx.Substring(0, 5) + "|" + Precx.Substring(Precx.Length - 7, 7) + "|" + Monx.Substring(Monx.Length - 7, 7) + "\n"; //EL TOTAL EXENTO DE IVA if (v[4] == "0") { TotalExento = TotalExento + double.Parse(v[3]); } //EL TOTAL IVA 5% if (v[4] == "5") { Total5 = Total5 + double.Parse(v[3]); } //EL TOTAL IVA 10% if (v[4] == "10") { Total10 = Total10 + double.Parse(v[3]); } Global.altura = Global.altura + 12; } } //FINAL DE LA IMPRESIÓN double LI5 = Total5 / 21;//LIQUIDACIÓN DE IVA 5% double LI10 = Total10 / 11;//LIQUIDACIÓN DE IVA 10% textImp = textImp + "----------------------------------------\n" + "SUBTOTAL EXENTO: " + TotalExento + "\n" + "SUBTOTAL 5%: " + Total5 + "\n" + "SUBTOTAL 10%: " + Total10 + "\n" + "----------------------------------------\n" + //SIN DECIMALES "LIQUIDACION DEL IVA 5%: " + string.Format("{0:0}", LI5) + "\n" + "LIQUIDACION DEL IVA 10%: " + string.Format("{0:0}", LI10) + "\n" + "TOTAL DEL IVA: " + string.Format("{0:0}", (LI5 + LI10)) + "\n"; string VALOR = double.Parse(Global.Totalx).ToString("0.00"); string DECIMAL = ""; //string DECIMAL = VALOR.Substring(VALOR.Length - 2, 2); if (VALOR.Substring(VALOR.Length - 2, 2) != "00") { DECIMAL = Nl.enletras(VALOR.Substring(VALOR.Length - 2, 2)); } string totalletras = "SON " + Global.SIMB_ + " " + Nl.enletras(Global.Totalx) + " " + DECIMAL; string totalL; if (totalletras.Length > 40) { totalL = totalletras.Substring(0, 40) + "\n" + totalletras.Substring(40, totalletras.Length - 40); } else { totalL = "SON " + Global.SIMB_ + " " + Nl.enletras(Global.Totalx) + " " + DECIMAL; } string sampleText; if (Global.Puerto_Ticket != "USB") //FINAL DE LA IMPRESIÓN SI ES LPT { sampleText = textImp + "----------------------------------------" + "\n" + totalL + "\n" + "TOTAL " + Global.SIMB_ + ": " + Global.Totalx + "\n" + "ENTREGA " + Global.SIMB_ + ": " + string.Format("{0:#,##0.##}", float.Parse(Global.Entregax)) + "\n" + "VUELTO " + Global.SIMB_ + ": " + Global.Vueltox + "\n" + Global.mJE_ + "\n" + "\n" + "\n" + "\n" + "\n" + "\n"; } else //FINAL DE LA IMPRESIÓN SI ES USB { sampleText = textImp + "----------------------------------------" + "\n" + totalL + "\n" + "TOTAL " + Global.SIMB_ + ": " + Global.Totalx + "\n" + "ENTREGA " + Global.SIMB_ + ": " + string.Format("{0:#,##0.##}", float.Parse(Global.Entregax)) + "\n" + "VUELTO " + Global.SIMB_ + ": " + Global.Vueltox + "\n" + Global.mJE_ + "\n" + "."; } //LA ORDEN DE IMPRESIÓN SE ENVÍA A LA IMPRESORA if (Global.Puerto_Ticket != "USB")//SI ES LPT { //CREA ARCHIVO Y GUARDAR string ruta = @"C:\\TICKET\FACTURA_" + Global.NUM_FACT + ".txt"; var escritor = new StreamWriter(ruta); escritor.WriteLine(sampleText); escritor.Close(); try {//ACÁ COMIENZA LA IMPRESIÓN REALMENTE Byte[] buffer = new byte[sampleText.Length]; buffer = System.Text.Encoding.ASCII.GetBytes(sampleText); SafeFileHandle fh = CreateFile(Global.Puerto_Ticket + ":", FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero); if (!fh.IsInvalid) { IsConnected = true; FileStream lpt1 = new FileStream(fh, FileAccess.ReadWrite); lpt1.Write(buffer, 0, buffer.Length); lpt1.Close(); } } catch (Exception ex) { string message = ex.Message; } } else//SI ES USB... { //CREA ARCHIVO Y GUARDAR string ruta = @"C:\\TICKET\FACTURA_" + Global.NUM_FACT + ".txt"; var escritor = new StreamWriter(ruta); escritor.WriteLine(sampleText); escritor.Close(); Global.T_Construido = sampleText; if (Global.BlocNota == 0)//SI NO ES CON BLOCK DE NOTAS { Ventas ventas = new Ventas();//LA NUEVA IMPRESIÓN (ESTÁ EN VENTAS) ventas.PrintTicket(); } else//IMPRIME CON BLOCK DE NOTAS { //IMPRIME EL ARCHIVO CREADO ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "print"; // Seleccionar el programa para imprimir PDF por defecto info.FileName = ruta;//@"TICKET.TXT"; // Ruta hacia el fichero que quieres imprimir info.CreateNoWindow = true; // Hacerlo sin mostrar ventana info.WindowStyle = ProcessWindowStyle.Hidden; // Y de forma oculta Process p = new Process(); p.StartInfo = info; p.Start(); // Lanza el proceso try { p.WaitForInputIdle(); } catch { } System.Threading.Thread.Sleep(3000); // Espera 3 segundos // Y cierra el programa de imprimir PDF's } Global.altura = 0; } //ACTUALIZA NÚMERO DE FACTURA ActualizaNumFactura(); //anteriormente hacía a continuación, ahora esta en otra rotina //string SQLFACT = "UPDATE CONFIG" + Global.NUM_caja + " SET NUM_FACT=NUM_FACT+1;"; //SQLiteCommand CMD_NF = new SQLiteCommand(SQLFACT, Global.conexion); //CMD_NF.ExecuteNonQuery(); fv.RegistrarVenta();//INSERTA LOS DATOS DE VENTA A LA TABLA VENTAS fv.BorraTemporal();//BORRA LA TABLA TEMPORAL //fv.Limpiar(); VA EN CERRAR VENTA,de lo cotrario no se ejecuta pagaré //VUELVE A ABRIR VENTAS, PORQUE DESAPARECE AL IMPRIMIR EL TICKET Principal principal = new Principal(); principal.Boton4_Click(null, null); //return IsConnected; } } private void ActualizaNumFactura() { //ACTUALIZA NÚMERO DE FACTURA string SQLFACT = "UPDATE CONFIG" + Global.NUM_caja + " SET NUM_FACT=NUM_FACT+1;"; SQLiteCommand CMD_NF = new SQLiteCommand(SQLFACT, Global.conexion); CMD_NF.ExecuteNonQuery(); } private void labelFACTURAR_Click(object sender, EventArgs e) { if (labelFACTURAR.Visible == true) { if (checFacturar.Checked == true) { checFacturar.Checked = false; return; } else { checFacturar.Checked = true; return; } } } protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) { try { if (DataG2.CurrentCell != null) { int icolumn = DataG2.CurrentCell.ColumnIndex; int irow = DataG2.CurrentCell.RowIndex; if (keyData == Keys.Enter) { if (icolumn == DataG2.Columns.Count - 1) { //DataG2.Rows.Add(); //DataG2.CurrentCell = DataG2[0, irow + 1]; } else { Listar_Click(null, null); } return true; } else { return base.ProcessCmdKey(ref msg, keyData); } } } catch { } return base.ProcessCmdKey(ref msg, keyData); } private void DataG2_KeyUp(object sender, KeyEventArgs e) { ID_LABEL.Text = ""; TextBox4.Text = ""; TextBox1.Text = DataG2.CurrentRow.Cells[0].Value.ToString(); TextBox3.Text = DataG2.CurrentRow.Cells[2].Value.ToString(); } private void DataG2_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button4_Click(object sender, EventArgs e) { Cierre_Pendiente(); Close(); } private void DataG3_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void checPresu_Click(object sender, EventArgs e) { } private void toolTip1_Popup(object sender, PopupEventArgs e) { } int i = 0; private void timer2_Tick(object sender, EventArgs e)//MULTI USO { { i = i+1; if (i == 30) { if (DataG1.Rows.Count == 0) { cuenta_en_linea(); } i = 0; } } } private void en_linea_Click(object sender, EventArgs e) { Venta_lineaClick(); } private void Label8_Click(object sender, EventArgs e) { } private void button4_Click_1(object sender, EventArgs e) { if (RUC_TBox.Text.Substring(RUC_TBox.TextLength - 2, 1) == "-") { RUC_TBox.Text = RUC_TBox.Text.Substring(0,RUC_TBox.TextLength-2); } DataG3.Rows.Clear(); ConsultarRUC(); Btn_Buscar_RUC.Visible= false; this.AcceptButton = Listar; } private void RAZON_TBox_Leave_1(object sender, EventArgs e) { RAZON_TBox.Text = RAZON_TBox.Text.Trim().ToUpper(); } private void RAZON_TBox_Validating(object sender, CancelEventArgs e) { if (RAZON_TBox.Text.Length < 1) { DataG3.Visible = false; } RAZON_TBox.BackColor = TextBox1.BackColor; RAZON_TBox.ForeColor = TextBox1.ForeColor; label9.Text = ""; } private void Opt_Precio1_CheckedChanged(object sender, EventArgs e) { TextBox1.Focus(); } private void Opt_Precio2_CheckedChanged(object sender, EventArgs e) { TextBox1.Focus(); } private void Opt_Precio3_CheckedChanged(object sender, EventArgs e) { TextBox1.Focus(); } private void Label3_Click(object sender, EventArgs e) { imprimirTicket2(); } private void Vuelto_label_Click(object sender, EventArgs e) { if (double.Parse(Global.version) > 1) { VUELTO_TITULO_label_Click(null, null); //button1_Click(null, null); } } private void Vuelto_label_TextChanged(object sender, EventArgs e) { if (double.Parse(Global.version) > 1)//Si la versión es 2 en adelante... { double d = 0; if (Vuelto_label.Text.Length > 0) { d = double.Parse(Vuelto_label.Text); } if (operacion2 == "Dividir")//Moneda 2 { double vueltoMone2 = d / valorMoneda2; lab_vueltoVal2.Text = vueltoMone2.ToString("0.##"); } else // Multiplica { double vueltoMone2 = d * valorMoneda2; lab_vueltoVal2.Text = vueltoMone2.ToString("0.##"); } if (operacion3 == "Dividir")//Moneda 3 { double vueltoMone3 = d / valorMoneda3; lab_vueltoVal3.Text = vueltoMone3.ToString("0.##"); } else // Multiplica { double vueltoMone3 = d * valorMoneda3; lab_vueltoVal3.Text = vueltoMone3.ToString("0.##"); } if (operacion4 == "Dividir")//Moneda 4 { double vueltoMone4 = d / valorMoneda4; lab_vueltoVal4.Text = vueltoMone4.ToString("0.##"); } else // Multiplica { double vueltoMone4 = d * valorMoneda4; lab_vueltoVal4.Text = vueltoMone4.ToString("0.##"); } faltante1 = Vuelto_label.Text; faltante2 = lab_vueltoVal2.Text; faltante3 = lab_vueltoVal3.Text; faltante4 = lab_vueltoVal4.Text; } } private void TOTAL_label_Click(object sender, EventArgs e) { } private void VUELTO_TITULO_label_Click(object sender, EventArgs e) { if (double.Parse(Global.version) > 1) { DialogResult result = MessageBox.Show("¿Confirma que ''" + VUELTO_TITULO_label.Text + "'' es correcto?", "¿ESTÁ SEGURO/A?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) return;//SE DETIENE SI RESPONDE "NO" chec_vuelto1.Checked = true; button1_Click(null, null); } } private void VUELTO_TITULO_label_TextChanged(object sender, EventArgs e) { if (VUELTO_TITULO_label.Text.Substring(0, 6) != "Vuelto") { lab_vuelto2.Text = "Faltante " + Global.simboloMoneda2; lab_vuelto3.Text = "Faltante " + Global.simboloMoneda3; lab_vuelto4.Text = "Faltante " + Global.simboloMoneda4; } else { lab_vuelto2.Text = "Vuelto " + Global.simboloMoneda2; lab_vuelto3.Text = "Vuelto " + Global.simboloMoneda3; lab_vuelto4.Text = "Vuelto " + Global.simboloMoneda4; } } private void lab_vuelto2_Click(object sender, EventArgs e) { if (double.Parse(Global.version) < 2) { return; } if (double.Parse(lab_vueltoVal2.Text) < 0.00000000000000001)//Si es faltante y no vuelto, entonces no hace nada { if (lab_vuelto2.Text.Substring(0, 8) == "Faltante") button1_Click(null, null); return; } DialogResult result = MessageBox.Show("¿Confirma que ''" + lab_vuelto2.Text + "'' es correcto?", "¿ESTÁ SEGURO/A?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) return;//SE DETIENE SI RESPONDE "NO" chec_vuelto2.Checked = true; string UsuSis = Global.USUARIO_SIST; double simbolo1 = 0; double simbolo2 = 0; string fecha = DateTime.Now.ToString("yyyy-MM-dd"); string hora = DateTime.Now.ToString("HH:mm:ss"); if (Global.operacion2 == "Dividir") { simbolo1 = double.Parse(lab_vueltoVal2.Text) * Global.valorMoneda2; simbolo2 = -(double.Parse(lab_vueltoVal2.Text)); } if (Global.operacion2 == "Multiplicar") { simbolo1 = double.Parse(lab_vueltoVal2.Text) / Global.valorMoneda2; simbolo2 = -(double.Parse(lab_vueltoVal2.Text)); } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/divisas_registrar2.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}", UsuSis, simbolo1, simbolo2, fecha, hora,"vuelto")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } button1_Click(null, null); } private void lab_vuelto3_Click(object sender, EventArgs e) { if (double.Parse(Global.version) < 2) { return; } if (double.Parse(lab_vueltoVal3.Text) < 0.00000000000000001)//Si es faltante y no vuelto, entonces no hace nada { if (lab_vuelto3.Text.Substring(0, 8) == "Faltante") { button1_Click(null, null); return; } } DialogResult result = MessageBox.Show("¿Confirma que ''" + lab_vuelto3.Text + "'' es correcto?", "¿ESTÁ SEGURO/A?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { return;//SE DETIENE SI RESPONDE "NO" } chec_vuelto3.Checked = true; string UsuSis = Global.USUARIO_SIST; double simbolo1 = 0; double simbolo3 = 0; string fecha = DateTime.Now.ToString("yyyy-MM-dd"); string hora = DateTime.Now.ToString("HH:mm:ss"); if (Global.operacion3 == "Dividir") { simbolo1 = double.Parse(lab_vueltoVal3.Text) * Global.valorMoneda3; simbolo3 = -(double.Parse(lab_vueltoVal3.Text)); } if (Global.operacion3 == "Multiplicar") { simbolo1 = double.Parse(lab_vueltoVal3.Text) / Global.valorMoneda3; simbolo3 = -(double.Parse(lab_vueltoVal3.Text)); } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/divisas_registrar3.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}", UsuSis, simbolo1, simbolo3, fecha, hora, "vuelto")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } button1_Click(null, null); } private void lab_vuelto4_Click(object sender, EventArgs e) { if (double.Parse(Global.version) < 2) { return; } if (double.Parse(lab_vueltoVal4.Text) < 0.00000000000000001) { if (lab_vuelto4.Text.Substring(0, 8) == "Faltante") button1_Click(null, null); return; } DialogResult result = MessageBox.Show("¿Confirma que ''" + lab_vuelto4.Text + "'' es correcto?", "¿ESTÁ SEGURO/A?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) return;//SE DETIENE SI RESPONDE "NO" chec_vuelto4.Checked = true; string UsuSis = Global.USUARIO_SIST; double simbolo1 = 0; double simbolo4 = 0; string fecha = DateTime.Now.ToString("yyyy-MM-dd"); string hora = DateTime.Now.ToString("HH:mm:ss"); if (Global.operacion4 == "Dividir") { simbolo1 = double.Parse(lab_vueltoVal4.Text) * Global.valorMoneda4; simbolo4 = -(double.Parse(lab_vueltoVal4.Text)); } if (Global.operacion4 == "Multiplicar") { simbolo1 = double.Parse(lab_vueltoVal4.Text) / Global.valorMoneda4; simbolo4 = -(double.Parse(lab_vueltoVal4.Text)); } HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/divisas_registrar4.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼{3}▼{4}▼{5}", UsuSis, simbolo1, simbolo4, fecha, hora, "vuelto")); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("
"); if (re == true) { MessageBox.Show(devuelve); return; } button1_Click(null, null); } private void lab_vueltoVal2_Click(object sender, EventArgs e) { if (double.Parse(Global.version) > 1) lab_vuelto2_Click(null, null); } private void lab_vueltoVal3_Click(object sender, EventArgs e) { if (double.Parse(Global.version) > 1) lab_vuelto3_Click(null, null); } private void lab_vueltoVal4_Click(object sender, EventArgs e) { if (double.Parse(Global.version) > 1) lab_vuelto4_Click(null, null); } private void panel_VueltoTotal_Paint(object sender, PaintEventArgs e) { } private void Lab_Cabecera_Paint(object sender, PaintEventArgs e) { } private void Cerrar_Click(object sender, EventArgs e) { Cierre_Pendiente(); Close(); } private void Ventas_KeyDown(object sender, KeyEventArgs e) { // Verificar si se presionó la tecla F1 if (e.KeyCode == Keys.F1) { chec_vuelto1.Checked = true; } if (e.KeyCode == Keys.F2) { chec_vuelto2.Checked = true; } if (e.KeyCode == Keys.F3) { chec_vuelto3.Checked = true; } if (e.KeyCode == Keys.F4) { chec_vuelto4.Checked = true; } } private void chec_vuelto1_CheckedChanged(object sender, EventArgs e) { if (chec_vuelto1.Checked) { chec_vuelto2.Checked = false; chec_vuelto3.Checked = false; chec_vuelto4.Checked = false; // VUELTO_TITULO_label_Click(null, null); } } private void chec_vuelto2_CheckedChanged(object sender, EventArgs e) { if (chec_vuelto2.Checked) { chec_vuelto1.Checked = false; chec_vuelto3.Checked = false; chec_vuelto4.Checked = false; //lab_vuelto2_Click(null, null); } } private void chec_vuelto3_CheckedChanged(object sender, EventArgs e) { if (chec_vuelto3.Checked) { chec_vuelto2.Checked = false; chec_vuelto1.Checked = false; chec_vuelto4.Checked = false; //lab_vuelto3_Click(null,null); } } private void chec_vuelto4_CheckedChanged(object sender, EventArgs e) { if (chec_vuelto4.Checked) { chec_vuelto2.Checked = false; chec_vuelto1.Checked = false; chec_vuelto3.Checked = false; //lab_vuelto4_Click(null, null); } } private void checMon2_CheckedChanged(object sender, EventArgs e) { if(checMon2.Checked) { checMon3.Checked= false; checMon4.Checked=false; Global.impFactEn = 2; TextBox1.Focus(); } } private void checMon3_CheckedChanged(object sender, EventArgs e) { if (checMon3.Checked) { checMon2.Checked = false; checMon4.Checked = false; Global.impFactEn = 3; TextBox1.Focus(); } } private void checMon4_CheckedChanged(object sender, EventArgs e) { if (checMon4.Checked) { checMon3.Checked = false; checMon2.Checked = false; Global.impFactEn = 4; TextBox1.Focus(); } } private void label15_MouseMove(object sender, MouseEventArgs e) { Ayuda_text.Text = "\"Precios 1, 2 y 3\" \nAl seleccionar una de las 2 opciones (Precio 2 o Precio 3), el sistema listará el precio del producto según la selección y dejará de aplicar los precios automatizados a partir de x cantidad. \nPuede seleccionar haciendo clic, también responde con las teclas combinadas \"Alt+1\", \"Alt+2\" y \"Alt+3\". \nRecomendamos siempre usar el teclado para una operación más ágil.\n\nLo primero es seleccionar el precio a vender y luego cargar la lista que se desee facturar.\nLa selección durará hasta que se cierre la venta al cliente en cuetión, para cada venta es necesario volver a seleecionar."; } private void no_imp_ticket_CheckedChanged(object sender, EventArgs e) { if (no_imp_ticket.Checked == true) { Global.no_imp_ticket = 1; } else { Global.no_imp_ticket = 0; } TextBox1.Select(); } private void FacturaGrandeEscri() { string condicionx = ""; if (Global.presu == 0)//SI ES FACTURA (CREA NÚMERO DE FACTURA) { GeneraNumFactura(); } else//SI ES PRESUPUESTO { Global.NUM_FACT = int.Parse(Global.num_esta).ToString("000") + "-" + int.Parse(Global.NUM_caja).ToString("000") + "-" + DateTime.Now.ToString("yyMMddHHmmss"); condicionx = " " + Global.Condi + " N° " + Global.NUM_FACT; } Ventas fv = new Ventas(); //ENCABEZADO FACTURA string RazonS = Global.RazonS; //"Darío El Más Capo Que Conozco"; string Ruc = Global.RUC;//"1234569-9"; string Direc = Global.DIRECCION_F + " ";// "Calle no conozco, c/No tengo idea 1520, Tucuman, Argentina."; string Fecha = DateTime.Today.ToString("dd-MMM-yyyy"); string Hora = " - Hora: " + DateAndTime.TimeOfDay.ToString("HH:mm"); string Condicion = condicionx;//" Condición de Venta: " + Global.Condi + " N° Interno: " + Global.NUM_FACT; string ruta = ""; //CREAR PDF if (Global.presu == 1)//SI ES PRESUPUESTO { ruta = "\\DOC_PDF\\PRESUPUESTOS_PDF\\" + Global.NUM_FACT + "_" + Global.RazonS + "_.pdf"; } else//SI ES FACTURA { ruta = "\\DOC_PDF\\FACTURAS_PDF\\" + Global.NUM_FACT + "_" + Global.RazonS + "_.pdf"; } string pdfgenerate = ruta; iTextSharp.text.Document oDoc; iTextSharp.text.pdf.PdfWriter pdfw; PdfContentByte cb; float top1; //MessageBox.Show("PDF generado. Haga clic en Aceptar para continuar."); //PREPARA Y ABRE EL PDF oDoc = new iTextSharp.text.Document(PageSize.A4, 30, 20, 20, 20); pdfw = PdfWriter.GetInstance(oDoc, new FileStream(pdfgenerate, FileMode.Create, FileAccess.Write, FileShare.None)); pdfw.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfw.SetFullCompression(); oDoc.Open(); oDoc.NewPage(); top1 = oDoc.PageSize.Top; //ENCABEZADO LOGO ORIGINAL if (Global.presu == 1)//SI ES PRESUPUESTO { iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("logo_presu.png", true); logo.SetAbsolutePosition(60, top1 - 130); oDoc.Add(logo); } cb = pdfw.DirectContent;//DEBE IR ANTES DE LAS LÍNEAS DE TEXTO // fecha, hora, condición de venta, NÚMERO INTERNO cb.BeginText(); cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Fecha:" + " " + Fecha + Hora + Condicion, 65, top1 - 140, 0); // razón social y ruc cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Razón Social: " + RazonS + " RUC: " + Ruc + " Teléfono: " + Global.Tel_Cliente, 65, top1 - 155, 0); // dirección cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Dirección:" + " " + Direc.Substring(0,70), 65, top1 - 170, 0); // TITULO VALOR DE VENTA cb.SetFontAndSize(BaseFont.CreateFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "VALOR DE VENTA", 440, top1 - 183, 0); // 1= Left, 2= Top // Títulos de columnas (CODIGO, CANT, DESCRIP, ETC.) cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " ARTÍCULOS Y/O SERVICIOS EXENTA IVA 5% IVA 10%", 75, top1 - 193, 0); cb.EndText(); // rectangulo 0 general (1= With, 2= Top, 3= Left, 4= Heigh) var rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 712, 60, (float)(59.256)); //var rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 712, 60, (float)(478.256)); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo VALOR VENTA (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 667, oDoc.PageSize.Width - 230, 657); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); //// rectangulo 1 (1= With, 2= Top, 3= Left, 4= Heigh) //rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 217, top1 - 175, oDoc.PageSize.Width - 445, 104); //rect.Border = iTextSharp.text.Rectangle.BOX; //rect.BorderWidth = (float)(0.5); //rect.BorderColor = new BaseColor(0, 0, 205); //cb = pdfw.DirectContent; //cb.Rectangle(rect); //cb = pdfw.DirectContent; //cb.SetLineWidth((float)(0.5)); // rectangulo DESCRIPCIÓN (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 230, top1 - 185, 60, 133); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 3 IVA5 (1= Left, 2= Top, 3= With, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 164, top1 - 185, oDoc.PageSize.Width - 92, 133); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); // rectangulo OBJETO (1= With, 2= Heihg, 3= Left, 4= Top) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 233, 590, 63, 642); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); //TEXTO (Objeto) CONSTANTE DENTRO DE OBJETO 1= Left, 2= Top cb.SetFontAndSize(BaseFont.CreateFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10); cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Objeto:", 69, 632, 0); //TEXTO (Concepto) VARIABLE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.Objeto + ".-", 103, 632, 0); //TEXTO (Nro. de Escritura:) CONSTANTE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Nro. de Escritura:", 69, (float)(612), 0); //TEXTO (en Número) VARIABLE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.NumEscri, 148, (float)(612), 0); //TEXTO (Protocolo:) CONSTANTE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Protocolo:", 230, (float)(612), 0); //TEXTO (texto de Protocolo) VARIABLE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.Protocolo, 276, (float)(612), 0); //TEXTO (Sección:) CONSTANTE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Sección:", 69, (float)(594), 0); //TEXTO (La Sección) VARIABLE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.SeccEscri, 110, (float)(594), 0); //TEXTO (Contribuyente:) CONSTANTE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Contribuyente:", 230, (float)(594), 0); //TEXTO (texto de Contribuyente) VARIABLE DENTRO DE OBJETO 1= Left, 2= Top cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.Contri, 296, (float)(594), 0); //// TASAS/GASTOS 1= Left, 2= Top //cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); //cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Tasas/Gastos", 363, 626, 0); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 195); // linea horizontal 1 cb.LineTo(60, top1 - 195); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 185); // linea horizontal 2 cb.LineTo(60, top1 - 185); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, 145); // linea horizontal 3 (PALANTA BAJA) cb.LineTo(60, 145); cb.MoveTo(oDoc.PageSize.Width - 20, 133); // linea horizontal 4 cb.LineTo(60, 133); cb.MoveTo(oDoc.PageSize.Width - 20, 121); // linea horizontal 5 cb.LineTo(60, 121); cb.MoveTo(oDoc.PageSize.Width - 20, 109); // linea horizontal 6 cb.LineTo(60, 109); cb.MoveTo(oDoc.PageSize.Width - 20, 97); // linea horizontal 7 cb.LineTo(60, 97); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, 85); // linea horizontal 8 cb.LineTo(60, 85); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, 73); // linea horizontal 9 cb.LineTo(60, 73); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); //LLENA EL CUERPO CON LA BD Principal fp = new Principal(); HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/factura_pdf.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼", Global.USUARIO_SIST, Global.Facturar, Global.Limite)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); //si hay error string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains(" 2) { //LOS DOS ÚLTIMOS string deci = VALORS.Substring(VALORS.Length - 2, 2); if (deci != "00")//SI NO ES CERO { string DECI_DOS = VALORS.Substring(VALORS.Length - 2, 2); TotalLet = TotalLet + " " + NumLet.enletras(DECI_DOS); } } // 1= Left, 2= Top cb.BeginText(); // SUBTOTALES: TÍTULO Y NUMEROS cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10); //SUBTOTALES EXENTA EN NÚMEROS string Exenta_ = " " + Global.SumExe.ToString("#,##0"); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Exenta_.Substring(Exenta_.Length - 12, 12), (float)(oDoc.PageSize.Width - 237), (float)(135), 0); //SUBTOTALES IVA5 EN NÚMEROS string Iva5_ = " " + Global.Sum5.ToString("#,##0"); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Iva5_.Substring(Iva5_.Length - 12, 12), (float)(oDoc.PageSize.Width - 165), (float)(135), 0); //SUBTOTALES IVA10 EN NÚMEROS string Iva10_ = " " + Global.Sum10.ToString("#,##0"); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Iva10_.Substring(Iva10_.Length - 12, 12), (float)(oDoc.PageSize.Width - 93), (float)(135), 0); //VALOR PARCIAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "VALOR PARCIAL: " + Global.SIMB_ + " " + TotalNumForM, (float)(61.5), (float)(135), 0); //DESCUENTO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "DESCUENTO: " + Global.SIMB_ + " " + (Descuento * (-1)).ToString("#,##0"), (float)(61.5), (float)(123), 0); //TOTAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TOTAL: " + Global.SIMB_ + " " + TotalConDesc.ToString("#,##0"), (float)(61.5), (float)(111), 0); cb.EndText(); // 1= Left, 2= Top cb.BeginText(); // TOTAL EN LETRAS Y NÚMEROS cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); //TOTAL EN LETRAS Y NÚMEROS (se usa en factura normal) //cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, (TotalLet + "----------------------------------------------------------------------------------------------------").Substring(0, 88) + "| " + Global.SIMB_ + " " + TotalNumForM, (float)(61.5), (float)(top1 - 761), 0); cb.EndText(); // 1= Left, 2= Top cb.BeginText(); // totales IVA y Total de IVA cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9); //LIQUIDACIÓN DEL IVA: cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "LIQUIDACIÓN DEL IVA: IVA 5%: " + string.Format("{0:#,##0}", Global.Total_iva5) + " | IVA 10%: " + string.Format("{0:#,##0}", Global.Total_iva10) + " | TOTAL DEL IVA: " + string.Format("{0:#,##0}", Global.Total_Iva), (float)(61.5), (float)(99), 0); //TOTAL REEMBOLSO DE IPUESTO: cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TOTAL REEMBOLSO DE IMPUESTO / TASA: " + Global.SumExe.ToString("#,##0"), (float)(61.5), (float)(87), 0); //TOTAL VENTAS / SERVICIOS: cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TOTAL VENTAS / SERVICIOS: ", (float)(61.5), (float)(75), 0); //TOTAL EN NÚMEROS: string TotalVentasx = " " + Global.SIMB_ + " " + Total_a_Cobrar.ToString("#,##0"); string TotalVentas = TotalVentasx.Substring(TotalVentasx.Length-20,20); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 11); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, TotalVentas, (float)(440), (float)(75), 0); //TOTAL EN LETRAS cb.SetFontAndSize(BaseFont.CreateFont(@"arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT,"Son " + Global.SIMB_ + " " + (TotalLet + "------------------------------------------------------------------------------------------------------------------------------------------------------------------").Substring(0, 100), (float)(61.5), (float)(63), 0); //MENSAJE EN LA FACTURA cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10); if (Global.mJE_ == null) { Global.mJE_ = ""; } cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.mJE_, (float)(61.5), (float)(top1 - 792), 0); cb.EndText(); pdfw.Flush(); oDoc.Close(); System.Diagnostics.Process.Start(@pdfgenerate);//MUESTRA LA FACTURA EN PDF //DESCONTAR STOCK, SÓLO EN EL CASO DE QUE EL CONTADOR SEA "1", PORQUE DEBE HACER ESTO UNA SOLA VEZ if (Global.CONTADOR_F == 1) { HttpWebRequest rq1 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/descontar_stock.php"); rq1.Method = "POST"; byte[] byteArray1 = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}", Global.USUARIO_SIST, Global.num_esta)); rq1.ContentType = "application/x-www-form-urlencoded"; rq1.ContentLength = byteArray1.Length; Stream stream1 = rq1.GetRequestStream(); stream1.Write(byteArray1, 0, byteArray1.Length); stream1.Close(); // WebResponse response1 = rq1.GetResponse(); stream1 = response1.GetResponseStream(); StreamReader reader1 = new StreamReader(stream1); string devuelve1 = reader1.ReadToEnd(); reader1.Close(); stream1.Close(); response1.Close(); string[] c1 = devuelve1.Split('▲'); if (c1[0].Length > 100) { //MENSAJE DE ERROR MessageBox.Show(devuelve1); } } //ACTUALIZA NÚMERO DE FACTURA if (Global.presu == 0)//SI NO ES PRESUPUESTO { string SQLFACT = "UPDATE CONFIG" + Global.NUM_caja + " SET NUM_FACT=NUM_FACT+1;"; SQLiteCommand CMD_NF = new SQLiteCommand(SQLFACT, Global.conexion); CMD_NF.ExecuteNonQuery(); } if (Global.presu == 0) { fv.RegistrarVenta();//INSERTA LOS DATOS DE VENTA A LA TABLA VENTAS (SI NO ES PRESUPUESTO) } fv.BorraTemporal();//BORRA LA TABLA TEMPORAL Global.Sum10 = 0; Global.Sum5 = 0; Global.SumExe = 0; Global.Total_Iva = 0; Global.Total_iva10 = 0; Global.Total_iva5 = 0; Global.TotalNum = 0; string UsuarioSist = Global.USUARIO_SIST; HttpWebRequest rq2 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/fact_consult_temp.php"); rq2.Method = "POST"; byte[] byteArray2 = Encoding.UTF8.GetBytes(string.Format("nu={0}", UsuarioSist)); rq2.ContentType = "application/x-www-form-urlencoded"; rq2.ContentLength = byteArray2.Length; Stream stream2 = rq2.GetRequestStream(); stream2.Write(byteArray2, 0, byteArray2.Length); stream2.Close(); // WebResponse response2 = rq2.GetResponse(); stream2 = response2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string devuelve2 = reader2.ReadToEnd(); reader2.Close(); stream2.Close(); response2.Close(); string[] c2 = devuelve2.Split('▲'); if (c2[0].Length > 100) { MessageBox.Show(devuelve2); } if (c2[0] == "SI") { //MessageBox.Show("SI"); Global.CONTADOR_F += 1; FacturaGrandeEscri(); } else { //MessageBox.Show("NO"); Global.CONTADOR_F = 1; } Global.Presupuestar = false; //return null; } public void Presupuesto() { Global.Limite = 52; //string condicionx = ""; Ventas fv = new Ventas(); string ruta = ""; string PresuNum = "PRESUPUESTO N° " + Global.num_esta + "-" + Global.NUM_caja + "-" + DateTime.Now.ToString("yyMMddHHmmss"); ruta = "\\DOC_PDF\\PRESUPUESTOS_PDF\\" + Global.RazonS + "_" + PresuNum + "_.pdf"; string pdfgenerate = ruta; iTextSharp.text.Document oDoc; iTextSharp.text.pdf.PdfWriter pdfw; PdfContentByte cb; float top1; //PREPARA Y ABRE EL PDF 1= TAMAÑO DE HOJA, 2= WHID, 3= TOP oDoc = new iTextSharp.text.Document(PageSize.A4, 60, 20, 90, 20); pdfw = PdfWriter.GetInstance(oDoc, new FileStream(pdfgenerate, FileMode.Create, FileAccess.Write, FileShare.None)); pdfw.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfw.SetFullCompression(); oDoc.Open(); oDoc.NewPage(); top1 = oDoc.PageSize.Top; //ENCABEZADO LOGO ORIGINAL if (Global.presu == 1)//SI ES PRESUPUESTO { iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("logo_presu.png", true); logo.SetAbsolutePosition(60, top1-70); oDoc.Add(logo); } cb = pdfw.DirectContent;//DEBE IR ANTES DE LAS LÍNEAS DE TEXTO string PresuFecha = DateTime.Now.ToString("dd") + " de " + DateTime.Now.ToString("MMMM") + " de " + DateTime.Now.ToString("yyyy.-"); PdfPTable table0 = new PdfPTable(1);//TABLA CON 1 CELDAS Phrase Conte4 = new Phrase(Global.PresuCiudad + ", " + PresuFecha, FontFactory.GetFont(FontFactory.DefaultEncoding, 12, BaseColor.BLACK)); PdfPCell TEXTO_T0 = new PdfPCell(Conte4); TEXTO_T0.HorizontalAlignment = Element.ALIGN_RIGHT; TEXTO_T0.BackgroundColor = new BaseColor(255, 255, 255); TEXTO_T0.BorderColor = new BaseColor(255, 255, 255);//125,125,255 table0.AddCell(TEXTO_T0); table0.WidthPercentage = 100; oDoc.Add(table0); string Dir = (CultureInfo.InvariantCulture.TextInfo.ToTitleCase(Global.DIRECCION_F.ToLower())); PdfPTable table = new PdfPTable(1);//TABLA CON 1 CELDAS Phrase Conte1 = new Phrase(Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + Dir + "\n\n" + Global.PresuText, FontFactory.GetFont(FontFactory.DefaultEncoding, 12, BaseColor.BLACK)); PdfPCell TEXTO_T1 = new PdfPCell(Conte1); TEXTO_T1.HorizontalAlignment = Element.ALIGN_JUSTIFIED; TEXTO_T1.BackgroundColor = new BaseColor(255, 255, 255); TEXTO_T1.BorderColor = new BaseColor(255, 255, 255);//125,125,255 table.AddCell(TEXTO_T1); table.WidthPercentage = 100; oDoc.Add(table); //tbala------------------------------------------------------------------------------------- cb.BeginText(); cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); // PRESUPUESTO N° cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, PresuNum, 61, top1 - 288, 0); // 1= Left, 2= Top // Títulos de columnas (CODIGO, CANT, DESCRIP, ETC.) cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "CANTIDAD ARTÍCULOS Y/O SERVICIOS PRECIO/U MONTO", 61, top1 - 299, 0); cb.EndText(); // rectangulo 0 general (1= With, 2= Top, 3= Left, 4= Heihg) var rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, top1 - 290, 60, (float)(59.256)); //var rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 712, 60, (float)(478.256)); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 1 CUERPO (1= With, 2= Top, 3= Left, 4= Heihg) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 135, top1 - 290, oDoc.PageSize.Width - 490, 109); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 3 PRECIO (1= With, 2= Top, 3= Left, 4= Heihg) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 135, top1 - 290, oDoc.PageSize.Width - 77, 109); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 290); // linea horizontal 1 cb.LineTo(60, top1 - 290); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 300); // linea horizontal 2 cb.LineTo(60, top1 - 300); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, 109); // linea horizontal 6 cb.LineTo(60, 109); cb.MoveTo(oDoc.PageSize.Width - 20, 97); // linea horizontal 7 cb.LineTo(60, 97); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, 85); // linea horizontal 8 cb.LineTo(60, 85); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, 73); // linea horizontal 9 cb.LineTo(60, 73); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); //LLENA EL CUERPO CON LA BD Principal fp = new Principal(); HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/factura_pdf.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼", Global.USUARIO_SIST, Global.Facturar, Global.Limite)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); //si hay error string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains(" 2) { //LOS DOS ÚLTIMOS string deci = VALORS.Substring(VALORS.Length - 2, 2); if (deci != "00")//SI NO ES CERO { string DECI_DOS = VALORS.Substring(VALORS.Length - 2, 2); TotalLet = TotalLet + " " + NumLet.enletras(DECI_DOS); } } // 1= Left, 2= Top cb.BeginText(); // SUBTOTALES: TÍTULO Y NUMEROS cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); ////TOTAL EN NÚMEROS //string Iva10_ = " " + TotalNumForM; //cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Iva10_.Substring(Iva10_.Length - 12, 12), (float)(oDoc.PageSize.Width - 79), (float)(99), 0); //VALOR PARCIAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "VALOR PARCIAL: " + Global.SIMB_ + " " + TotalNumForM, (float)(61.5), (float)(99), 0); //DESCUENTO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "DESCUENTO: " + Global.SIMB_ + " " + (Descuento * (-1)).ToString("#,##0"), (float)(61.5), (float)(87), 0); cb.EndText(); // 1= Left, 2= Top cb.BeginText(); // TOTAL EN LETRAS Y NÚMEROS cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); cb.EndText(); // 1= Left, 2= Top cb.BeginText(); // totales IVA y Total de IVA cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); //TOTAL VENTAS / SERVICIOS: cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TOTAL VENTAS / SERVICIOS: ", (float)(61.5), (float)(75), 0); //TOTAL EN NÚMEROS: string TotalVentasx = " " + Global.SIMB_ + " " + Total_a_Cobrar.ToString("#,##0.##"); string TotalVentas = TotalVentasx.Substring(TotalVentasx.Length - 20, 20); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 11); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, TotalVentas, (float)(440), (float)(75), 0); //TOTAL EN LETRAS cb.SetFontAndSize(BaseFont.CreateFont(@"arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Son " + Global.SIMB_ + " " + (TotalLet + "------------------------------------------------------------------------------------------------------------------------------------------------------------------").Substring(0, 100), (float)(61.5), (float)(63), 0); //MENSAJE EN LA FACTURA cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); if (Global.mJE_ == null) { Global.mJE_ = ""; } cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.mJE_, (float)(61.5), (float)(top1 - 792), 0); cb.EndText(); pdfw.Flush(); oDoc.Close(); System.Diagnostics.Process.Start(@pdfgenerate);//MUESTRA LA FACTURA EN PDF fv.BorraTemporal();//BORRA LA TABLA TEMPORAL Global.Sum10 = 0; Global.Sum5 = 0; Global.SumExe = 0; Global.Total_Iva = 0; Global.Total_iva10 = 0; Global.Total_iva5 = 0; Global.TotalNum = 0; string UsuarioSist = Global.USUARIO_SIST; HttpWebRequest rq2 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/fact_consult_temp.php"); rq2.Method = "POST"; byte[] byteArray2 = Encoding.UTF8.GetBytes(string.Format("nu={0}", UsuarioSist)); rq2.ContentType = "application/x-www-form-urlencoded"; rq2.ContentLength = byteArray2.Length; Stream stream2 = rq2.GetRequestStream(); stream2.Write(byteArray2, 0, byteArray2.Length); stream2.Close(); // WebResponse response2 = rq2.GetResponse(); stream2 = response2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string devuelve2 = reader2.ReadToEnd(); reader2.Close(); stream2.Close(); response2.Close(); string[] c2 = devuelve2.Split('▲'); if (c2[0].Length > 100) { MessageBox.Show(devuelve2); } if (c2[0] == "SI") { //MessageBox.Show("SI"); Global.CONTADOR_F += 1; Presupuesto(); } else { //MessageBox.Show("NO"); Global.CONTADOR_F = 1; } Global.Presupuestar = false; } } public class PdfClass { public object Facturar() { string condicionx = ""; if (Global.presu == 0)//SI ES FACTURA (CREA NÚMERO DE FACTURA) { Ventas ventas = new Ventas(); ventas.GeneraNumFactura(); condicionx = " Condición de Venta: " + Global.Condi + " Vendedor: " + Global.Vendedor;//N° Interno: " + Global.NUM_FACT; ; } Ventas fv = new Ventas(); //ENCABEZADO FACTURA string RazonS = Global.RazonS; //"Darío El Más Capo Que Conozco"; string Ruc = Global.RUC;//"1234569-9"; string Tel = Global.Tel_Cliente; string Direc = Global.DIRECCION_F;// "Calle no conozco, c/No tengo idea 1520, Tucumán, Argentina."; string Fecha = DateTime.Today.ToString("dd-MMM-yyyy"); string Hora = " - Hora: " + DateAndTime.TimeOfDay.ToString("HH:mm"); string Condicion = condicionx;//" Condición de Venta: " + Global.Condi + " N° Interno: " + Global.NUM_FACT; string ruta = ""; //CREAR PDF if (Global.presu == 1)//SI ES PRESUPUESTO { ruta = "\\DOC_PDF\\PRESUPUESTOS_PDF\\" + Global.NUM_FACT + "_" + Global.RazonS + "_.pdf"; } else//SI ES FACTURA { ruta = "\\DOC_PDF\\FACTURAS_PDF\\" + Global.NUM_FACT + "_" + Global.RazonS + "_.pdf"; } string pdfgenerate = ruta; iTextSharp.text.Document oDoc; iTextSharp.text.pdf.PdfWriter pdfw; PdfContentByte cb; float top1; //MessageBox.Show("PDF generado. Haga clic en Aceptar para continuar."); //PREPARA Y ABRE EL PDF oDoc = new iTextSharp.text.Document(PageSize.A4, 30, 20, 20, 20); pdfw = PdfWriter.GetInstance(oDoc, new FileStream(pdfgenerate, FileMode.Create, FileAccess.Write, FileShare.None)); pdfw.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfw.SetFullCompression(); oDoc.Open(); oDoc.NewPage(); top1 = oDoc.PageSize.Top; //ENCABEZADO LOGO ORIGINAL if (Global.presu == 1)//SI ES PRESUPUESTO { iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("logo_presu.png", true); logo.SetAbsolutePosition(60, top1 - 130); oDoc.Add(logo); } //ENCABEZADO LOGO DUPLICADO if (Global.presu == 1)//SI ES PRESUPUESTO { iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("logo_presu.png", true); logo.SetAbsolutePosition(60, top1 - 549); oDoc.Add(logo); } cb = pdfw.DirectContent;//DEBE IR ANTES DE LAS LÍNEAS DE TEXTO // fecha, hora, condición de venta, NÚMERO INTERNO cb.BeginText(); cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Fecha:" + " " + Fecha + Hora + Condicion, 65, top1 - 140, 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Fecha:" + " " + Fecha + Hora + Condicion, 65, top1 - 559, 0); // razón social y ruc cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Razón Social: " + RazonS + " RUC: " + Ruc + " TEL.: " + Tel, 65, top1 - 155, 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Razón Social: " + RazonS + " RUC: " + Ruc + " TEL.: " + Tel, 65, top1 - 574, 0); // dirección cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Dirección:" + " " + Direc, 65, top1 - 170, 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Dirección:" + " " + Direc, 65, top1 - 589, 0); // TITULO VALOR DE VENTA cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "VALOR DE VENTA", 465, top1 - 173, 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "VALOR DE VENTA", 465, top1 - 592, 0); // 1= Left, 2= Top // Títulos de columnas (CODIGO, CANT, DESCRIP, ETC.) cb.SetColorFill(iTextSharp.text.BaseColor.BLUE); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "CÓDIGO CANT ARTÍCULOS Y/O SERVICIOS PRECIO/U EXENTA IVA 5% IVA 10%", 75, top1 - 183, 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "CÓDIGO CANT ARTÍCULOS Y/O SERVICIOS PRECIO/U EXENTA IVA 5% IVA 10%", 75, top1 - 602, 0); cb.EndText(); // rectangulo 0 general (1= With, 2= Top, 3= Left, 4= Heigh) var rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 712, 60, (float)(478.256)); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 0 general (DUPLICADO) (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 293, 60, (float)(59.256)); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo VALOR VENTA (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 677, oDoc.PageSize.Width - 170, 667); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo VALOR VENTA (DUPLICADO) (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 20, 258, oDoc.PageSize.Width - 170, 248); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 1 (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 217, top1 - 175, oDoc.PageSize.Width - 445, top1 - 319); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 1 (DUPLICADO) (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 217, 248, oDoc.PageSize.Width - 445, 104); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 2 (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 170, top1 - 175, oDoc.PageSize.Width - 470, top1 - 319); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 2 (DUPLICADO) (1= With, 2= Top, 3= Left, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 170, 248, oDoc.PageSize.Width - 470, 104); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); // rectangulo 3 (1= Left, 2= Top, 3= With, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 120, top1 - 175, oDoc.PageSize.Width - 70, top1 - 319); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); // rectangulo 3 (DUPLICADO) (1= Left, 2= Top, 3= With, 4= Heigh) rect = new iTextSharp.text.Rectangle(oDoc.PageSize.Width - 120, 248, oDoc.PageSize.Width - 70, 104); rect.Border = iTextSharp.text.Rectangle.BOX; rect.BorderWidth = (float)(0.5); rect.BorderColor = new BaseColor(0, 0, 205); cb = pdfw.DirectContent; cb.Rectangle(rect); cb = pdfw.DirectContent; cb.SetLineWidth((float)(0.5)); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 175); // linea horizontal 1 cb.LineTo(60, top1 - 175); cb.MoveTo(oDoc.PageSize.Width - 20, 248); // linea horizontal 1 (DUPLICADO) cb.LineTo(60, 248); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 185); // linea horizontal 2 cb.LineTo(60, top1 - 185); cb.MoveTo(oDoc.PageSize.Width - 20, 238); // linea horizontal 2 (DUPLICADO) cb.LineTo(60, 238); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 319); // linea horizontal 3 cb.LineTo(60, top1 - 319); cb.MoveTo(oDoc.PageSize.Width - 20, 104); // linea horizontal 3 (DUPLICADO) cb.LineTo(60, 104); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 330); // linea horizontal 4 cb.LineTo(60, top1 - 330); cb.MoveTo(oDoc.PageSize.Width - 20, 93); // linea horizontal 4 (DUPLICADO) cb.LineTo(60, 93); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); cb.MoveTo(oDoc.PageSize.Width - 20, top1 - 350); // linea horizontal 5 cb.LineTo(60, top1 - 350); cb.MoveTo(oDoc.PageSize.Width - 20, 73); // linea horizontal 5 (DUPLICADO) cb.LineTo(60, 73); cb.SetColorStroke(new BaseColor(Color.Blue)); cb.Stroke(); //LLENA EL CUERPO CON LA BD Principal fp = new Principal(); HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/factura_pdf.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}▼{2}▼", Global.USUARIO_SIST, Global.Facturar, Global.Limite)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); //si hay error string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains(" 2) { //LOS DOS ÚLTIMOS string deci = VALORS.Substring(VALORS.Length - 2, 2); if (deci != "00")//SI NO ES CERO { string DECI_DOS = VALORS.Substring(VALORS.Length - 2, 2); TotalLet = TotalLet + " " + NumLet.enletras(DECI_DOS); } } // 1= Left, 2= Top cb.BeginText(); // SUBTOTALES: TÍTULO Y NUMEROS cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "SUBTOTALES " + (" " + Strings.Format(Global.SumExe, "0.##")).Substring((" " + Strings.Format(Global.SumExe, "0.##")).Length - 9, 9) + " " + (" " + Strings.Format(Global.Sum5, "0.##")).Substring((" " + Strings.Format(Global.Sum5, "0.##")).Length - 9, 9) + " " + (" " + Strings.Format(Global.Sum10, "0.##")).Substring((" " + Strings.Format(Global.Sum10, "0.##")).Length - 9, 9), (float)(61.5), (float)(top1 - 327), 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "SUBTOTALES " + (" " + Strings.Format(Global.SumExe, "0.##")).Substring((" " + Strings.Format(Global.SumExe, "0.##")).Length - 9, 9) + " " + (" " + Strings.Format(Global.Sum5, "0.##")).Substring((" " + Strings.Format(Global.Sum5, "0.##")).Length - 9, 9) + " " + (" " + Strings.Format(Global.Sum10, "0.##")).Substring((" " + Strings.Format(Global.Sum10, "0.##")).Length - 9, 9), (float)(61.5), (float)(top1 - 746), 0); cb.EndText(); // 1= Left, 2= Top cb.BeginText(); // TOTAL EN LETRAS Y NÚMEROS cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); //ORIGINAL cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, (TotalLet + "----------------------------------------------------------------------------------------------------").Substring(0, 88) + "| " + Global.SIMB_ + " " + TotalNumForM, (float)(61.5), (float)(top1 - 342), 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, (TotalLet + "----------------------------------------------------------------------------------------------------").Substring(0, 88) + "| " + Global.SIMB_ + " " + TotalNumForM, (float)(61.5), (float)(top1 - 761), 0); cb.EndText(); // 1= Left, 2= Top cb.BeginText(); // totales IVA y Total de IVA cb.SetColorFill(iTextSharp.text.BaseColor.BLACK); cb.SetFontAndSize(BaseFont.CreateFont(@"lucon.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8); //ORIGINA cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "LIQUIDACIÓN DEL IVA: IVA 5%: " + string.Format("{0:#,##0.##}", Global.Total_iva5) + " | IVA 10%: " + string.Format("{0:#,##0.##}", Global.Total_iva10) + " | TOTAL DEL IVA: " + string.Format("{0:#,##0.##}", Global.Total_Iva), (float)(61.5), (float)(top1 - 360), 0); //DUPLICADO cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "LIQUIDACIÓN DEL IVA: IVA 5%: " + string.Format("{0:#,##0.##}", Global.Total_iva5) + " | IVA 10%: " + string.Format("{0:#,##0.##}", Global.Total_iva10) + " | TOTAL DEL IVA: " + string.Format("{0:#,##0.##}", Global.Total_Iva), (float)(61.5), (float)(top1 - 779), 0); //MENSAJE EN LA FACTURA (ORIGINAL) if (Global.mJE_ == null) { Global.mJE_ = ""; } cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.mJE_, (float)(61.5), (float)(top1 - 373), 0); //MENSAJE EN LA FACTURA (DUPLICADO) cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Global.mJE_, (float)(61.5), (float)(top1 - 792), 0); cb.EndText(); pdfw.Flush(); oDoc.Close(); System.Diagnostics.Process.Start(@pdfgenerate);//MUESTRA LA FACTURA EN PDF //DESCONTAR STOCK, SÓLO EN EL CASO DE QUE EL CONTADOR SEA "1", PORQUE DEBE HACER ESTO UNA SOLA VEZ if (Global.CONTADOR_F == 1) { HttpWebRequest rq1 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/descontar_stock.php"); rq1.Method = "POST"; byte[] byteArray1 = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}", Global.USUARIO_SIST, Global.num_esta)); rq1.ContentType = "application/x-www-form-urlencoded"; rq1.ContentLength = byteArray1.Length; Stream stream1 = rq1.GetRequestStream(); stream1.Write(byteArray1, 0, byteArray1.Length); stream1.Close(); // WebResponse response1 = rq1.GetResponse(); stream1 = response1.GetResponseStream(); StreamReader reader1 = new StreamReader(stream1); string devuelve1 = reader1.ReadToEnd(); reader1.Close(); stream1.Close(); response1.Close(); string[] c1 = devuelve1.Split('▲'); if (c1[0].Length > 100) { //MENSAJE DE ERROR MessageBox.Show(devuelve1); } } //ACTUALIZA NÚMERO DE FACTURA if (Global.presu == 0)//SI NO ES PRESUPUESTO { string SQLFACT = "UPDATE CONFIG" + Global.NUM_caja + " SET NUM_FACT=NUM_FACT+1;"; SQLiteCommand CMD_NF = new SQLiteCommand(SQLFACT, Global.conexion); CMD_NF.ExecuteNonQuery(); } if (Global.presu == 0) { fv.RegistrarVenta();//INSERTA LOS DATOS DE VENTA A LA TABLA VENTAS (SI NO ES PRESUPUESTO) } fv.BorraTemporal();//BORRA LA TABLA TEMPORAL Global.Sum10 = 0; Global.Sum5 = 0; Global.SumExe = 0; Global.Total_Iva = 0; Global.Total_iva10 = 0; Global.Total_iva5 = 0; Global.TotalNum = 0; string UsuarioSist = Global.USUARIO_SIST; HttpWebRequest rq2 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/fact_consult_temp.php"); rq2.Method = "POST"; byte[] byteArray2 = Encoding.UTF8.GetBytes(string.Format("nu={0}", UsuarioSist)); rq2.ContentType = "application/x-www-form-urlencoded"; rq2.ContentLength = byteArray2.Length; Stream stream2 = rq2.GetRequestStream(); stream2.Write(byteArray2, 0, byteArray2.Length); stream2.Close(); // WebResponse response2 = rq2.GetResponse(); stream2 = response2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string devuelve2 = reader2.ReadToEnd(); reader2.Close(); stream2.Close(); response2.Close(); string[] c2 = devuelve2.Split('▲'); if (c2[0].Length > 100) { MessageBox.Show(devuelve2); } if (c2[0] == "SI") { //MessageBox.Show("SI"); Global.CONTADOR_F += 1; Facturar(); } else { //MessageBox.Show("NO"); Global.CONTADOR_F = 1; } //Global.Presupuestar = false; //fv.Limpiar(); return null; } } public static class Ticket_LPT { [DllImport("kernel32.dll", SetLastError = true)] static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); public static bool Print() { //CONSTRUYE EL DOCUMENTO A IMPRIMIR Ventas fv = new Ventas(); NumLet Nl = new NumLet(); //PROCESA DATOS PARA IMPRESIÓN //CONSULTAR NÚMERO DE FACTURA if (Global.num_esta == null) { Global.num_esta = "0"; } int num_esta_ = int.Parse(Global.num_esta); SQLiteDataReader RSnF = null; string SQLnF = "SELECT NUM_FACT FROM CONFIG" + Global.NUM_caja + ";"; SQLiteCommand CMDnF = new SQLiteCommand(SQLnF, Global.conexion); RSnF = CMDnF.ExecuteReader(); if (RSnF.HasRows == true) { RSnF.Read(); int num_fact_ = RSnF.GetInt32(0); Global.NUM_FACT = string.Format("{0:000}", num_esta_) + "-" + Global.NUM_caja + "-" + string.Format("{0:0000000}", num_fact_); } RSnF.Close(); //DESCONTAR STOCK HttpWebRequest rq1 = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/descontar_stock.php"); rq1.Method = "POST"; byte[] byteArray1 = Encoding.UTF8.GetBytes(string.Format("nu={0}▼{1}", Global.USUARIO_SIST, Global.num_esta)); rq1.ContentType = "application/x-www-form-urlencoded"; rq1.ContentLength = byteArray1.Length; Stream stream1 = rq1.GetRequestStream(); stream1.Write(byteArray1, 0, byteArray1.Length); stream1.Close(); // WebResponse response1 = rq1.GetResponse(); stream1 = response1.GetResponseStream(); StreamReader reader1 = new StreamReader(stream1); string devuelve1 = reader1.ReadToEnd(); reader1.Close(); stream1.Close(); response1.Close(); string[] c1 = devuelve1.Split('▲'); if (c1[0].Length > 100) { //MENSAJE DE ERROR MessageBox.Show(devuelve1); } //ARREGLO PARA CREAR TICKET bool nova = false; HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://" + Global._host + "/ecv/crear_ticket.php"); rq.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("nu={0}", Global.USUARIO_SIST)); rq.ContentType = "application/x-www-form-urlencoded"; rq.ContentLength = byteArray.Length; Stream stream = rq.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); // WebResponse response = rq.GetResponse(); stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string devuelve = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string resultado = devuelve.ToUpper(); bool re; re = resultado.Contains("WARNING"); if (re == true) { MessageBox.Show(devuelve); return nova; } string ultimo_operador = ""; if (devuelve != "") { var oper= devuelve.Split('↔'); var o = oper[0].Split('▲'); ultimo_operador = o[5]; } bool IsConnected = false; //CABECERA COMIENZA ASÍ DateTime fecha = DateTime.Now; string hoy = fecha.ToString("dd-MM-yyyy, HH:mm:ss"); string textImp; string cabecera; if (Global.autoimp == 1)//SI ES AUTOIMPRESOR LA CABECERA DEL TICKET... { cabecera = ".\n" + Global._nom_empresa + "\n" + "DE " + Global.Razon_EMPRESA + "\n" + "RUC " + Global.Ruc_EMPRESA + "\n" + "TIMBRADO " + Global.Timb_EMPRESA + "\n" + "VALIDO DESDE " + Global.validez + "\n" + Global.Direc_EMPRESA + "\n" + "TEL. " + Global.Tel_EMPRESA + "\n" + "."; } else//SI NO ES AUTOIMPRESOR LA CABECERA DEL TICKET... { cabecera = ".\n" + Global._nom_empresa + "\n" + Global.Razon_EMPRESA + "\n" + "RUC " + Global.Ruc_EMPRESA + "\n" + Global.Direc_EMPRESA + "\n" + "TEL. " + Global.Tel_EMPRESA + "\n" + "."; } if (Global.Puerto_Ticket != "USB")//SI ES LPT { if (Global.autoimp == 0) { //SI NO ES AUTOIMPRESOR textImp = "FECHA: " + hoy + "\n" + "CONDICION DE VENTA: " + Global.Condicion + "\n" + "CLIENTE: " + Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + "PEDIDO N.:" + Global.NUM_FACT + "\n" + "VENDEDOR:" + ultimo_operador + "\n" + "CAJA " + Global.NUM_caja + " " + Global.USUARIO_SIST + "\n" + "----------------------------------------" + "\n" + "CANT |ARTICULOS Y/O SER| PRECIO| MONTO" + "\n"; } else { //SI ES AUTOIMPRESOR textImp = "CONDICION DE VENTA: " + Global.Condicion + "\n" + "FACTURA No.:" + Global.NUM_FACT + "\n" + "CLIENTE: " + Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + "FECHA: " + hoy + "\n" + "VENDEDOR:" + ultimo_operador + "\n" + "CAJA " + Global.NUM_caja + " " + Global.USUARIO_SIST + "\n" + "----------------------------------------" + "\n" + "ARTICULOS |IVA|CANT | PRECIO| MONTO" + "\n"; } } else//SI ES USB { if (Global.autoimp == 0) { //SI NO ES AUTOIMPRESOR if (Global.Imp58mm == 0)//SI ES 75 MM { textImp = "FECHA: " + hoy + "\n" + "CONDICION DE VENTA: " + Global.Condicion + "\n" + "CLIENTE: " + Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + "PEDIDO No.:" + Global.NUM_FACT + "\n" + "VENDEDOR:" + ultimo_operador + "\n" + "CAJA " + Global.NUM_caja + " " + Global.USUARIO_SIST + "\n" + "----------------------------------------" + "\n" + "CANT |ARTICULOS Y/O SER| PRECIO| MONTO" + "\n"; } else//SI ES 58MM { textImp = cabecera + "\n" + "FECHA: " + hoy + "\n" + "CONDICION DE VENTA: " + Global.Condicion + "\n" + "CLIENTE: " + Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + "PEDIDO No.:" + Global.NUM_FACT + "\n" + "VENDEDOR:" + ultimo_operador + "\n" + "CAJA " + Global.NUM_caja + " " + Global.USUARIO_SIST + "\n" + "-----------------------------" + "\n" + "CANT |ARTICUL| PRECIO| MONTO" + "\n";//CANT:5, ART:7, PRECIO:7 MONTO7 } } else { //SI ES AUTOIMPRESOR textImp = "CONDICION DE VENTA: " + Global.Condicion + "\n" + "FACTURA No.:" + Global.NUM_FACT + "\n" + "CLIENTE: " + Global.RazonS + "\n" + "RUC: " + Global.RUC + "\n" + "FECHA: " + hoy + "\n" + "VENDEDOR:" + ultimo_operador + "\n" + "CAJA " + Global.NUM_caja + " " + Global.USUARIO_SIST + "\n" + "----------------------------------------" + "\n" + "ARTICULOS |IVA|CANT | PRECIO| MONTO" + "\n"; } } double TotalExento = 0; double Total5 = 0; double Total10 = 0; double TotalX = 0; string SimboloX = "", EntregaX= "", VueltoX=""; if (devuelve != "") { foreach (var line in devuelve.Split('↔')) { if (line == "")//si la última línea está vacía, continua al siguiente proceso { continue; } var v = line.Split('▲'); string Cantx = v[0] + " "; string Artx = v[1].ToUpper() + " " + " "; string Precx = " " + string.Format("{0:0.##}", float.Parse(v[2])); string Monx = " " + string.Format("{0:0.##}", float.Parse(v[3])); TotalX = double.Parse(Global.Totalx); SimboloX = Global.SIMB_; EntregaX = double.Parse(Global.Entregax).ToString("#,##0.##"); VueltoX = double.Parse(Global.Vueltox).ToString("#,##0.##"); if (Global.impFactEn == 2)//Facturar en moneda 2 { if (Global.operacion2 == "Multiplicar") { Precx = " " + string.Format("{0:0.##}", float.Parse(v[2]) * Global.valorMoneda2);//hoy 23/07/2024 Monx = " " + string.Format("{0:0.##}", float.Parse(v[3]) * Global.valorMoneda2);//hoy 23/07/2024 TotalX = double.Parse(Global.Totalx) * Global.valorMoneda2; SimboloX = Global.simboloMoneda2; EntregaX = (double.Parse(Global.Entregax) * Global.valorMoneda2).ToString("#,##0.##"); VueltoX = (double.Parse(Global.Vueltox) * Global.valorMoneda2).ToString("#,##0.##"); } if (Global.operacion2 == "Dividir") { Precx = " " + string.Format("{0:0.##}", float.Parse(v[2]) / Global.valorMoneda2);//hoy 23/07/2024 Monx = " " + string.Format("{0:0.##}", float.Parse(v[3]) / Global.valorMoneda2);//hoy 23/07/2024 TotalX = double.Parse(Global.Totalx) / Global.valorMoneda2; SimboloX = Global.simboloMoneda2; EntregaX = (double.Parse(Global.Entregax) / Global.valorMoneda2).ToString("#,##0.##"); VueltoX = (double.Parse(Global.Vueltox) / Global.valorMoneda2).ToString("#,##0.##"); } } if (Global.impFactEn == 3)//Facturar en moneda 3 { if (Global.operacion3 == "Multiplicar") { Precx = " " + string.Format("{0:0.##}", float.Parse(v[2]) * Global.valorMoneda3);//hoy 24/07/2024 Monx = " " + string.Format("{0:0.##}", float.Parse(v[3]) * Global.valorMoneda3);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) * Global.valorMoneda3; SimboloX = Global.simboloMoneda3; EntregaX = (double.Parse(Global.Entregax) * Global.valorMoneda3).ToString("#,##0.##"); VueltoX = (double.Parse(Global.Vueltox) * Global.valorMoneda3).ToString("#,##0.##"); } if (Global.operacion3 == "Dividir") { Precx = " " + string.Format("{0:0.##}", float.Parse(v[2]) / Global.valorMoneda3);//hoy 24/07/2024 Monx = " " + string.Format("{0:0.##}", float.Parse(v[3]) / Global.valorMoneda3);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) / Global.valorMoneda3; SimboloX = Global.simboloMoneda3; EntregaX = (double.Parse(Global.Entregax) / Global.valorMoneda3).ToString("#,##0.##"); VueltoX = (double.Parse(Global.Vueltox) / Global.valorMoneda3).ToString("#,##0.##"); } } if (Global.impFactEn == 4)//Facturar en moneda 4 { if (Global.operacion4 == "Multiplicar") { Precx = " " + string.Format("{0:0.##}", float.Parse(v[2]) * Global.valorMoneda4);//hoy 24/07/2024 Monx = " " + string.Format("{0:0.##}", float.Parse(v[3]) * Global.valorMoneda4);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) * Global.valorMoneda4; SimboloX = Global.simboloMoneda4; EntregaX = (double.Parse(Global.Entregax) * Global.valorMoneda4).ToString("#,##0.##"); VueltoX = (double.Parse(Global.Vueltox) * Global.valorMoneda4).ToString("#,##0.##"); } if (Global.operacion4 == "Dividir") { Precx = " " + string.Format("{0:0.##}", float.Parse(v[2]) / Global.valorMoneda4);//hoy 24/07/2024 Monx = " " + string.Format("{0:0.##}", float.Parse(v[3]) / Global.valorMoneda4);//hoy 24/07/2024 TotalX = double.Parse(Global.Totalx) / Global.valorMoneda4; SimboloX = Global.simboloMoneda4; EntregaX = (double.Parse(Global.Entregax) / Global.valorMoneda4).ToString("#,##0.##"); VueltoX = (double.Parse(Global.Vueltox) / Global.valorMoneda4).ToString("#,##0.##"); } } string IVA = string.Format("{0:00}", float.Parse(v[4])) + "%"; if (Global.Imp58mm == 0)//SI ES 75MM { //SI NO ES AUTOIMPRESOR if (Global.autoimp == 0) { textImp = textImp + Cantx.Substring(0, 5) + "|" + Artx.Substring(0, 17) + "|" + Precx.Substring(Precx.Length - 7, 7) + "|" + Monx.Substring(Monx.Length - 8, 8) + "\n"; } } else//SI ES 58MM { //SI NO ES AUTOIMPRESOR if (Global.autoimp == 0) { textImp = textImp + Cantx.Substring(0, 5) + "|" + Artx.Substring(0, 7) + "|" + Precx.Substring(Precx.Length - 7, 7) + "|" + Monx.Substring(Monx.Length - 7, 7) + "\n"; } } //SI ES AUTOIMPRESOR if (Global.autoimp == 1) { textImp = textImp + Artx.Substring(0, 14) + "|" + IVA + "|" + Cantx.Substring(0, 5) + "|" + Precx.Substring(Precx.Length - 7, 7) + "|" + Monx.Substring(Monx.Length - 7, 7) + "\n"; //EL TOTAL EXENTO DE IVA if (v[4] == "0") { TotalExento = TotalExento + double.Parse(v[3]); } //EL TOTAL IVA 5% if (v[4] == "5") { Total5 = Total5 + double.Parse(v[3]); } //EL TOTAL IVA 10% if (v[4] == "10") { Total10 = Total10 + double.Parse(v[3]); } } Global.altura = Global.altura + 12; } } //SI ES AUTOIMPRESOR if (Global.autoimp == 1) { double LI5 = Total5 / 21;//LIQUIDACIÓN DE IVA 5% double LI10 = Total10 / 11;//LIQUIDACIÓN DE IVA 10% textImp = textImp + "----------------------------------------\n" + "SUBTOTAL EXENTO: " + TotalExento + "\n" + "SUBTOTAL 5%: " + Total5 + "\n" + "SUBTOTAL 10%: " + Total10 + "\n" + "----------------------------------------\n" + "LIQUIDACION DEL IVA 5%: " + string.Format("{0:0.##}", LI5) + "\n" + "LIQUIDACION DEL IVA 10%: " + string.Format("{0:0.##}", LI10) + "\n" + "TOTAL DEL IVA: " + string.Format("{0:0.##}", (LI5 + LI10)) + "\n"; } string VALOR = double.Parse(Global.Totalx).ToString("0.00"); string DECIMAL = ""; if (Global.impFactEn == 2)//Facturar en moneda 2 { if (Global.operacion2 == "Multiplicar") { VALOR = (TotalX).ToString("0.00"); }//hoy 23/07/2024 if (Global.operacion2 == "Dividir") { VALOR = (TotalX).ToString("0.00"); }//hoy 23/07/2024 } if (VALOR.Substring(VALOR.Length - 2, 2) != "00") { DECIMAL = Nl.enletras(VALOR.Substring(VALOR.Length - 2, 2)); } string totalletras = "SON " + SimboloX + " " + Nl.enletras(TotalX.ToString("0.##")) + " " + DECIMAL; string totalL; if (Global.impFactEn == 2)//Facturar en moneda 2 { if (Global.operacion2 == "Multiplicar") { totalletras = "SON " + Global.simboloMoneda2 + " " + Nl.enletras((TotalX).ToString("0.##")) + " " + DECIMAL; }//hoy 23/07/2024 if (Global.operacion2 == "Dividir") { totalletras = "SON " + Global.simboloMoneda2 + " " + Nl.enletras((TotalX).ToString("0.##")) + " " + DECIMAL; }//hoy 23/07/2024 } if (totalletras.Length > 40) { totalL = totalletras.Substring(0, 40) + "\n" + totalletras.Substring(40, totalletras.Length - 40); } else { totalL = "SON " + SimboloX + " " + Nl.enletras((TotalX).ToString("0.##")) + " " + DECIMAL; if (Global.impFactEn == 2)//Facturar en moneda 2 { if (Global.operacion2 == "Multiplicar") { totalL = "SON " + Global.simboloMoneda2 + " " + Nl.enletras((TotalX).ToString("0.##")) + " " + DECIMAL; }//hoy 23/07/2024 if (Global.operacion2 == "Dividir") { totalL = "SON " + Global.simboloMoneda2 + " " + Nl.enletras((TotalX).ToString("0.##")) + " " + DECIMAL; }//hoy 23/07/2024 } } string sampleText; if (Global.Puerto_Ticket != "USB") //FINAL DE LA IMPRESIÓN SI ES LPT { sampleText = textImp + "----------------------------------------" + "\n" + totalL + "\n" + "TOTAL " + SimboloX + ": " + TotalX + "\n" + //SIN DECIMALE "ENTREGA " + SimboloX + ": " + string.Format("{0:#,##0.##}", EntregaX) + "\n" + "VUELTO " + SimboloX + ": " + VueltoX + "\n" + Global.mJE_ + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + Global._nom_empresa + "\n" + "DE " + Global.Razon_EMPRESA + "\n" + "RUC: " + Global.Ruc_EMPRESA + "\n" + //"TIMBRADO: " + Global.Timb_EMPRESA + "\n" + //"VALIDO DESDE" + Global.validez + "\n" + Global.Direc_EMPRESA + "\n" + "TEL. " + Global.Tel_EMPRESA + "\n"; } else //FINAL DE LA IMPRESIÓN SI ES USB { if (Global.Imp58mm == 0)//SI ES 75MM { if (Global.con_corte == 0)//SI ES SIN CORTE { sampleText = textImp + "----------------------------------------" + "\n" + totalL + "\n" + "TOTAL " + SimboloX + ": " + TotalX.ToString("0.##") + "\n" + //SIN DECIMALES "ENTREGA " + SimboloX + ": " + string.Format("{0:#,##0}", float.Parse(EntregaX)) + "\n" + "VUELTO " + SimboloX + ": " + VueltoX + "\n" + Global.mJE_ + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + cabecera; } else { //CON CORTE sampleText = cabecera + "\n" + textImp + "----------------------------------------" + "\n" + totalL + "\n" + "TOTAL " + SimboloX + ": " + TotalX.ToString("0.##") + "\n" + //SIN DECIMALES "ENTREGA " + SimboloX + ": " + string.Format("{0:#,##0}", EntregaX) + "\n" + "VUELTO " + SimboloX + ": " + VueltoX + "\n" + Global.mJE_ + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + "." + "\n" + "." + "\n"; } } else//SI ES 58MM { sampleText = textImp + "-----------------------------" + "\n" + totalL + "\n" + "TOTAL " + SimboloX + ": " + TotalX + "\n" + "ENTREGA " + SimboloX + ": " + string.Format("{0:#,##0.##}", float.Parse(EntregaX)) + "\n" + "VUELTO " + SimboloX + ": " + VueltoX + "\n" + "-----------------------------\n" + Global.mJE_ + "\n" + "." + "\n" + "."; } } //LA ORDEN DE IMPRESIÓN SE ENVÍA A LA IMPRESORA if (Global.Puerto_Ticket != "USB")//SI ES LPT { //CREA ARCHIVO Y GUARDAR string ruta = @"C:\\TICKET\" + Global.NUM_FACT + ".txt"; var escritor = new StreamWriter(ruta); escritor.WriteLine(sampleText); escritor.Close(); if (Global.no_imp_ticket == 0)//IMPRIMIR O NO TICKET { try {//ACÁ COMIENZA LA IMPRESIÓN REALMENTE Byte[] buffer = new byte[sampleText.Length]; buffer = System.Text.Encoding.ASCII.GetBytes(sampleText); SafeFileHandle fh = CreateFile(Global.Puerto_Ticket + ":", FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero); if (!fh.IsInvalid) { IsConnected = true; FileStream lpt1 = new FileStream(fh, FileAccess.ReadWrite); lpt1.Write(buffer, 0, buffer.Length); lpt1.Close(); } } catch (Exception ex) { string message = ex.Message; } if (Global.imp_2veces == 1)//IMPRESIÓN DOBLE { MessageBox.Show("Preparado para imprimir la segunda copia."); try {//ACÁ COMIENZA LA IMPRESIÓN REALMENTE Byte[] buffer = new byte[sampleText.Length]; buffer = System.Text.Encoding.ASCII.GetBytes(sampleText); SafeFileHandle fh = CreateFile(Global.Puerto_Ticket + ":", FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero); if (!fh.IsInvalid) { IsConnected = true; FileStream lpt1 = new FileStream(fh, FileAccess.ReadWrite); lpt1.Write(buffer, 0, buffer.Length); lpt1.Close(); } } catch (Exception ex) { string message = ex.Message; } } } } else//SI ES USB... { //CREA ARCHIVO Y GUARDAR string ruta = @"C:\\TICKET\" + Global.NUM_FACT + ".txt"; var escritor = new StreamWriter(ruta); escritor.WriteLine(sampleText); escritor.Close(); Global.T_Construido = sampleText; if (Global.BlocNota == 0)//SI NO ES CON BLOCK DE NOTAS { if (Global.no_imp_ticket == 0)//IMPRIMIR TICKET si es 0 { Ventas ventas = new Ventas();//LA NUEVA IMPRESIÓN (ESTÁ EN VENTAS) ventas.PrintTicket(); if (Global.imp_2veces == 1) { MessageBox.Show("Presione ENTER para la segunda impresión."); ventas.PrintTicket(); } } } else//IMPRIME CON BLOCK DE NOTA { if (Global.no_imp_ticket == 0)//IMPRIMIR TICKET si es 0 { //IMPRIME EL ARCHIVO CREADO ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "print"; // Seleccionar el programa para imprimir PDF por defecto info.FileName = ruta;//@"TICKET.TXT"; // Ruta hacia el fichero que quieres imprimir info.CreateNoWindow = true; // Hacerlo sin mostrar ventana info.WindowStyle = ProcessWindowStyle.Hidden; // Y de forma oculta Process p = new Process(); p.StartInfo = info; p.Start(); // Lanza el proceso try { p.WaitForInputIdle(); } catch { } System.Threading.Thread.Sleep(3000); // Espera 3 segundos //if (false == p.CloseMainWindow()) // p.Kill(); // Y cierra el programa de imprimir PDF's if (Global.imp_2veces == 1) { MessageBox.Show("Preparado para imprimir otra copia."); //IMPRIME EL ARCHIVO CREADO ProcessStartInfo info2 = new ProcessStartInfo(); info2.Verb = "print"; // Seleccionar el programa para imprimir PDF por defecto info2.FileName = ruta;//@"TICKET.TXT"; // Ruta hacia el fichero que quieres imprimir info2.CreateNoWindow = true; // Hacerlo sin mostrar ventana info2.WindowStyle = ProcessWindowStyle.Hidden; // Y de forma oculta Process p2 = new Process(); p2.StartInfo = info; p2.Start(); // Lanza el proceso p2.WaitForInputIdle(); System.Threading.Thread.Sleep(3000); } } } Global.altura = 0; } //ACTUALIZA NÚMERO DE FACTURA string SQLFACT = "UPDATE CONFIG" + Global.NUM_caja + " SET NUM_FACT=NUM_FACT+1;"; SQLiteCommand CMD_NF = new SQLiteCommand(SQLFACT, Global.conexion); CMD_NF.ExecuteNonQuery(); fv.RegistrarVenta();//INSERTA LOS DATOS DE VENTA A LA TABLA VENTAS fv.BorraTemporal();//BORRA LA TABLA TEMPORAL //fv.Limpiar(); VA EN CERRAR VENTA,de lo cotrario no se ejecuta pagaré //VUELVE A ABRIR VENTAS, PORQUE DESAPARECE AL IMPRIMIR EL TICKET Principal principal = new Principal(); principal.Boton4_Click(null, null); return IsConnected; } } }