Example #1
0
 public override Lfx.Types.OperationResult SolicitudEliminacion(Lbl.ListaIds codigos)
 {
     using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(@"Una vez anulados, los comprobantes deberán ser archivados en todas sus copias y no podrán ser rehabilitados ni reutilizados.", @"¿Está seguro de que desea anular?"))
     {
         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
         if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             int IdRemito = codigos[0];
             System.Data.IDbTransaction Trans = this.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable);
             System.Data.DataTable      Tabla = this.Connection.Select("select id_comprob from comprob where id_remito=" + IdRemito + " and anulada=0;");
             if (Tabla == null || Tabla.Rows.Count == 0)
             {
                 Lbl.Comprobantes.ComprobanteConArticulos Rem = new Lbl.Comprobantes.ComprobanteConArticulos(Connection, IdRemito);
                 if (Rem.Anulado == false)
                 {
                     Rem.Anular(false);
                     Trans.Commit();
                 }
             }
             else
             {
                 Lui.Forms.MessageBox.Show("No se puede anular si se encuentra relacionada con una factura", "¡Error!");
             }
         }
     }
     return(new Lfx.Types.SuccessOperationResult());
 }
Example #2
0
        public override void ActualizarElemento()
        {
            Lbl.Entidades.Moneda Mon = this.Elemento as Lbl.Entidades.Moneda;

            Mon.Nombre              = EntradaNombre.Text;
            Mon.Simbolo             = EntradaSigno.Text;
            Mon.NomenclaturaIso     = EntradaISO.Text;
            Mon.Cotizacion          = EntradaCotizacion.ValueDecimal;
            Mon.Decimales           = EntradaDecimales.ValueInt;
            Mon.ActualizarProductos = 0;


            Lfx.Data.Row RowProdConMoneda = this.Connection.FirstRowFromSelect("SELECT id_articulocotiza FROM articulos_cotiza WHERE id_moneda=" + Mon.Id + " AND estado=1");
            if (RowProdConMoneda != null)
            {
                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea actualizar los productos que cotizan con esta moneda?", "¿Actualización de Productos?");
                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                if (Pregunta.ShowDialog() == DialogResult.OK)
                {
                    Mon.ActualizarProductos = 1;
                    reiniciar = true;
                }
            }

            base.ActualizarElemento();
            //Lfx.Workspace.Master.RunTime.Execute("REBOOT");
        }
Example #3
0
 private Lfx.Types.OperationResult EditarPermisos()
 {
     if (Lui.LogOn.LogOnData.ValidateAccess(this.Elemento, Lbl.Sys.Permisos.Operaciones.Administrar))
     {
         if (this.Changed || this.Elemento.Existe == false)
         {
             Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Antes de editar los permisos debe guardar los cambios en este formulario. ¿Desea guardar ahora?", "Editar Permisos");
             Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
             if (this.Elemento.Existe)
             {
                 this.ShowChanged = true;
             }
             DialogResult Respuesta = Pregunta.ShowDialog();
             this.ShowChanged = false;
             if (Respuesta != DialogResult.OK)
             {
                 return(new Lfx.Types.CancelOperationResult());
             }
             else
             {
                 Lfx.Types.OperationResult ResultadoGuardar = this.Save();
                 if (ResultadoGuardar.Success == false)
                 {
                     return(ResultadoGuardar);
                 }
             }
         }
         Lfx.Workspace.Master.RunTime.Execute("EDITAR Lbl.Personas.Usuario " + this.Elemento.Id.ToString());
         return(new Lfx.Types.SuccessOperationResult());
     }
     else
     {
         return(new Lfx.Types.NoAccessOperationResult());
     }
 }
Example #4
0
        private void BotonArqueo_Click(object sender, System.EventArgs e)
        {
            if (this.Fechas.To < System.DateTime.Now)
            {
                Lfx.Workspace.Master.RunTime.Toast("La vista actual muestra el estado de la caja en una fecha pasada. No puede asentar un arqueo con una fecha pasada. Para asentar un arqueo cambie el filtro de fechas para ver el estado actual de la caja.", "Arqueo de caja");
                return;
            }
            else if (this.Caja == null)
            {
                Lfx.Workspace.Master.RunTime.Toast("La vista actual muestra los movimientos de varias cajas combinados. No se puede asentar un arqueo en este estado.", "Arqueo de caja");
                return;
            }
            else if (this.Cliente != null || this.Concepto != null || this.Direccion != 0)
            {
                Lfx.Workspace.Master.RunTime.Toast("La vista actual no muestra todos los movimientos de la caja ya que existe un filtro activo (filtro por Cliente, Concepto, etc.). Quite todos los filtros para poder asentar un arqueo.", "Arqueo de caja");
                return;
            }

            Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Confirma que el saldo de la caja de " + Lbl.Sys.Config.Moneda.Simbolo + " " + Lfx.Types.Formatting.FormatCurrency(this.Contadores[3].Total) + " corresponde con lo que se encuentra físicamente en la caja? Si confirma que el saldo de la cuenta es el indicado se asentará una marca de 'Arqueo', para su propio control.", "El saldo de la caja es de " + Lbl.Sys.Config.Moneda.Simbolo + "  " + Lfx.Types.Formatting.FormatCurrency(this.Contadores[3].Total));
            Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
            if (Pregunta.ShowDialog() == DialogResult.OK)
            {
                using (IDbTransaction Trans = this.Caja.Connection.BeginTransaction()) {
                    this.Caja.Arqueo();
                    Trans.Commit();
                }
                this.RefreshList();
            }
            else
            {
                Lui.Forms.MessageBox.Show("No se asentó un arqueo. Verifique el saldo de la cuenta y si es necesario realice un ajuste.", "Arqueo de caja");
            }
        }
Example #5
0
        private void TimerProgramador_Tick(object sender, EventArgs e)
        {
            TimerProgramador.Stop();

            if (this.Visible)
            {
                //Ejecuto tareas del programador
                Lfx.Services.Task ProximaTarea = null;
                // En conexiones lentas, 1 vez por minuto
                // En conexiones rápidas, cada 5 segundos
                if (Lfx.Workspace.Master.SlowLink)
                {
                    if (Lfx.Workspace.Master.DefaultScheduler.LastGetTask == System.DateTime.MinValue || (DateTime.Now - Lfx.Workspace.Master.DefaultScheduler.LastGetTask).Minutes >= 1)
                    {
                        ProximaTarea = Lfx.Workspace.Master.DefaultScheduler.GetNextTask("lazaro");
                    }
                }
                else
                {
                    if (Lfx.Workspace.Master.DefaultScheduler.LastGetTask == System.DateTime.MinValue || (DateTime.Now - Lfx.Workspace.Master.DefaultScheduler.LastGetTask).Seconds >= 5)
                    {
                        ProximaTarea = Lfx.Workspace.Master.DefaultScheduler.GetNextTask("lazaro");
                    }
                }

                if (ProximaTarea != null)
                {
                    // Lanzo la tarea en un nuevo thread
                    System.Threading.ThreadStart ParamInicio = delegate { Ejecutor.Exec(ProximaTarea.Command, ProximaTarea.ComputerName); };
                    new System.Threading.Thread(ParamInicio).Start();
                }

                if (YaSubiEstadisticas == false && Lfx.Workspace.Master.DebugMode == false)
                {
                    YaSubiEstadisticas = true;
                    System.Threading.ThreadStart ParamInicio = delegate { Aplicacion.EnviarEstadisticas(); };
                    System.Threading.Thread      Thr         = new System.Threading.Thread(ParamInicio);
                    Thr.IsBackground = true;
                    Thr.Start();
                }

                if (YaPregunteReiniciar == false && Lfx.Updates.Updater.Master != null && Lfx.Updates.Updater.Master.UpdatesPending() && ActiveForm == this)
                {
                    YaPregunteReiniciar = true;
                    Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Existe una nueva versión de Lázaro. Debe reiniciar la aplicación para instalar la actualización.", "¿Desea reiniciar ahora?");
                    Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                    DialogResult Respuesta = Pregunta.ShowDialog();
                    if (Respuesta == DialogResult.OK)
                    {
                        Ejecutor.Exec("REBOOT");
                    }
                }
            }

            TimerProgramador.Start();
        }
Example #6
0
        private void BotonPresentar_Click(object sender, EventArgs e)
        {
            if (Listado.CheckedItems.Count == 0)
            {
                Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para presentar.", "Acreditar");
                return;
            }

            int CantidadCupones = 0;

            foreach (System.Windows.Forms.ListViewItem itm in Listado.Items)
            {
                if (itm.Checked)
                {
                    CantidadCupones++;
                    if (itm.SubItems["tarjetas_cupones.estado"].Text != "Sin presentar")
                    {
                        Lui.Forms.MessageBox.Show("Sólo se pueden hacer presentaciones de cupones que no han sido presentados.", "Presentación de cupones");
                        return;
                    }
                }
            }

            if (CantidadCupones == 0)
            {
                Lui.Forms.MessageBox.Show("Debe seleccionar uno o más cupones para presentar.", "Presentación de cupones");
                return;
            }


            using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea marcar los cupones seleccionados como presentados?", "Presentación de cupones")) {
                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                if (Pregunta.ShowDialog() == DialogResult.OK)
                {
                    IDbTransaction Trans = Connection.BeginTransaction(IsolationLevel.Serializable);
                    Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Presentación de cupones", "Se están marcando los cupones seleccionados como 'Presentados'.");
                    Progreso.Max = CantidadCupones;
                    Progreso.Begin();
                    foreach (System.Windows.Forms.ListViewItem itm in Listado.Items)
                    {
                        if (itm.Checked)
                        {
                            Progreso.Advance(1);
                            Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text));
                            if (Cupon.Estado == 0)
                            {
                                Cupon.Presentar();
                            }
                        }
                    }
                    Progreso.End();
                    Trans.Commit();
                    this.RefreshList();
                }
            }
        }
Example #7
0
        private void BotonAnular_Click(object sender, System.EventArgs e)
        {
            if (Listado.CheckedItems.Count == 0)
            {
                Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para anular.", "Acreditar");
                return;
            }

            int CantidadCupones = 0;

            foreach (System.Windows.Forms.ListViewItem itm in Listado.Items)
            {
                if (itm.Checked)
                {
                    CantidadCupones++;
                    if (itm.SubItems["tarjetas_cupones.estado"].Text != "Sin presentar" && itm.SubItems["estado"].Text != "Presentado")
                    {
                        Lui.Forms.MessageBox.Show("Sólo se pueden anular cupones que no han sido acreditados o rechazados.", "Anular de cupones");
                        return;
                    }
                }
            }

            if (CantidadCupones == 0)
            {
                Lui.Forms.MessageBox.Show("Debe seleccionar uno o más cupones para anular.", "Anular de cupones");
                return;
            }


            using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea eliminar de manera permanente los cupones seleccionados?", "Anular cupones")) {
                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                if (Pregunta.ShowDialog() == DialogResult.OK)
                {
                    Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando cupones", "Se van a eleiminar los cupones seleccionados");
                    Progreso.Max = CantidadCupones;
                    Progreso.Begin();
                    foreach (System.Windows.Forms.ListViewItem itm in Listado.Items)
                    {
                        if (itm.Checked)
                        {
                            Progreso.Advance(1);
                            Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text));
                            if (Cupon.Estado == 0 || Cupon.Estado == 10)
                            {
                                Cupon.Anular();
                            }
                        }
                    }
                    Progreso.End();
                    this.RefreshList();
                }
            }
        }
Example #8
0
 private void AplicarActualizacion()
 {
         this.Close();
         if (Lfx.Updates.Updater.Master != null && Lfx.Updates.Updater.Master.UpdatesPending()) {
                 Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Se descargó una nueva versión de Lázaro. Debe reiniciar la aplicación para instalar la actualización.", "¿Desea reiniciar ahora?");
                 Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                 DialogResult Respuesta = Pregunta.ShowDialog();
                 if (Respuesta == DialogResult.OK)
                         Ejecutor.Exec("REBOOT");
         }
 }
Example #9
0
 private void BotonCambiarPais_Click(object sender, System.EventArgs e)
 {
     using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Al cambiar el país, Gestion777 cambiará varios ajustes del sistema como la moneda, las tasas del IVA y los tipos de comprobante. ¿Está seguro de que quiere cambiar el país?", "Cambiar país")) {
         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
         if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             EntradaPais.ReadOnly     = false;
             BotonCambiarPais.Visible = false;
             EntradaPais.Focus();
         }
     }
 }
Example #10
0
 private void AplicarActualizacion()
 {
     this.Close();
     if (Lfx.Updates.Updater.Master != null && Lfx.Updates.Updater.Master.UpdatesPending())
     {
         Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Se descargó una nueva versión de Lázaro. Debe reiniciar la aplicación para instalar la actualización.", "¿Desea reiniciar ahora?");
         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
         DialogResult Respuesta = Pregunta.ShowDialog();
         if (Respuesta == DialogResult.OK)
         {
             Ejecutor.Exec("REBOOT");
         }
     }
 }
Example #11
0
 private void BotonEliminar_Click(object sender, System.EventArgs e)
 {
     if (Listado.SelectedItems.Count > 0 && Listado.SelectedItems[0] != null)
     {
         string NombreCarpeta           = Listado.SelectedItems[0].Text;
         Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Puede eliminar una copia de seguridad antigua o que ya no sea de utilidad. Al eliminar una copia de seguridad no se modificarán los datos actualmente almacenados en el sistema, ni tampoco se impide que el sistema haga nuevas copias de seguridad.", "¿Desea eliminar la copia de seguridad seleccionada?");
         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
         if (Pregunta.ShowDialog() == DialogResult.OK)
         {
             this.BackupManager.Delete(NombreCarpeta);
             MostrarListaBackups();
         }
     }
 }
Example #12
0
 private void dgvRubro_CellClick(object sender, DataGridViewCellEventArgs e)
 {
     if (dgvRubro.Columns[e.ColumnIndex].Name == "cg_Anular")
     {
         Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea anular el descuento?", "Se anulara el descuento");
         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
         DialogResult Respuesta = Pregunta.ShowDialog();
         if (Respuesta == DialogResult.OK)
         {
             dgvRubro.Rows[e.RowIndex].Cells["cg_Estado"].Value = "Anulado";
             DataGridViewCellStyle style = new DataGridViewCellStyle();
             style.BackColor = System.Drawing.Color.Red;
             dgvRubro.Rows[e.RowIndex].DefaultCellStyle = style;
         }
     }
 }
Example #13
0
 private void DepositarPagar_Click(object sender, System.EventArgs e)
 {
     if (this.Emitidos == false)
     {
         //Depositar
         Lbl.ListaIds Codigos = this.CodigosSeleccionados;
         if (Codigos == null || Codigos.Count == 0)
         {
             Lui.Forms.MessageBox.Show("Por favor seleccione uno o más cheques.", "Error");
         }
         else
         {
             Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Al depositar un cheque en una cuenta bancaria propia, puede marcarlo como depositado para control interno.\nSirve sólamente para depositos en cajas propias. Para depósitos en cajas de terceros utilice la opción 'Efectivizar'.", "¿Desea marcar los cheques seleccionados como depositados?");
             if (Pregunta.ShowDialog() == DialogResult.OK)
             {
                 using (IDbTransaction Trans = this.Connection.BeginTransaction()) {
                     qGen.Update Depo = new qGen.Update("bancos_cheques");
                     Depo.ColumnValues.AddWithValue("estado", 5);
                     Depo.WhereClause = new qGen.Where();
                     Depo.WhereClause.AddWithValue("estado", 0);
                     Depo.WhereClause.AddWithValue("id_cheque", qGen.ComparisonOperators.In, Codigos);
                     this.Connection.ExecuteNonQuery(Depo);
                     Trans.Commit();
                 }
                 foreach (System.Windows.Forms.ListViewItem itm in Listado.Items)
                 {
                     if (itm.Checked)
                     {
                         itm.Checked = false;
                     }
                 }
                 this.RefreshList();
             }
         }
     }
     else
     {
         Lfx.Types.OperationResult Res = this.Pagar();
         if (Res.Success == false && Res.Message != null)
         {
             Lfx.Workspace.Master.RunTime.Toast(Res.Message, "Error");
         }
     }
 }
Example #14
0
        public override Lfx.Types.OperationResult Ok()
        {
            int PV       = EntradaPV.ValueInt;
            int Desde    = EntradaDesde.ValueInt;
            int Hasta    = EntradaHasta.ValueInt;
            int Cantidad = Hasta - Desde + 1;

            int DesdeReal, HastaReal;

            if (EntradaOrden.TextKey == "1")
            {
                DesdeReal = Hasta;
                HastaReal = Desde - 1;
            }
            else
            {
                DesdeReal = Desde;
                HastaReal = Hasta + 1;
            }

            Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Por favor verifique que impresora tenga " + Cantidad.ToString() + " comprobantes, iniciando con el Nº " + PV.ToString("0000") + "-" + DesdeReal.ToString("00000000"), "¿Está seguro de que desea reimprimir " + Cantidad.ToString() + " comprobantes?");
            Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

            if (Pregunta.ShowDialog() == DialogResult.OK)
            {
                System.Threading.ThreadStart ThreadFiltro = delegate { ProcesarReimpresion(EntradaTipo.TextKey, PV, DesdeReal, HastaReal);; };
                System.Threading.Thread      Thr          = new System.Threading.Thread(ThreadFiltro);
                Thr.IsBackground = true;
                Thr.Start();

                ProximosNumeros.Clear();

                EntradaDesde.Text = "0";
                EntradaHasta.Text = "0";
                EntradaDesde.Focus();

                return(new Lfx.Types.CancelOperationResult());
            }
            else
            {
                return(new Lfx.Types.FailureOperationResult("La operación fue cancelada."));
            }
        }
Example #15
0
        public override Lfx.Types.OperationResult Ok()
        {
            if (Lui.LogOn.LogOnData.ValidateAccess(typeof(Lbl.Comprobantes.Recibo), Lbl.Sys.Permisos.Operaciones.Eliminar) == false)
            {
                return(new Lfx.Types.NoAccessOperationResult());
            }

            Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Una vez anulado, el comprobante deberá ser archivado en todas sus copias y no podrá ser rehabilitado ni reutilizado.", "¿Está seguro de que desea anular el comprobante?");
            Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

            if (Pregunta.ShowDialog() == DialogResult.OK)
            {
                int Numero = Lfx.Types.Parsing.ParseInt(EntradaNumero.Text);
                int PV     = Lfx.Types.Parsing.ParseInt(EntradaPV.Text);
                Lbl.Comprobantes.Recibo Rec = null;

                int IdRecibo = 0;
                if (Numero > 0)
                {
                    IdRecibo = this.Connection.FieldInt("SELECT id_recibo FROM recibos WHERE tipo_fac='" + EntradaTipo.TextKey + "' AND pv=" + PV.ToString() + " AND numero=" + Numero.ToString());
                }
                if (IdRecibo != 0)
                {
                    Rec = new Lbl.Comprobantes.Recibo(this.Connection, IdRecibo);
                }

                if (Rec != null && Rec.Existe)
                {
                    IDbTransaction Trans = Rec.Connection.BeginTransaction(IsolationLevel.Serializable);
                    Rec.Anular();
                    Trans.Commit();
                }

                EntradaNumero.Text = "";
                EntradaNumero.Focus();

                return(new Lfx.Types.SuccessOperationResult());
            }
            else
            {
                return(new Lfx.Types.CancelOperationResult());
            }
        }
Example #16
0
 private void btnEstructura_Click(object sender, System.EventArgs e)
 {
     using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(@"¡Atención! Esto puede generar inconvenientes. Responda 'Sí' sólamente si es la primera vez que utiliza Gestión777 o está restaurando desde una copia de seguridad.", @"¿Desea preparar el almacén de datos?"))
     {
         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
         if (Pregunta.ShowDialog() == DialogResult.OK)
         {
             Lfx.Types.OperationResult Res;
             using (var Connection = Lfx.Workspace.Master.GetNewConnection("Preparar almacén de datos") as Lfx.Data.Connection)
             {
                 Connection.RequiresTransaction = false;
                 Res = Lfx.Workspace.Master.Prepare(null);
             }
             if (Res.Success == false)
             {
                 return;
             }
         }
     }
 }
Example #17
0
 private void EntradaMoneda_TextChanged(object sender, EventArgs e)
 {
     if (EntradaMoneda.Enabled && EntradaMoneda.Elemento != null)
     {
         Lui.Forms.YesNoDialog msj = new Lui.Forms.YesNoDialog("¿Desea cotizar moneda a valor del proveedor?.\nSi presiona \"No\" toma el valor de la moneda predeterminado. ", "Forma de cotizar");
         Lfx.Data.Row          rowCotiza;
         if (msj.ShowDialog() == DialogResult.Yes)
         {
             rowCotiza = this.Connection.FirstRowFromSelect("SELECT cotiza as cotizacion FROM personas_cotiza WHERE id_persona=" + this.EntradaProveedor.Elemento.Id.ToString() + " and estado=1 and id_moneda=" + this.EntradaMoneda.Elemento.Id.ToString() + " order by id_personacotiza desc");
         }
         else
         {
             rowCotiza = this.Connection.FirstRowFromSelect("SELECT cotizacion FROM monedas WHERE id_moneda=" + this.EntradaMoneda.Elemento.Id.ToString());
         }
         if (rowCotiza != null)
         {
             EntradaCotiza.ValueDecimal = Convert.ToDecimal(rowCotiza["cotizacion"]);
         }
         EntradaCotiza.Focus();
     }
 }
Example #18
0
        public override Lfx.Types.OperationResult ValidarControl()
        {
            if (EntradaContrasena.Text.Length > 0)
            {
                if (EntradaContrasena.Text.Length < 6 || EntradaContrasena.Text.Length > 32)
                {
                    return(new Lfx.Types.FailureOperationResult("La contraseña debe tener entre 6 y 32 caracteres"));
                }
            }

            if (Listado.Items.Count == 0)
            {
                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("El usuario no tiene ningún permiso asignado y por lo tanto no podrá operar con el sistema. ¿Desea continuar de todos modos?", "Permisos");
                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                if (Pregunta.ShowDialog() != DialogResult.OK)
                {
                    return(new Lfx.Types.FailureOperationResult("Debe asignar al menos un permiso al usuario. Utilice la tecla 'Agregar' (F6) para asignar uno o más permisos."));
                }
            }

            return(base.ValidarControl());
        }
Example #19
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (this.GetControlsChanged(this.Controls))
            {
                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Si cierra el formulario en este momento, no se guardarán los cambios realizados (subrayados en color rojo). ¿Desea cerrar el formulario de todos modos y perder los cambios realizados?", "Hay cambios sin guardar");
                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                this.ShowChanged = true;
                DialogResult Res = Pregunta.ShowDialog();
                this.ShowChanged = false;

                if (Res == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    e.Cancel = false;
                }
            }
            base.OnFormClosing(e);
        }
Example #20
0
                private void Imprimir()
                {
                        Lfx.Types.OperationResult Res;
                        if (this.ReadOnly) {
                                Res = new Lfx.Types.SuccessOperationResult();
                        } else {
                                if (this.Elemento.Existe == false) {
                                        // Si es nuevo, lo guardo sin preguntar.
                                        Res = this.Save();
                                } else if (this.Changed) {
                                        // Si es edición, y hay cambios, pregunto si quiere guardar
                                        using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Hay modificaciones sin guardar (subrayadas en color rojo). Antes de imprimir el ducumento se guardarán las modificaciones. ¿Desea continuar?", "Imprimir")) {
                                                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                                this.ShowChanged = true;
                                                if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                                                        Res = this.Save();
                                                } else {
                                                        Res = new Lfx.Types.CancelOperationResult();
                                                }
                                                this.ShowChanged = false;
                                        }
                                } else {
                                        // Es edición y no hay cambios... continúo
                                        Res = new Lfx.Types.SuccessOperationResult();
                                }
                        }

                        if (Res.Success)
                                Res = this.ControlUnico.BeforePrint();

                        if (Res.Success) {
                                Lbl.Impresion.Impresora Impresora = null;
                                if ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) == Keys.Shift) {
                                        using (Lui.Printing.PrinterSelectionDialog FormularioSeleccionarImpresora = new Lui.Printing.PrinterSelectionDialog()) {
                                                if (FormularioSeleccionarImpresora.ShowDialog() == DialogResult.OK) {
                                                        Impresora = FormularioSeleccionarImpresora.SelectedPrinter;
                                                } else {
                                                        return;
                                                }
                                        }
                                }

                                string NombreDocumento = Elemento.ToString();
                                Lbl.Impresion.CargasPapel Carga = Lbl.Impresion.CargasPapel.Automatica;
                                if (Impresora != null && Impresora.CargaPapel == Lbl.Impresion.CargasPapel.Manual) {
                                        Carga = Lbl.Impresion.CargasPapel.Manual;
                                } else if (this.Elemento is Lbl.Comprobantes.ComprobanteConArticulos) {
                                        Lbl.Comprobantes.ComprobanteConArticulos Comprob = this.Elemento as Lbl.Comprobantes.ComprobanteConArticulos;

                                        if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero[Comprob.PV].Tipo == Lbl.Comprobantes.TipoPv.Fiscal) {
                                                Carga = Lbl.Impresion.CargasPapel.Automatica;
                                        } else {
                                                // El tipo de comprobante puede forzar a una carga manual
                                                Carga = Comprob.Tipo.CargaPapel;

                                                // Intento averiguar el número de comprobante, en caso de que aun no esté numerado
                                                if (Comprob.Numero == 0) {
                                                        int ProximoNumero = Lbl.Comprobantes.Numerador.ProximoNumero(Comprob);
                                                        NombreDocumento = NombreDocumento.Replace("00000000", ProximoNumero.ToString("00000000"));
                                                }
                                        }
                                }

                                if (Carga == Lbl.Impresion.CargasPapel.Manual) {
                                        using (Lui.Printing.ManualFeedDialog FormularioCargaManual = new Lui.Printing.ManualFeedDialog()) {
                                                FormularioCargaManual.DocumentName = NombreDocumento;
                                                // Muestro el nombre de la impresora
                                                if (Impresora != null) {
                                                        FormularioCargaManual.PrinterName = Impresora.Nombre;
                                                } else {
                                                        System.Drawing.Printing.PrinterSettings ObjPrint = new System.Drawing.Printing.PrinterSettings();
                                                        FormularioCargaManual.PrinterName = ObjPrint.PrinterName;
                                                }
                                                if (FormularioCargaManual.ShowDialog() == DialogResult.Cancel)
                                                        return;
                                        }
                                }

                                if (Impresora != null && Impresora.EsVistaPrevia) {
                                        Lazaro.Impresion.ImpresorElemento ImpresorVistaPrevia = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, null);
                                        ImpresorVistaPrevia.PrintController = new System.Drawing.Printing.PreviewPrintController();
                                        Lui.Printing.PrintPreviewForm VistaPrevia = new Lui.Printing.PrintPreviewForm();
                                        VistaPrevia.MdiParent = this.ParentForm.MdiParent;
                                        VistaPrevia.PrintPreview.Document = ImpresorVistaPrevia;
                                        VistaPrevia.Show();
                                } else {
                                        Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Imprimiendo", "El documento se está enviando a la impresora.");
                                        if (Impresora != null)
                                                Progreso.Description = "El documento se está enviando a la impresora " + Impresora.ToString();
                                        Progreso.Modal = false;
                                        Progreso.Begin();

                                        using (IDbTransaction Trans = this.Elemento.Connection.BeginTransaction()) {
                                                Lazaro.Impresion.ImpresorElemento Impresor = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, Trans);
                                                Impresor.Impresora = Impresora;
                                                try {
                                                        Res = Impresor.Imprimir();
                                                } catch (Exception ex) {
                                                        Res = new Lfx.Types.FailureOperationResult(ex.Message);
                                                }
                                                Progreso.End();
                                                if (Res.Success == false) {
                                                        if (Impresor.Transaction != null)
                                                                // Puede que la transacción ya haya sido finalizada por el impresor
                                                                Impresor.Transaction.Rollback();
                                                        Lui.Forms.MessageBox.Show(Res.Message, "Error");
                                                } else {
                                                        if (Impresor.Transaction != null)
                                                                // Puede que la transacción ya haya sido finalizada por el impresor
                                                                Impresor.Transaction.Commit();
                                                        this.Elemento.Cargar();
                                                        this.FromRow(this.Elemento);
                                                        this.ControlUnico.AfterPrint();
                                                }
                                        }
                                }
                        } 
                        
                        if (Res.Success == false && Res.Message != null) {
                                Lui.Forms.MessageBox.Show(Res.Message, "Imprimir");
                        }
                }
Example #21
0
        public override Lfx.Types.OperationResult ValidarControl()
        {
            if (EntradaTipo.ValueInt <= 0)
            {
                return(new Lfx.Types.FailureOperationResult("Seleccione el tipo de cliente"));
            }

            Lbl.Personas.Persona Cliente = this.Elemento as Lbl.Personas.Persona;

            if (EntradaNombreFantasia.Text.Length > 0 && EntradaRazonSocial.Text.Length == 0)
            {
                return(new Lfx.Types.FailureOperationResult("Escriba la razón social"));
            }

            if (EntradaRazonSocial.Text.Length == 0 && EntradaNombre.Text.Length == 0 && EntradaApellido.Text.Length == 0)
            {
                return(new Lfx.Types.FailureOperationResult("Escriba el nombre y el apellido o la razón social"));
            }
            else
            {
                //Busco un cliente con datos similares
                Lfx.Data.Row ClienteDup = null;
                string       Sql        = @"SELECT id_persona, nombre_visible, domicilio, telefono, cuit, email FROM personas WHERE (";
                if (this.Text.Length > 0)
                {
                    Sql += @"nombre_visible LIKE '%" + this.Connection.EscapeString(this.Text.Replace("%", "").Replace("_", "")) + @"%'";
                }
                if (EntradaDomicilio.Text.Length > 0)
                {
                    Sql += @" OR domicilio LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaDomicilio.Text) + @"%'";
                }

                if (EntradaNumDoc.Text.Length > 0)
                {
                    Sql += @" OR REPLACE(num_doc, '.', '') LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaNumDoc.Text.Replace(".", "")) + @"%'";
                }

                if (EntradaTelefono.Text.Length > 0)
                {
                    string         Telefono  = EntradaTelefono.Text.Replace(" -", "").Replace("- ", "").Replace("/", " ").Replace(",", " ").Replace(".", " ").Replace("  ", " ").Replace("%", "").Replace("_", "");
                    IList <string> Telefonos = Lfx.Types.Strings.SplitDelimitedString(Telefono, ";");
                    if (Telefonos != null && Telefonos.Count > 0)
                    {
                        foreach (string Tel in Telefonos)
                        {
                            if (Tel != null && Tel.Length > 4)
                            {
                                Sql += @" OR telefono LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(Tel.Replace("%", "").Replace("_", "")) + @"%'";
                            }
                        }
                    }
                }
                if (EntradaEmail.Text.Length > 0)
                {
                    Sql += @" OR email LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaEmail.Text.Replace("%", "").Replace("_", "")) + @"%'";
                }
                if (EntradaClaveTributaria.Text.Length > 0)
                {
                    Sql += @" OR cuit='" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaClaveTributaria.Text.Replace("%", "").Replace("_", "")) + @"'";
                }
                Sql += @") AND id_persona<>" + this.Elemento.Id.ToString();

                ClienteDup = this.Connection.FirstRowFromSelect(Sql);
                if (ClienteDup != null)
                {
                    if (Cliente != null && Cliente.Existe == false)
                    {
                        AltaDuplicada FormAltaDuplicada = new AltaDuplicada();
                        ListViewItem  itm;
                        itm = FormAltaDuplicada.ListaComparacion.Items.Add("Nombre");
                        itm.SubItems.Add(ClienteDup["nombre_visible"].ToString());
                        itm.SubItems.Add(this.Text);
                        itm = FormAltaDuplicada.ListaComparacion.Items.Add("Domicilio");
                        itm.SubItems.Add(ClienteDup["domicilio"].ToString());
                        itm.SubItems.Add(EntradaDomicilio.Text);
                        itm = FormAltaDuplicada.ListaComparacion.Items.Add("Teléfono");
                        itm.SubItems.Add(ClienteDup["telefono"].ToString());
                        itm.SubItems.Add(EntradaTelefono.Text);
                        itm = FormAltaDuplicada.ListaComparacion.Items.Add(Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre);
                        if (ClienteDup["cuit"] != null)
                        {
                            itm.SubItems.Add(ClienteDup["cuit"].ToString());
                        }
                        else
                        {
                            itm.SubItems.Add("");
                        }
                        itm.SubItems.Add(EntradaClaveTributaria.Text);
                        itm = FormAltaDuplicada.ListaComparacion.Items.Add("E-mail");
                        if (ClienteDup["email"] != null)
                        {
                            itm.SubItems.Add(ClienteDup["email"].ToString());
                        }
                        else
                        {
                            itm.SubItems.Add("");
                        }
                        itm.SubItems.Add(EntradaEmail.Text);

                        switch (FormAltaDuplicada.ShowDialog())
                        {
                        case DialogResult.Yes:
                            //Crear uno nuevo
                            return(new Lfx.Types.SuccessOperationResult());

                        case DialogResult.No:
                            //Actualizar
                            this.Elemento = new Lbl.Personas.Persona(this.Elemento.Connection, System.Convert.ToInt32(ClienteDup["id_persona"]));
                            return(new Lfx.Types.SuccessOperationResult());

                        case DialogResult.Cancel:
                            //Volver a la edición
                            return(new Lfx.Types.CancelOperationResult());
                        }
                    }
                }
            }

            switch (Lbl.Sys.Config.Pais.ClaveBancaria.Nombre)
            {
            case "CBU":
                if (EntradaClaveBancaria.Text.Length > 0 && Lbl.Bancos.Claves.Cbu.EsValido(EntradaClaveBancaria.Text) == false)
                {
                    return(new Lfx.Types.FailureOperationResult("La CBU es incorrecta."));
                }
                break;
            }


            if (Cliente.Existe == false && Cliente.Grupo != null && Cliente.Grupo.Id == 2 && (EntradaClaveBancaria.Text.Length > 0 || EntradaNumeroCuenta.Text.Length > 0) && EntradaTipoCuenta.TextKey == "0")
            {
                return(new Lfx.Types.FailureOperationResult("Por favor seleccione el tipo de cuenta bancaria."));
            }


            if (Lbl.Sys.Config.Pais.ClavePersonasJuridicas != null)
            {
                switch (Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre)
                {
                case "CUIT":
                    if (EntradaClaveTributaria.Text.Length > 0)
                    {
                        if (EntradaSituacion.ValueInt == 1)
                        {
                            return(new Lfx.Types.FailureOperationResult(@"Un Cliente con CUIT no debe estar en Situación de ""Consumidor Final""."));
                        }
                        if (System.Text.RegularExpressions.Regex.IsMatch(EntradaClaveTributaria.Text, @"^\d{11}$"))
                        {
                            EntradaClaveTributaria.Text = EntradaClaveTributaria.Text.Substring(0, 2) + "-" + EntradaClaveTributaria.Text.Substring(2, 8) + "-" + EntradaClaveTributaria.Text.Substring(10, 1);
                        }

                        //Agrego los guiones si no los tiene
                        if (EntradaClaveTributaria.Text.Length == 11)
                        {
                            EntradaClaveTributaria.Text = EntradaClaveTributaria.Text.Substring(0, 2) + "-" + EntradaClaveTributaria.Text.Substring(2, 8) + "-" + EntradaClaveTributaria.Text.Substring(10, 1);
                        }

                        if (Lbl.Personas.Claves.Cuit.EsValido(EntradaClaveTributaria.Text) == false)
                        {
                            return(new Lfx.Types.FailureOperationResult("La CUIT no es correcta." + Environment.NewLine + "El sistema le permite dejar la CUIT en blanco, pero no aceptará una incorrecta."));
                        }
                    }
                    break;
                }
            }

            if (EntradaClaveTributaria.Text.Length > 0)
            {
                Lfx.Data.Row RowPersMismaClave = this.Connection.FirstRowFromSelect("SELECT id_persona FROM personas WHERE cuit='" + EntradaClaveTributaria.Text + "' AND id_persona<>" + this.Elemento.Id.ToString());
                if (RowPersMismaClave != null)
                {
                    if (Cliente.Existe == false || System.Convert.ToInt32(RowPersMismaClave["id_persona"]) != this.Elemento.Id)
                    {
                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Ya existe una empresa o persona con esa clave tributaria (" + Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre + ") en la base de datos. ¿Desea continuar y crear una nueva de todos modos?", "Clave tributaria duplicada");
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                        if (Pregunta.ShowDialog() != DialogResult.OK)
                        {
                            return(new Lfx.Types.FailureOperationResult("Cambie la Clave tributaria (" + Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre + ") para antes de continuar."));
                        }
                    }
                }
            }

            return(new Lfx.Types.SuccessOperationResult());
        }
Example #22
0
                private Lfx.Types.OperationResult Facturar()
                {
                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea guardar los cambios realizados y generar una factura a partir de esta tarea?", "Facturar");
                        if (Pregunta.ShowDialog() != DialogResult.OK)
                                return new Lfx.Types.CancelOperationResult();

                        if (EntradaEstado.ValueInt < 50)
                                EntradaEstado.ValueInt = 50;

                        Lfx.Types.OperationResult Res = this.Save();
                        if (Res.Success == false)
                                return Res;

                        Lbl.Tareas.Tarea Tarea = this.Elemento as Lbl.Tareas.Tarea;
                        Lbl.Comprobantes.ComprobanteFacturable Factura;

                        Lfx.Data.Connection ConnFacturaNueva = Lfx.Workspace.Master.GetNewConnection("Convertir tarea en factura");

                        if (Tarea.Factura != null && Tarea.Factura.Anulado == false) {
                                // Ya fue facturada... lo muestro
                                Factura = Tarea.Factura;
                        } else {
                                // No tiene comprobante, lo creo
                                Factura = new Lbl.Comprobantes.Factura(ConnFacturaNueva);

                                Factura.Crear();
                                Factura.Cliente = EntradaCliente.Elemento as Lbl.Personas.Persona;
                                Factura.Cliente.Connection = ConnFacturaNueva;
                                Factura.Tipo = Factura.Cliente.ObtenerTipoComprobante();
                                Factura.Tipo.Connection = ConnFacturaNueva;
                                Factura.Vendedor = EntradaEncargado.Elemento as Lbl.Personas.Persona;
                                Factura.Vendedor.Connection = ConnFacturaNueva;
                                Factura.Obs = EntradaTarea.TextDetail + " s/" + this.Elemento.ToString();
                                if (Tarea.Articulos.Count > 0) {
                                        Factura.Articulos.AddRange(Tarea.Articulos);
                                } else if (Tarea.Presupuesto != null && Tarea.Presupuesto.Articulos.Count > 0) {
                                        Factura.Articulos.AddRange(Tarea.Presupuesto.Articulos);
                                        Factura.Descuento = Tarea.Presupuesto.Descuento;
                                }

                                if (EntradaImportePresupuesto.ValueDecimal > 0) {
                                        Lbl.Comprobantes.DetalleArticulo Art = new Lbl.Comprobantes.DetalleArticulo(Factura);

                                        Art.Nombre = this.Elemento.ToString();
                                        Art.Unitario = EntradaImportePresupuesto.ValueDecimal;
                                        Art.Cantidad = 1;

                                        Factura.Articulos.Add(Art);
                                }
                        }

                        Lfc.FormularioEdicion FormularioFactura = Lfc.Instanciador.InstanciarFormularioEdicion(Factura);
                        FormularioFactura.MdiParent = this.ParentForm.MdiParent;        
                        FormularioFactura.ControlDestino = EntradaComprobanteId;

                        FormularioFactura.Show();
                        return new Lfx.Types.SuccessOperationResult();
                }
Example #23
0
        /// <summary>
        /// Inicia una conexión con la base de datos y verifica si la versión de la la misma es la última disponible. En caso contrario la actualiza.
        /// </summary>
        internal static Lfx.Types.OperationResult AbrirConexion()
        {
            Lfx.Types.OperationResult iniciarReturn = new Lfx.Types.SuccessOperationResult();

            //Si el servidor SQL es esta misma PC, intento iniciar el servidor
            if (Lfx.Environment.SystemInformation.Platform == Lfx.Environment.SystemInformation.Platforms.Windows && Lfx.Workspace.Master.ConnectionParameters.ServerName.ToUpperInvariant() == "LOCALHOST")
            {
                switch (Lfx.Data.DatabaseCache.DefaultCache.AccessMode)
                {
                case Lfx.Data.AccessModes.MySql:
                    Lfx.Environment.Shell.Execute("net", "start mysql", ProcessWindowStyle.Hidden, true);
                    break;

                case Lfx.Data.AccessModes.Npgsql:
                    // FIXME: detectar el nombre del servicio.
                    Lfx.Environment.Shell.Execute("net", "start postgresql-9.0", ProcessWindowStyle.Hidden, true);
                    break;
                }
            }

            try
            {
                Lfx.Workspace.Master.MasterConnection.Open();
            }
            catch (Exception ex)
            {
                return(new Lfx.Types.FailureOperationResult(ex.Message));
            }

            if (Lfx.Workspace.Master.IsPrepared() == false)
            {
                using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(@"Aparentemente es la primera vez que utiliza este almacén de datos. Antes de poder utilizarlo debe prepararlo con una carga inicial de datos.
Responda 'Sí' sólamente si es la primera vez que utiliza Gestión o está restaurando desde una copia de seguridad.", @"¿Desea preparar el almacén de datos?"))
                {
                    Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                    if (Pregunta.ShowDialog() == DialogResult.OK)
                    {
                        Lfx.Types.OperationResult Res;
                        using (var Connection = Lfx.Workspace.Master.GetNewConnection("Preparar almacén de datos") as Lfx.Data.Connection)
                        {
                            Connection.RequiresTransaction = false;
                            Res = Lfx.Workspace.Master.Prepare(null);
                        }
                        if (Res.Success == false)
                        {
                            return(Res);
                        }
                    }
                    else
                    {
                        return(new Lfx.Types.FailureOperationResult("Debe preparar el almacén de datos."));
                    }
                }
            }

            // Configuro el nivel de aislación predeterminado
            // FIXME: no puedo obtener esto de la BD (System.Data.IsolationLevel)(Enum.Parse(typeof(System.Data.IsolationLevel), Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.Datos.Aislacion", "Serializable")));
            Lfx.Data.DatabaseCache.DefaultCache.DefaultIsolationLevel = System.Data.IsolationLevel.Serializable;

            return(iniciarReturn);
        }
Example #24
0
                public override Lfx.Types.OperationResult Ok()
                {
                        int PV = EntradaPV.ValueInt;
                        int Desde = EntradaDesde.ValueInt;
                        int Hasta = EntradaHasta.ValueInt;
                        int Cantidad = Hasta - Desde + 1;

                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Una vez anulados, los comprobantes deberán ser archivados en todas sus copias y no podrán ser rehabilitados ni reutilizados.", "¿Está seguro de que desea anular " + Cantidad.ToString() + " comprobantes?");
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                        if (Pregunta.ShowDialog() == DialogResult.OK) {
                                bool AnularPagos = EntradaAnularPagos.ValueInt != 0;

                                int m_Id = 0;
                                string IncluyeTipos = "";

                                switch (EntradaTipo.TextKey) {
                                        case "A":
                                                IncluyeTipos = "'FA', 'NCA', 'NDA'";
                                                break;

                                        case "B":
                                                IncluyeTipos = "'FB', 'NCB', 'NDB'";
                                                break;

                                        case "C":
                                                IncluyeTipos = "'FC', 'NCC', 'NDC'";
                                                break;

                                        case "E":
                                                IncluyeTipos = "'FE', 'NCE', 'NDE'";
                                                break;

                                        case "M":
                                                IncluyeTipos = "'FM', 'NCM', 'NDM'";
                                                break;

                                        case "T":
                                                IncluyeTipos = "'T'";
                                                break;

                                        default:
                                                IncluyeTipos = "'" + EntradaTipo.TextKey + "'";
                                                break;
                                }

                                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando comprobantes", "Se están anulando los comprobantes seleccionados.");
                                Progreso.Cancelable = true;
                                Progreso.Max = Cantidad;
                                Progreso.Begin();

                                IDbTransaction Trans = this.Connection.BeginTransaction(IsolationLevel.Serializable);
                                for (int Numero = Desde; Numero <= Hasta; Numero++) {
                                        int IdFactura = Connection.FieldInt("SELECT id_comprob FROM comprob WHERE impresa=1 AND tipo_fac IN (" + IncluyeTipos + ") AND pv=" + PV.ToString() + " AND numero=" + Numero.ToString());

                                        if (IdFactura == 0) {
                                                // Es una factura que todava no existe
                                                // Tengo que crear la factura y anularla
                                                qGen.Insert InsertarComprob = new qGen.Insert("comprob");
                                                InsertarComprob.Fields.AddWithValue("tipo_fac", "F" + EntradaTipo.TextKey);
                                                InsertarComprob.Fields.AddWithValue("id_formapago", 3);
                                                InsertarComprob.Fields.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual);
                                                InsertarComprob.Fields.AddWithValue("pv", Lfx.Types.Parsing.ParseInt(EntradaPV.Text));
                                                InsertarComprob.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                                                InsertarComprob.Fields.AddWithValue("id_vendedor", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                                                InsertarComprob.Fields.AddWithValue("id_cliente", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                                                InsertarComprob.Fields.AddWithValue("obs", "Comprobante anulado antes de ser impreso.");
                                                InsertarComprob.Fields.AddWithValue("impresa", 1);
                                                InsertarComprob.Fields.AddWithValue("anulada", 1);
                                                Connection.Execute(InsertarComprob);
                                                m_Id = Connection.FieldInt("SELECT LAST_INSERT_ID()");
                                                Lbl.Comprobantes.ComprobanteConArticulos NuevoComprob = new Lbl.Comprobantes.ComprobanteConArticulos(this.Connection, m_Id);
                                                NuevoComprob.Numerar(true);
                                        } else {
                                                Lbl.Comprobantes.ComprobanteConArticulos Fac = new Lbl.Comprobantes.ComprobanteConArticulos(Connection, IdFactura);
                                                if (Fac.Anulado == false)
                                                        Fac.Anular(AnularPagos);
                                        }

                                        Progreso.Advance(1);
                                        if (Progreso.Cancelar)
                                                break;
                                }

                                Progreso.End();

                                if (Progreso.Cancelar) {
                                        Trans.Rollback();
                                        Lfx.Workspace.Master.RunTime.Toast("La operación fue cancelada.", "Aviso");
                                } else {
                                        Trans.Commit();
                                        ProximosNumeros.Clear();
                                        Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Recuerde archivar ambas copias.", "Aviso");
                                }

                                EntradaDesde.ValueInt = 0;
                                EntradaHasta.ValueInt = 0;
                                EntradaDesde.Focus();

                                return base.Ok(); 
                        } else {
                                return new Lfx.Types.FailureOperationResult("La operación fue cancelada.");
                        }
                }
Example #25
0
                private void BotonPresentar_Click(object sender, EventArgs e)
                {
                        if (Listado.CheckedItems.Count == 0) {
                                Lui.Forms.MessageBox.Show("Debe marcar uno o más cupones para presentar.", "Acreditar");
                                return;
                        }

                        int CantidadCupones = 0;
                        foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) {
                                if (itm.Checked) {
                                        CantidadCupones++;
                                        if (itm.SubItems["tarjetas_cupones.estado"].Text != "Sin presentar") {
                                                Lui.Forms.MessageBox.Show("Sólo se pueden hacer presentaciones de cupones que no han sido presentados.", "Presentación de cupones");
                                                return;
                                        }
                                }
                        }

                        if (CantidadCupones == 0) {
                                Lui.Forms.MessageBox.Show("Debe seleccionar uno o más cupones para presentar.", "Presentación de cupones");
                                return;
                        }


                        using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea marcar los cupones seleccionados como presentados?", "Presentación de cupones")) {
                                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                if (Pregunta.ShowDialog() == DialogResult.OK) {
                                        Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Presentación de cupones", "Se están marcando los cupones seleccionados como 'Presentados'.");
                                        Progreso.Max = CantidadCupones;
                                        Progreso.Begin();
                                        foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) {
                                                if (itm.Checked) {
                                                        Progreso.Advance(1);
                                                        Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(this.Connection, Lfx.Types.Parsing.ParseInt(itm.Text));
                                                        if (Cupon.Estado == 0)
                                                                Cupon.Presentar();
                                                }
                                        }
                                        Progreso.End();
                                        this.RefreshList();
                                }
                        }
                }
Example #26
0
                public override Lfx.Types.OperationResult Ok()
                {
                        if (Lui.LogOn.LogOnData.ValidateAccess(typeof(Lbl.Comprobantes.Recibo), Lbl.Sys.Permisos.Operaciones.Eliminar) == false)
                                return new Lfx.Types.NoAccessOperationResult();

                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Una vez anulado, el comprobante deberá ser archivado en todas sus copias y no podrá ser rehabilitado ni reutilizado.", "¿Está seguro de que desea anular el comprobante?");
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                        if (Pregunta.ShowDialog() == DialogResult.OK) {
                                int Numero = Lfx.Types.Parsing.ParseInt(EntradaNumero.Text);
                                int PV = Lfx.Types.Parsing.ParseInt(EntradaPV.Text);
                                Lbl.Comprobantes.Recibo Rec = null;

                                int IdRecibo = 0;
                                if (Numero > 0)
                                        IdRecibo = this.Connection.FieldInt("SELECT id_recibo FROM recibos WHERE tipo_fac='" + EntradaTipo.TextKey + "' AND pv=" + PV.ToString() + " AND numero=" + Numero.ToString());
                                if (IdRecibo != 0)
                                        Rec = new Lbl.Comprobantes.Recibo(this.Connection, IdRecibo);

                                if (Rec != null && Rec.Existe) {
                                        IDbTransaction Trans = Rec.Connection.BeginTransaction(IsolationLevel.Serializable);
                                        Rec.Anular();
                                        Trans.Commit();
                                }

                                EntradaNumero.Text = "";
                                EntradaNumero.Focus();

                                return new Lfx.Types.SuccessOperationResult();
                        } else {
                                return new Lfx.Types.CancelOperationResult();
                        }
                }
Example #27
0
                private void TimerProgramador_Tick(object sender, EventArgs e)
                {
                        TimerProgramador.Stop();

                        if (this.Visible) {
                                //Ejecuto tareas del programador
                                Lfx.Services.Task ProximaTarea = null;
                                // En conexiones lentas, 1 vez por minuto
                                // En conexiones rápidas, cada 5 segundos
                                if (Lfx.Workspace.Master.SlowLink) {
                                        if (Lfx.Workspace.Master.DefaultScheduler.LastGetTask == System.DateTime.MinValue || (DateTime.Now - Lfx.Workspace.Master.DefaultScheduler.LastGetTask).Minutes >= 1)
                                                ProximaTarea = Lfx.Workspace.Master.DefaultScheduler.GetNextTask("lazaro");
                                } else {
                                        if (Lfx.Workspace.Master.DefaultScheduler.LastGetTask == System.DateTime.MinValue || (DateTime.Now - Lfx.Workspace.Master.DefaultScheduler.LastGetTask).Seconds >= 5)
                                                ProximaTarea = Lfx.Workspace.Master.DefaultScheduler.GetNextTask("lazaro");
                                }

                                if (ProximaTarea != null) {
                                        // Lanzo la tarea en un nuevo thread
                                        System.Threading.ThreadStart ParamInicio = delegate { Ejecutor.Exec(ProximaTarea.Command, ProximaTarea.ComputerName); };
                                        new System.Threading.Thread(ParamInicio).Start();
                                }

                                if (YaSubiEstadisticas == false && Lfx.Workspace.Master.DebugMode == false) {
                                        YaSubiEstadisticas = true;
                                        System.Threading.ThreadStart ParamInicio = delegate { Aplicacion.EnviarEstadisticas(); };
                                        System.Threading.Thread Thr = new System.Threading.Thread(ParamInicio);
                                        Thr.IsBackground = true;
                                        Thr.Start();
                                }

                                if (YaPregunteReiniciar == false && Lfx.Updates.Updater.Master != null && Lfx.Updates.Updater.Master.UpdatesPending() && ActiveForm == this) {
                                        YaPregunteReiniciar = true;
                                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Existe una nueva versión de Lázaro. Debe reiniciar la aplicación para instalar la actualización.", "¿Desea reiniciar ahora?");
                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                        DialogResult Respuesta = Pregunta.ShowDialog();
                                        if (Respuesta == DialogResult.OK)
                                                Ejecutor.Exec("REBOOT");
                                }
                        }

                        TimerProgramador.Start();
                }
Example #28
0
                /// <summary>
                /// Inicia una conexión con la base de datos y verifica si la versión de la la misma es la última disponible. En caso contrario la actualiza.
                /// </summary>
                internal static Lfx.Types.OperationResult AbrirConexion()
                {
                        Lfx.Types.OperationResult iniciarReturn = new Lfx.Types.SuccessOperationResult();

                        //Si el servidor SQL es esta misma PC, intento iniciar el servidor
                        if (Lfx.Environment.SystemInformation.Platform == Lfx.Environment.SystemInformation.Platforms.Windows && Lfx.Data.DataBaseCache.DefaultCache.ServerName.ToUpperInvariant() == "LOCALHOST") {
                                switch (Lfx.Data.DataBaseCache.DefaultCache.AccessMode) {
                                        case Lfx.Data.AccessModes.MySql:
                                                Lfx.Environment.Shell.Execute("net", "start mysql", ProcessWindowStyle.Hidden, true);
                                                break;
                                        case Lfx.Data.AccessModes.Npgsql:
                                                // FIXME: detectar el nombre del servicio.
                                                Lfx.Environment.Shell.Execute("net", "start postgresql-9.0", ProcessWindowStyle.Hidden, true);
                                                break;
                                }
                        }

                        try {
                                Lfx.Workspace.Master.MasterConnection.Open();
                        } catch (Exception ex) {
                                return new Lfx.Types.FailureOperationResult(ex.Message);
                        }

                        if (Lfx.Workspace.Master.IsPrepared() == false) {
                                using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(@"Aparentemente es la primera vez que utiliza este almacén de datos. Antes de poder utilizarlo debe prepararlo con una carga inicial de datos.
Responda 'Sí' sólamente si es la primera vez que utiliza Lázaro o está restaurando desde una copia de seguridad.", @"¿Desea preparar el almacén de datos?")) {
                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                        if (Pregunta.ShowDialog() == DialogResult.OK) {
                                                Lfx.Types.OperationResult Res;
                                                using (Lfx.Data.Connection DataBase = Lfx.Workspace.Master.GetNewConnection("Preparar almacén de datos")) {
                                                        DataBase.RequiresTransaction = false;
                                                        Res = Lfx.Workspace.Master.Prepare(null);
                                                }
                                                if (Res.Success == false)
                                                        return Res;
                                        } else {
                                                return new Lfx.Types.FailureOperationResult("Debe preparar el almacén de datos.");
                                        }
                                }
                        }

                        // Configuro el nivel de aislación predeterminado
                        Lfx.Data.DataBaseCache.DefaultCache.DefaultIsolationLevel = (System.Data.IsolationLevel)(Enum.Parse(typeof(System.Data.IsolationLevel), Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.Datos.Aislacion", "Serializable")));

                        return iniciarReturn;
                }
Example #29
0
                public override Lfx.Types.OperationResult BeforePrint()
                {
                        Lbl.Comprobantes.ComprobanteConArticulos Comprob = this.Elemento as Lbl.Comprobantes.ComprobanteConArticulos;
                        if (Comprob.Articulos.Count >= 1 && (Comprob.Articulos[0].Cantidad < 0 || Comprob.Articulos[0].Unitario < 0))
                                return new Lfx.Types.OperationResult(false, "El primer ítem de la factura no puede ser negativo. Utilice los ítem negativos en último lugar.");

                        Comprob.Cliente.Cargar();

                        if (Comprob.FormaDePago == null)
                                return new Lfx.Types.FailureOperationResult("Por favor seleccione la forma de pago.");

                        if (Comprob.Cliente == null)
                                return new Lfx.Types.FailureOperationResult("Por favor seleccione un cliente.");

                        if (Comprob.Tipo == null)
                                return new Lfx.Types.FailureOperationResult("Por favor seleccione el tipo de comprobante.");

                        if (Lbl.Sys.Config.Pais.Id == 1) {
                                // Verificaciones especiales para Argentina
                                if (Comprob.Tipo.EsFacturaNCoND && Comprob.Cliente.SituacionTributaria != null && Comprob.Tipo.Letra != Comprob.Cliente.LetraPredeterminada()) {
                                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(@"La situación tributaria del cliente y el tipo de comprobante no se corresponden.
Un cliente " + Comprob.Cliente.SituacionTributaria.ToString() + @" debería llevar un comprobante tipo " + Comprob.Cliente.LetraPredeterminada() + @". No debería continuar con la impresión. 
¿Desea continuar de todos modos?", "Tipo de comprobante incorrecto");
                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                        if (Pregunta.ShowDialog() == DialogResult.Cancel)
                                                return new Lfx.Types.FailureOperationResult("Corrija la situación tributaria del cliente o el tipo de comprobante.");
                                }

                                if (Comprob.Tipo.Letra.ToUpperInvariant() == "A") {
                                        if (Comprob.Cliente.ClaveTributaria == null || Comprob.Cliente.ClaveTributaria.EsValido() == false)
                                                return new Lfx.Types.FailureOperationResult("El cliente no tiene una CUIT válida. Por favor edite el cliente y escriba una CUIT válida.");
                                } else if (Comprob.Tipo.Letra == "B") {
                                        //Si es factura B de más de $ 1000, debe llevar el Nº de DNI
                                        if (Comprob.Total >= 1000 && Comprob.Cliente.NumeroDocumento.Length < 5 &&
                                                (Comprob.Cliente.ClaveTributaria == null || Comprob.Cliente.ClaveTributaria.EsValido() == false))
                                                return new Lfx.Types.FailureOperationResult("Para Facturas B de $ 1.000 o más debe proporcionar el número de DNI/CUIT del cliente.");
                                        //Si es factura B de más de $ 1000, debe llevar domicilio
                                        if (Comprob.Total >= 1000 && Comprob.Cliente.Domicilio.Length < 1)
                                                return new Lfx.Types.FailureOperationResult("Para Facturas B de $ 1.000 o más debe proporcionar el domicilio del cliente.");
                                }
                        }

                        if (EntradaProductos.ShowStock && this.Tipo.MueveExistencias < 0 && Comprob.HayExistencias() == false) {
                                Lui.Forms.YesNoDialog OPregunta = new Lui.Forms.YesNoDialog("Las existencias actuales no son suficientes para cubrir la operación que intenta realizar.\n¿Desea continuar de todos modos?", "No hay existencias suficientes");
                                OPregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                if (OPregunta.ShowDialog() == DialogResult.Cancel)
                                        return new Lfx.Types.FailureOperationResult("No se imprimir el comprobante por falta de existencias.");
                        }

                        if (Comprob.Cliente.Id != 999 && (Comprob.Tipo.EsFactura || Comprob.Tipo.EsNotaDebito)) {
                                decimal SaldoCtaCte = Comprob.Cliente.CuentaCorriente.ObtenerSaldo(false);

                                if (Comprob.FormaDePago != null && Comprob.FormaDePago.Tipo == Lbl.Pagos.TiposFormasDePago.CuentaCorriente) {
                                        decimal LimiteCredito = Comprob.Cliente.LimiteCredito;

                                        if (LimiteCredito == 0)
                                                LimiteCredito = Lfx.Types.Parsing.ParseCurrency(Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.Cuentas.LimiteCreditoPredet", "0"));

                                        if (LimiteCredito != 0 && (Comprob.Total + SaldoCtaCte) > LimiteCredito)
                                                return new Lfx.Types.FailureOperationResult("El valor de la factura y/o el saldo en cuenta corriente supera el límite de crédito de este cliente.");
                                } else {
                                        if (SaldoCtaCte < 0) {
                                                using (SaldoEnCuentaCorriente FormularioError = new SaldoEnCuentaCorriente()) {
                                                        switch (FormularioError.ShowDialog()) {
                                                                case DialogResult.Yes:
                                                                        //Corregir el problema
                                                                        this.EntradaFormaPago.ValueInt = 3;
                                                                        this.Save();
                                                                        Comprob.FormaDePago.Tipo = Lbl.Pagos.TiposFormasDePago.CuentaCorriente;
                                                                        break;
                                                                case DialogResult.No:
                                                                        //Continuar. No corregir el problema.
                                                                        break;
                                                                default:
                                                                        //Cancelar y volver a la edición.
                                                                        return new Lfx.Types.OperationResult(false);
                                                        }
                                                }
                                        }
                                }
                        }

                        if (Comprob.PV < 1)
                                return new Lfx.Types.FailureOperationResult("Por favor escriba un punto de venta válido.");

                        if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero.ContainsKey(Comprob.PV) == false) {
                                // No existe el PV... vacío la caché antes intentar de nuevo y dar un error
                                Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero.Clear();
                                if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero.ContainsKey(Comprob.PV) == false)
                                        return new Lfx.Types.FailureOperationResult("El punto de venta no existe. Si desea definir un nuevo punto de venta, utilice el menú Comprobantes -> Tablas -> Puntos de venta.");
                        }

                        Lbl.Comprobantes.PuntoDeVenta Pv = Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero[Comprob.PV];
                        if (Pv.Tipo == Lbl.Comprobantes.TipoPv.Normal) {
                                Lbl.Impresion.Impresora Impresora = Comprob.ObtenerImpresora();

                                if (Pv.CargaManual && (Impresora == null || Impresora.CargaPapel == Lbl.Impresion.CargasPapel.Automatica)) {
                                        Lui.Printing.ManualFeedDialog FormularioCargaManual = new Lui.Printing.ManualFeedDialog();
                                        FormularioCargaManual.DocumentName = Comprob.Tipo.ToString() + " " + Comprob.PV.ToString("0000") + "-" + Lbl.Comprobantes.Numerador.ProximoNumero(Comprob).ToString("00000000");
                                        // Muestro el nombre de la impresora
                                        if (Impresora != null) {
                                                FormularioCargaManual.PrinterName = Impresora.Nombre;
                                        } else {
                                                System.Drawing.Printing.PrinterSettings objPrint = new System.Drawing.Printing.PrinterSettings();
                                                FormularioCargaManual.PrinterName = objPrint.PrinterName;
                                        }
                                        if (FormularioCargaManual.ShowDialog() == DialogResult.Cancel)
                                                return new Lfx.Types.CancelOperationResult();
                                }
                        }

                        if (Comprob.Tipo.MueveExistencias != 0) {
                                Lfx.Types.OperationResult Res = Comprob.VerificarSeries();
                                if (Res.Success == false)
                                        return Res;
                        }

                        return base.BeforePrint();
                }
Example #30
0
        public override Lfx.Types.OperationResult BeforePrint()
        {
            Lbl.Comprobantes.ComprobanteConArticulos Comprob = this.Elemento as Lbl.Comprobantes.ComprobanteConArticulos;
            if (Comprob.Articulos.Count >= 1 && (Comprob.Articulos[0].Cantidad < 0 || Comprob.Articulos[0].ImporteUnitario < 0))
            {
                return(new Lfx.Types.FailureOperationResult("El primer ítem de la factura no puede ser negativo. Utilice los ítem negativos en último lugar."));
            }

            Comprob.Cliente.Cargar();

            if (Comprob.FormaDePago == null)
            {
                return(new Lfx.Types.FailureOperationResult("Por favor seleccione la forma de pago."));
            }

            if (Comprob.Cliente == null)
            {
                return(new Lfx.Types.FailureOperationResult("Por favor seleccione un cliente."));
            }

            if (Comprob.Tipo == null)
            {
                return(new Lfx.Types.FailureOperationResult("Por favor seleccione el tipo de comprobante."));
            }

            if (Lbl.Sys.Config.Pais.Id == 1)
            {
                // Verificaciones especiales para Argentina
                if (Comprob.Tipo.EsFacturaNCoND && Comprob.Cliente.SituacionTributaria != null && Comprob.Tipo.Letra != Comprob.Cliente.LetraPredeterminada())
                {
                    Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(@"La situación tributaria del cliente y el tipo de comprobante no se corresponden.
Un cliente " + Comprob.Cliente.SituacionTributaria.ToString() + @" debería llevar un comprobante tipo " + Comprob.Cliente.LetraPredeterminada() + @". No debería continuar con la impresión. 
¿Desea continuar de todos modos?", "Tipo de comprobante incorrecto");
                    Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                    if (Pregunta.ShowDialog() == DialogResult.Cancel)
                    {
                        return(new Lfx.Types.FailureOperationResult("Corrija la situación tributaria del cliente o el tipo de comprobante."));
                    }
                }

                if (Comprob.Tipo.Letra.ToUpperInvariant() == "A")
                {
                    if (Comprob.Cliente.ClaveTributaria == null || Comprob.Cliente.ClaveTributaria.EsValido() == false)
                    {
                        return(new Lfx.Types.FailureOperationResult("El cliente no tiene una CUIT válida. Por favor edite el cliente y escriba una CUIT válida."));
                    }
                }
                else if (Comprob.Tipo.Letra == "B")
                {
                    //Si es factura B de más de $ 1000, debe llevar el Nº de DNI
                    if (Comprob.Total >= 1000 && Comprob.Cliente.NumeroDocumento.Length < 5 &&
                        (Comprob.Cliente.ClaveTributaria == null || Comprob.Cliente.ClaveTributaria.EsValido() == false))
                    {
                        return(new Lfx.Types.FailureOperationResult("Para Facturas B de $ 1.000 o más debe proporcionar el número de DNI/CUIT del cliente."));
                    }
                    //Si es factura B de más de $ 1000, debe llevar domicilio
                    if (Comprob.Total >= 1000 && Comprob.Cliente.Domicilio.Length < 1)
                    {
                        return(new Lfx.Types.FailureOperationResult("Para Facturas B de $ 1.000 o más debe proporcionar el domicilio del cliente."));
                    }
                }
            }

            if (EntradaProductos.MostrarExistencias && this.Tipo.MueveExistencias < 0 && Comprob.HayExistencias() == false)
            {
                Lui.Forms.YesNoDialog OPregunta = new Lui.Forms.YesNoDialog("Las existencias actuales no son suficientes para cubrir la operación que intenta realizar.\n¿Desea continuar de todos modos?", "No hay existencias suficientes");
                OPregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                if (OPregunta.ShowDialog() == DialogResult.Cancel)
                {
                    return(new Lfx.Types.FailureOperationResult("No se imprimir el comprobante por falta de existencias."));
                }
            }

            if (Comprob.Cliente.Id != 999 && (Comprob.Tipo.EsFactura || Comprob.Tipo.EsNotaDebito))
            {
                decimal SaldoCtaCte = Comprob.Cliente.CuentaCorriente.ObtenerSaldo(false);

                if (Comprob.FormaDePago != null && Comprob.FormaDePago.Tipo == Lbl.Pagos.TiposFormasDePago.CuentaCorriente)
                {
                    decimal LimiteCredito = Comprob.Cliente.LimiteCredito;

                    if (LimiteCredito == 0)
                    {
                        LimiteCredito = Lfx.Types.Parsing.ParseCurrency(Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <string>("Sistema.Cuentas.LimiteCreditoPredet", "0"));
                    }

                    if (LimiteCredito != 0 && (Comprob.Total + SaldoCtaCte) > LimiteCredito)
                    {
                        return(new Lfx.Types.FailureOperationResult("El valor de la factura y/o el saldo en cuenta corriente supera el límite de crédito de este cliente."));
                    }
                }
                else
                {
                    if (SaldoCtaCte < 0)
                    {
                        using (SaldoEnCuentaCorriente FormularioError = new SaldoEnCuentaCorriente()) {
                            switch (FormularioError.ShowDialog())
                            {
                            case DialogResult.Yes:
                                //Corregir el problema
                                this.EntradaFormaPago.ValueInt = 3;
                                this.Save();
                                Comprob.FormaDePago.Tipo = Lbl.Pagos.TiposFormasDePago.CuentaCorriente;
                                break;

                            case DialogResult.No:
                                //Continuar. No corregir el problema.
                                break;

                            default:
                                //Cancelar y volver a la edición.
                                return(new Lfx.Types.CancelOperationResult());
                            }
                        }
                    }
                }
            }

            if (Comprob.PV < 1)
            {
                return(new Lfx.Types.FailureOperationResult("Por favor escriba un punto de venta válido."));
            }

            if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero.ContainsKey(Comprob.PV) == false)
            {
                // No existe el PV... vacío la caché antes intentar de nuevo y dar un error
                Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero.Clear();
                if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero.ContainsKey(Comprob.PV) == false)
                {
                    return(new Lfx.Types.FailureOperationResult("El punto de venta no existe. Si desea definir un nuevo punto de venta, utilice el menú Comprobantes -> Tablas -> Puntos de venta."));
                }
            }

            Lbl.Comprobantes.PuntoDeVenta Pv = Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero[Comprob.PV];
            if (Pv.Tipo == Lbl.Comprobantes.TipoPv.Talonario)
            {
                Lbl.Impresion.Impresora Impresora = Comprob.ObtenerImpresora();

                if (Pv.CargaManual && (Impresora == null || Impresora.CargaPapel == Lbl.Impresion.CargasPapel.Automatica))
                {
                    Lui.Printing.ManualFeedDialog FormularioCargaManual = new Lui.Printing.ManualFeedDialog();
                    FormularioCargaManual.DocumentName = Comprob.Tipo.ToString() + " " + Comprob.PV.ToString("0000") + "-" + Lbl.Comprobantes.Numerador.ProximoNumero(Comprob).ToString("00000000");
                    // Muestro el nombre de la impresora
                    if (Impresora != null)
                    {
                        FormularioCargaManual.PrinterName = Impresora.Nombre;
                    }
                    else
                    {
                        System.Drawing.Printing.PrinterSettings objPrint = new System.Drawing.Printing.PrinterSettings();
                        FormularioCargaManual.PrinterName = objPrint.PrinterName;
                    }
                    if (FormularioCargaManual.ShowDialog() == DialogResult.Cancel)
                    {
                        return(new Lfx.Types.CancelOperationResult());
                    }
                }
            }

            if (Comprob.Tipo.MueveExistencias != 0)
            {
                Lfx.Types.OperationResult Res = Comprob.VerificarSeries();
                if (Res.Success == false)
                {
                    return(Res);
                }
            }

            return(base.BeforePrint());
        }
Example #31
0
                /// <summary>
                /// Inicia la interfaz gráfica del programa.
                /// </summary>
                private static Lfx.Types.OperationResult IniciarGui()
                {
                        int Configurado = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<int>("Sistema.Configurado", 0);
                        if ((Configurado == 0 && Lbl.Sys.Config.Empresa.ClaveTributaria == null) || string.IsNullOrEmpty(Lbl.Sys.Config.Empresa.Nombre)) {
                                Config.Preferencias FormConfig = new Config.Preferencias();
                                FormConfig.PrimeraVez = true;
                                if (FormConfig.ShowDialog() != DialogResult.OK)
                                        Ejecutor.Exec("QUIT");
                        }

                        System.DateTime FechaServidor = System.Convert.ToDateTime(Lfx.Workspace.Master.MasterConnection.FirstRowFromSelect("SELECT NOW()")[0]);
                        System.TimeSpan Diferencia = FechaServidor - System.DateTime.Now;
                        if (Math.Abs(Diferencia.TotalMinutes) > 10) {
                                string DiferenciaExplicada = "";
                                if (Math.Abs(Diferencia.TotalDays) >= 2)
                                        DiferenciaExplicada = Math.Ceiling(Math.Abs(Diferencia.TotalDays)).ToString() + " días";
                                else if (Math.Abs(Diferencia.TotalHours) >= 2)
                                        DiferenciaExplicada = Math.Ceiling(Math.Abs(Diferencia.TotalHours)).ToString() + " horas";
                                else
                                        DiferenciaExplicada = Math.Ceiling(Math.Abs(Diferencia.TotalMinutes)).ToString() + " minutos";

                                Lfx.Workspace.Master.RunTime.Toast("Existe una diferencia de " + DiferenciaExplicada + " entre el reloj del servidor SQL y el reloj de este equipo. Es necesario que revise y ajuste el reloj de ambos equipos a la brevedad.", "Error de fecha y hora");
                        }


                        // Si el administrador tiene la contraseña predeterminada y aquí entro siempre como administrador
                        // o todavía no entré nunca, ingreso directamente sin pedir contraseña.
                        int UltimoUsuario = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<int>("Sistema.Ingreso.UltimoUsuario", 1);
                        if(UltimoUsuario == 1) {
                                Lbl.Personas.Usuario Usu = new Lbl.Personas.Usuario(Lfx.Workspace.Master.MasterConnection, 1);
                                if (Usu.ContrasenaValida("admin"))
                                        Lbl.Sys.Config.Actual.UsuarioConectado = new Lbl.Sys.Configuracion.UsuarioConectado(Usu);
                        }

                        if (Lbl.Sys.Config.Actual.UsuarioConectado.Id == 0) {
                                using (Lazaro.WinMain.Misc.Ingreso FormIngreso = new Lazaro.WinMain.Misc.Ingreso()) {
                                        FormIngreso.Connection = Lfx.Workspace.Master.MasterConnection;
                                        FormIngreso.ShowDialog();
                                }
                        }


                        if (Lbl.Sys.Config.Actual.UsuarioConectado.Id > 0) {
                                if (Lfx.Workspace.Master.SlowLink == false && Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.Backup.Tipo", "0") == "2") {
                                        string FechaActual = System.DateTime.Now.ToString("yyyy-MM-dd");
                                        string FechaBackup = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Sistema.Backup.Ultimo", "");
                                        if (FechaActual != FechaBackup) {
                                                int Articulos = Lfx.Workspace.Master.MasterConnection.FieldInt("SELECT COUNT(id_articulo) FROM articulos");
                                                if (Articulos > 0) {
                                                        //Hago un backup automático, una vez por día, siempre que haya al menos 1 artículo en la BD
                                                        //Esto es para evitar hacer backup de una BD vacía
                                                        Ejecutor.Exec("BACKUP NOW");
                                                        Lfx.Workspace.Master.CurrentConfig.WriteGlobalSetting("Sistema.Backup.Ultimo", FechaActual);
                                                }
                                        }
                                }

                                // Mostrar qué hay de nuevo
                                string FechaWhatsnew = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<string>("Usuario." + Lbl.Sys.Config.Actual.UsuarioConectado.Id.ToString() + ".Whatsnew.Ultimo", "firsttime");
                                if (FechaWhatsnew == "firsttime") {
                                        // Primera vez que entra. No muestro qué hay de nuevo (TODO: pero podría darle una bienvenida)
                                        Lfx.Workspace.Master.CurrentConfig.WriteGlobalSetting("Usuario." + Lbl.Sys.Config.Actual.UsuarioConectado.Id.ToString() + ".Whatsnew.Ultimo", System.DateTime.Now.ToString("yyyy-MM-dd"));
                                } else {
                                        // Veo si hay novedades para mostrar
                                        // string FechaWhatsnewOriginal = FechaWhatsnew;
                                        System.IO.StreamReader Whatsnew = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Lazaro.whatsnew.txt"));
                                        System.Text.StringBuilder Mostrar = null;
                                        bool Mostrando = false;
                                        while (Whatsnew.EndOfStream == false) {
                                                string Linea = Whatsnew.ReadLine();
                                                if (Linea.Length > 4 && Linea.Substring(0, 4) == "*** ") {
                                                        string FechaLinea = Linea.Substring(4, Linea.Length - 4);
                                                        if (string.Compare(FechaLinea, FechaWhatsnew) > 0) {
                                                                FechaWhatsnew = FechaLinea;
                                                                Linea = Lfx.Types.Parsing.ParseDate(FechaLinea).Value.ToString(Lfx.Types.Formatting.DateTime.LongDatePattern) + ":";
                                                                Mostrando = true;
                                                        }
                                                }

                                                if (Mostrando) {
                                                        if (Mostrar == null) {
                                                                Mostrar = new System.Text.StringBuilder();
                                                                Mostrar.AppendLine("Por favor tómese un momento para leer sobre las novedades incorporadas recientemente en Lázaro:");
                                                                Mostrar.AppendLine("");
                                                        }
                                                        Mostrar.AppendLine(Linea.Replace("* ", "• "));
                                                }
                                        }
                                        Whatsnew.BaseStream.Close();
                                        Whatsnew.Close();
                                        if (Mostrar != null && Mostrar.Length > 0) {
                                                Lfx.Workspace.Master.RunTime.Toast(Mostrar.ToString(), "Novedades");
                                                Lfx.Workspace.Master.CurrentConfig.WriteGlobalSetting("Usuario." + Lbl.Sys.Config.Actual.UsuarioConectado.Id.ToString(), "Whatsnew.Ultimo", FechaWhatsnew);
                                        }
                                }

                                // Mostrar el formulario
                                Lfx.Workspace.Master.MainForm = new Principal.Inicio();
                                Aplicacion.FormularioPrincipal.Show();
                                if (FechaWhatsnew == "firsttime") {
                                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¡Hola! ¿Le gustaría ver una página sencilla con un poco de información sobre cómo utilizar Lázaro?", "Primeros pasos");
                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                        if (Pregunta.ShowDialog() == DialogResult.OK)
                                                Help.ShowHelp(Aplicacion.FormularioPrincipal, "http://www.lazarogestion.com/?q=node/44");
                                } else {
                                        string RunTimeName = Lfx.Environment.SystemInformation.RuntimeName;
                                        // Verifico la presencia de .NET Framework 3.5
                                        if (Lfx.Environment.SystemInformation.RunTime == Lfx.Environment.SystemInformation.RunTimes.DotNet && RunTimeName.IndexOf("3.5") < 0) {
                                                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Es necesario instalar un componente para el correcto funcionamiento de Lázaro. El componente es Microsoft .NET Framework versión 3.5. ¿Desea ir a la página de descarga para instalarlo ahora?", "Advertencia");
                                                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                                if (Pregunta.ShowDialog() == DialogResult.OK)
                                                        Help.ShowHelp(Aplicacion.FormularioPrincipal, "http://download.microsoft.com/download/5/3/4/5347CEDC-6A83-49F5-9347-BCD58A9AAE25/DotNetFx35ClientSetup.exe");
                                        }
                                }
                                Application.Run(Aplicacion.FormularioPrincipal);
                        }

                        return new Lfx.Types.SuccessOperationResult();
                }
Example #32
0
                private void BotonArqueo_Click(object sender, System.EventArgs e)
                {
                        if (this.Fechas.To < System.DateTime.Now) {
                                Lfx.Workspace.Master.RunTime.Toast("La vista actual muestra el estado de la caja en una fecha pasada. No puede asentar un arqueo con una fecha pasada. Para asentar un arqueo cambie el filtro de fechas para ver el estado actual de la caja.", "Arqueo de caja");
                                return;
                        } else if (this.Caja == null) {
                                Lfx.Workspace.Master.RunTime.Toast("La vista actual muestra los movimientos de varias cajas combinados. No se puede asentar un arqueo en este estado.", "Arqueo de caja");
                                return;
                        } else if (this.Cliente != null || this.Concepto != null || this.Direccion != 0) {
                                Lfx.Workspace.Master.RunTime.Toast("La vista actual no muestra todos los movimientos de la caja ya que existe un filtro activo (filtro por Cliente, Concepto, etc.). Quite todos los filtros para poder asentar un arqueo.", "Arqueo de caja");
                                return;
                        }

                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Confirma que el saldo de la caja de " + Lbl.Sys.Config.Moneda.Simbolo + " " + Lfx.Types.Formatting.FormatCurrency(this.Contadores[3].Total) + " corresponde con lo que se encuentra físicamente en la caja? Si confirma que el saldo de la cuenta es el indicado se asentará una marca de 'Arqueo', para su propio control.", "El saldo de la caja es de " + Lbl.Sys.Config.Moneda.Simbolo + "  " + Lfx.Types.Formatting.FormatCurrency(this.Contadores[3].Total));
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                        if (Pregunta.ShowDialog() == DialogResult.OK) {
                                using (IDbTransaction Trans = this.Caja.Connection.BeginTransaction()) {
                                        this.Caja.Arqueo();
                                        Trans.Commit();
                                }
                                this.RefreshList();
                        } else {
                                Lui.Forms.MessageBox.Show("No se asentó un arqueo. Verifique el saldo de la cuenta y si es necesario realice un ajuste.", "Arqueo de caja");
                        }
                }
Example #33
0
                protected override void OnFormClosing(FormClosingEventArgs e)
                {
                        if (this.GetControlsChanged(this.Controls)) {
                                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Si cierra el formulario en este momento, no se guardarán los cambios realizados (subrayados en color rojo). ¿Desea cerrar el formulario de todos modos y perder los cambios realizados?", "Hay cambios sin guardar");
                                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                                this.ShowChanged = true;
                                DialogResult Res = Pregunta.ShowDialog();
                                this.ShowChanged = false;

                                if (Res == DialogResult.Cancel) {
                                        e.Cancel = true;
                                } else {
                                        e.Cancel = false;
                                }
                        }
                        base.OnFormClosing(e);
                }
Example #34
0
 private Lfx.Types.OperationResult EditarPermisos()
 {
         if (Lui.LogOn.LogOnData.ValidateAccess(this.Elemento, Lbl.Sys.Permisos.Operaciones.Administrar)) {
                 if (this.Changed || this.Elemento.Existe == false) {
                         Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Antes de editar los permisos debe guardar los cambios en este formulario. ¿Desea guardar ahora?", "Editar Permisos");
                         Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                         if (this.Elemento.Existe)
                                 this.ShowChanged = true;
                         DialogResult Respuesta = Pregunta.ShowDialog();
                         this.ShowChanged = false;
                         if (Respuesta != DialogResult.OK) {
                                 return new Lfx.Types.CancelOperationResult();
                         } else {
                                 Lfx.Types.OperationResult ResultadoGuardar = this.Save();
                                 if (ResultadoGuardar.Success == false)
                                         return ResultadoGuardar;
                         }
                 }
                 Lfx.Workspace.Master.RunTime.Execute("EDITAR Lbl.Personas.Usuario " + this.Elemento.Id.ToString());
                 return new Lfx.Types.SuccessOperationResult();
         } else {
                 return new Lfx.Types.NoAccessOperationResult();
         }
 }
Example #35
0
 private void DepositarPagar_Click(object sender, System.EventArgs e)
 {
         if (this.Emitidos == false) {
                 //Depositar
                 Lbl.ListaIds Codigos = this.CodigosSeleccionados;
                 if (Codigos == null || Codigos.Count == 0) {
                         Lui.Forms.MessageBox.Show("Por favor seleccione uno o más cheques.", "Error");
                 } else {
                         Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Al depositar un cheque en una cuenta bancaria propia, puede marcarlo como depositado para control interno.\nSirve sólamente para depositos en cajas propias. Para depósitos en cajas de terceros utilice la opción 'Efectivizar'.", "¿Desea marcar los cheques seleccionados como depositados?");
                         if (Pregunta.ShowDialog() == DialogResult.OK) {
                                 using (IDbTransaction Trans = this.Connection.BeginTransaction()) {
                                         qGen.Update Depo = new qGen.Update("bancos_cheques");
                                         Depo.Fields.AddWithValue("estado", 5);
                                         Depo.WhereClause = new qGen.Where();
                                         Depo.WhereClause.AddWithValue("estado", 0);
                                         Depo.WhereClause.AddWithValue("id_cheque", qGen.ComparisonOperators.In, Codigos);
                                         this.Connection.Execute(Depo);
                                         Trans.Commit();
                                 }
                                 foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) {
                                         if (itm.Checked)
                                                 itm.Checked = false;
                                 }
                                 this.RefreshList();
                         }
                 }
         } else {
                 Lfx.Types.OperationResult Res = this.Pagar();
                 if (Res.Success == false && Res.Message != null)
                         Lfx.Workspace.Master.RunTime.Toast(Res.Message, "Error");
         }
 }
Example #36
0
                public override Lfx.Types.OperationResult ValidarControl()
                {
                        if (EntradaTipo.ValueInt <= 0)
                                return new Lfx.Types.FailureOperationResult("Seleccione el tipo de cliente");

                        Lbl.Personas.Persona Cliente = this.Elemento as Lbl.Personas.Persona;

                        if (EntradaRazonSocial.Text.Length == 0 && EntradaNombre.Text.Length == 0 && EntradaApellido.Text.Length == 0) {
                                return new Lfx.Types.FailureOperationResult("Escriba el nombre y el apellido o la razón social");
                        } else {
                                //Busco un cliente con datos similares
                                Lfx.Data.Row ClienteDup = null;
                                string Sql = @"SELECT id_persona, nombre_visible, domicilio, telefono, cuit, email FROM personas WHERE (";
                                if (this.Text.Length > 0)
                                        Sql += @"nombre_visible LIKE '%" + this.Connection.EscapeString(this.Text.Replace("%", "").Replace("_", "")) + @"%'";
                                if (EntradaDomicilio.Text.Length > 0)
                                        Sql += @" OR domicilio LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaDomicilio.Text) + @"%'";

                                if (EntradaNumDoc.Text.Length > 0)
                                        Sql += @" OR REPLACE(num_doc, '.', '') LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaNumDoc.Text.Replace(".", "")) + @"%'";

                                if (EntradaTelefono.Text.Length > 0) {
                                        string Telefono = EntradaTelefono.Text.Replace(" -", "").Replace("- ", "").Replace("/", " ").Replace(",", " ").Replace(".", " ").Replace("  ", " ").Replace("%", "").Replace("_", "");
                                        IList<string> Telefonos = Lfx.Types.Strings.SplitDelimitedString(Telefono, ";");
                                        if (Telefonos != null && Telefonos.Count > 0) {
                                                foreach (string Tel in Telefonos) {
                                                        if (Tel != null && Tel.Length > 4)
                                                                Sql += @" OR telefono LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(Tel.Replace("%", "").Replace("_", "")) + @"%'";
                                                }
                                        }
                                }
                                if (EntradaEmail.Text.Length > 0)
                                        Sql += @" OR email LIKE '%" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaEmail.Text.Replace("%", "").Replace("_", "")) + @"%'";
                                if (EntradaClaveTributaria.Text.Length > 0)
                                        Sql += @" OR cuit='" + Lfx.Workspace.Master.MasterConnection.EscapeString(EntradaClaveTributaria.Text.Replace("%", "").Replace("_", "")) + @"'";
                                Sql += @") AND id_persona<>" + this.Elemento.Id.ToString();

                                ClienteDup = this.Connection.FirstRowFromSelect(Sql);
                                if (ClienteDup != null) {
                                        if (Cliente != null && Cliente.Existe == false) {
                                                AltaDuplicada FormAltaDuplicada = new AltaDuplicada();
                                                ListViewItem itm;
                                                itm = FormAltaDuplicada.ListaComparacion.Items.Add("Nombre");
                                                itm.SubItems.Add(ClienteDup["nombre_visible"].ToString());
                                                itm.SubItems.Add(this.Text);
                                                itm = FormAltaDuplicada.ListaComparacion.Items.Add("Domicilio");
                                                itm.SubItems.Add(ClienteDup["domicilio"].ToString());
                                                itm.SubItems.Add(EntradaDomicilio.Text);
                                                itm = FormAltaDuplicada.ListaComparacion.Items.Add("Teléfono");
                                                itm.SubItems.Add(ClienteDup["telefono"].ToString());
                                                itm.SubItems.Add(EntradaTelefono.Text);
                                                itm = FormAltaDuplicada.ListaComparacion.Items.Add(Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre);
                                                if (ClienteDup["cuit"] != null)
                                                        itm.SubItems.Add(ClienteDup["cuit"].ToString());
                                                else
                                                        itm.SubItems.Add("");
                                                itm.SubItems.Add(EntradaClaveTributaria.Text);
                                                itm = FormAltaDuplicada.ListaComparacion.Items.Add("E-mail");
                                                itm.SubItems.Add(ClienteDup["email"].ToString());
                                                itm.SubItems.Add(EntradaEmail.Text);

                                                switch (FormAltaDuplicada.ShowDialog()) {
                                                        case DialogResult.Yes:
                                                                //Crear uno nuevo
                                                                return new Lfx.Types.SuccessOperationResult();
                                                        case DialogResult.No:
                                                                //Actualizar
                                                                this.Elemento = new Lbl.Personas.Persona(this.Elemento.Connection, System.Convert.ToInt32(ClienteDup["id_persona"]));
                                                                return new Lfx.Types.SuccessOperationResult();
                                                        case DialogResult.Cancel:
                                                                //Volver a la edición
                                                                return new Lfx.Types.OperationResult(false);
                                                }
                                        }
                                }
                        }

                        switch (Lbl.Sys.Config.Pais.ClaveBancaria.Nombre) {
                                case "CBU":
                                        if (EntradaClaveBancaria.Text.Length > 0 && Lbl.Bancos.Claves.Cbu.EsValido(EntradaClaveBancaria.Text) == false) {
                                                return new Lfx.Types.FailureOperationResult("La CBU es incorrecta.");
                                        }
                                        break;
                        }


                        if (Cliente.Existe == false && Cliente.Grupo != null && Cliente.Grupo.Id == 2 && (EntradaClaveBancaria.Text.Length > 0 || EntradaNumeroCuenta.Text.Length > 0) && EntradaTipoCuenta.TextKey == "0")
                        {
                                return new Lfx.Types.FailureOperationResult("Por favor seleccione el tipo de cuenta bancaria.");
                        }


                        if (Lbl.Sys.Config.Pais.ClavePersonasJuridicas != null) {
                                switch (Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre) {
                                        case "CUIT":
                                                if (EntradaClaveTributaria.Text.Length > 0) {
                                                        if (EntradaSituacion.ValueInt == 1) {
                                                                return new Lfx.Types.FailureOperationResult(@"Un Cliente con CUIT no debe estar en Situación de ""Consumidor Final"".");
                                                        }
                                                        if (System.Text.RegularExpressions.Regex.IsMatch(EntradaClaveTributaria.Text, @"^\d{11}$")) {
                                                                EntradaClaveTributaria.Text = EntradaClaveTributaria.Text.Substring(0, 2) + "-" + EntradaClaveTributaria.Text.Substring(2, 8) + "-" + EntradaClaveTributaria.Text.Substring(10, 1);
                                                        }

                                                        //Agrego los guiones si no los tiene
                                                        if (EntradaClaveTributaria.Text.Length == 11)
                                                                EntradaClaveTributaria.Text = EntradaClaveTributaria.Text.Substring(0, 2) + "-" + EntradaClaveTributaria.Text.Substring(2, 8) + "-" + EntradaClaveTributaria.Text.Substring(10, 1);

                                                        if (Lbl.Personas.Claves.Cuit.EsValido(EntradaClaveTributaria.Text) == false) {
                                                                return new Lfx.Types.FailureOperationResult("La CUIT no es correcta." + Environment.NewLine + "El sistema le permite dejar la CUIT en blanco, pero no aceptará una incorrecta.");
                                                        }
                                                }
                                                break;
                                }
                        }

                        if (EntradaClaveTributaria.Text.Length > 0) {
                                Lfx.Data.Row RowPersMismaClave = this.Connection.FirstRowFromSelect("SELECT id_persona FROM personas WHERE cuit='" + EntradaClaveTributaria.Text + "' AND id_persona<>" + this.Elemento.Id.ToString());
                                if (RowPersMismaClave != null) {
                                        if (Cliente.Existe == false || System.Convert.ToInt32(RowPersMismaClave["id_persona"]) != this.Elemento.Id) {
                                                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Ya existe una empresa o persona con esa clave tributaria (" + Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre + ") en la base de datos. ¿Desea continuar y crear una nueva de todos modos?", "Clave tributaria duplicada");
                                                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                                if (Pregunta.ShowDialog() != DialogResult.OK) {
                                                        return new Lfx.Types.FailureOperationResult("Cambie la Clave tributaria (" + Lbl.Sys.Config.Pais.ClavePersonasJuridicas.Nombre + ") para antes de continuar.");
                                                }
                                        }
                                }
                        }

                        return new Lfx.Types.SuccessOperationResult();
                }
Example #37
0
        public override Lfx.Types.OperationResult Ok()
        {
            int PV       = EntradaPV.ValueInt;
            int Desde    = EntradaDesde.ValueInt;
            int Hasta    = EntradaHasta.ValueInt;
            int Cantidad = Hasta - Desde + 1;

            Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Una vez anulados, los comprobantes deberán ser archivados en todas sus copias y no podrán ser rehabilitados ni reutilizados.", "¿Está seguro de que desea anular " + Cantidad.ToString() + " comprobantes?");
            Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

            if (Pregunta.ShowDialog() == DialogResult.OK)
            {
                bool AnularPagos = EntradaAnularPagos.ValueInt != 0;

                int    m_Id         = 0;
                string IncluyeTipos = "";

                switch (EntradaTipo.TextKey)
                {
                case "A":
                    IncluyeTipos = "'FA', 'NCA', 'NDA'";
                    break;

                case "B":
                    IncluyeTipos = "'FB', 'NCB', 'NDB'";
                    break;

                case "C":
                    IncluyeTipos = "'FC', 'NCC', 'NDC'";
                    break;

                case "E":
                    IncluyeTipos = "'FE', 'NCE', 'NDE'";
                    break;

                case "M":
                    IncluyeTipos = "'FM', 'NCM', 'NDM'";
                    break;

                case "T":
                    IncluyeTipos = "'T'";
                    break;

                default:
                    IncluyeTipos = "'" + EntradaTipo.TextKey + "'";
                    break;
                }

                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Anulando comprobantes", "Se están anulando los comprobantes seleccionados.");
                Progreso.Cancelable = true;
                Progreso.Max        = Cantidad;
                Progreso.Begin();

                IDbTransaction Trans = this.Connection.BeginTransaction(IsolationLevel.Serializable);
                for (int Numero = Desde; Numero <= Hasta; Numero++)
                {
                    int IdFactura = Connection.FieldInt("SELECT id_comprob FROM comprob WHERE impresa=1 AND tipo_fac IN (" + IncluyeTipos + ") AND pv=" + PV.ToString() + " AND numero=" + Numero.ToString() + " ORDER BY anulada");

                    if (IdFactura == 0)
                    {
                        // Es una factura que todava no existe
                        // Tengo que crear la factura y anularla
                        qGen.Insert InsertarComprob = new qGen.Insert("comprob");
                        InsertarComprob.ColumnValues.AddWithValue("tipo_fac", "F" + EntradaTipo.TextKey);
                        InsertarComprob.ColumnValues.AddWithValue("id_formapago", 3);
                        InsertarComprob.ColumnValues.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual);
                        InsertarComprob.ColumnValues.AddWithValue("pv", Lfx.Types.Parsing.ParseInt(EntradaPV.Text));
                        InsertarComprob.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
                        InsertarComprob.ColumnValues.AddWithValue("id_vendedor", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                        InsertarComprob.ColumnValues.AddWithValue("id_cliente", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                        InsertarComprob.ColumnValues.AddWithValue("obs", "Comprobante anulado antes de ser impreso.");
                        InsertarComprob.ColumnValues.AddWithValue("impresa", 1);
                        InsertarComprob.ColumnValues.AddWithValue("anulada", 1);
                        Connection.ExecuteNonQuery(InsertarComprob);
                        m_Id = Connection.FieldInt("SELECT LAST_INSERT_ID()");
                        Lbl.Comprobantes.ComprobanteConArticulos NuevoComprob = new Lbl.Comprobantes.ComprobanteConArticulos(this.Connection, m_Id);
                        new Lbl.Comprobantes.Numerador(NuevoComprob).Numerar(true);
                    }
                    else
                    {
                        Lbl.Comprobantes.ComprobanteConArticulos Fac = new Lbl.Comprobantes.ComprobanteConArticulos(Connection, IdFactura);
                        if (Fac.Anulado == false)
                        {
                            Fac.Anular(AnularPagos);
                        }
                    }

                    Progreso.Advance(1);
                    if (Progreso.Cancelar)
                    {
                        break;
                    }
                }

                Progreso.End();

                if (Progreso.Cancelar)
                {
                    Trans.Rollback();
                    Lfx.Workspace.Master.RunTime.Toast("La operación fue cancelada.", "Aviso");
                }
                else
                {
                    Trans.Commit();
                    ProximosNumeros.Clear();
                    if (this.DeCompra)
                    {
                        Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Si fueron anulados por error de carga, ahora puede cargarlos nuevamente.", "Aviso");
                    }
                    else
                    {
                        Lui.Forms.MessageBox.Show("Se anularon los comprobantes seleccionados. Recuerde archivar ambas copias.", "Aviso");
                    }
                }

                EntradaDesde.ValueInt = 0;
                EntradaHasta.ValueInt = 0;
                EntradaDesde.Focus();

                return(base.Ok());
            }
            else
            {
                return(new Lfx.Types.FailureOperationResult("La operación fue cancelada."));
            }
        }
Example #38
0
        private Lfx.Types.OperationResult Facturar()
        {
            Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("¿Desea guardar los cambios realizados y generar una factura a partir de esta tarea?", "Facturar");
            if (Pregunta.ShowDialog() != DialogResult.OK)
            {
                return(new Lfx.Types.CancelOperationResult());
            }

            if (EntradaEstado.ValueInt < 50)
            {
                EntradaEstado.ValueInt = 50;
            }

            Lfx.Types.OperationResult Res = this.Save();
            if (Res.Success == false)
            {
                return(Res);
            }

            Lbl.Tareas.Tarea Tarea = this.Elemento as Lbl.Tareas.Tarea;
            Lbl.Comprobantes.ComprobanteFacturable Factura;

            Lfx.Data.Connection ConnFacturaNueva = Lfx.Workspace.Master.GetNewConnection("Convertir tarea en factura");

            if (Tarea.Factura != null && Tarea.Factura.Anulado == false)
            {
                // Ya fue facturada... lo muestro
                Factura = Tarea.Factura;
            }
            else
            {
                // No tiene comprobante, lo creo
                Factura = new Lbl.Comprobantes.Factura(ConnFacturaNueva);

                Factura.Crear();
                Factura.Cliente            = EntradaCliente.Elemento as Lbl.Personas.Persona;
                Factura.Cliente.Connection = ConnFacturaNueva;
                Factura.Tipo                = Factura.Cliente.ObtenerTipoComprobante();
                Factura.Tipo.Connection     = ConnFacturaNueva;
                Factura.Vendedor            = EntradaEncargado.Elemento as Lbl.Personas.Persona;
                Factura.Vendedor.Connection = ConnFacturaNueva;
                Factura.Obs = EntradaTarea.TextDetail + " s/" + this.Elemento.ToString();
                if (Tarea.Articulos.Count > 0)
                {
                    Factura.Articulos.AddRange(Tarea.Articulos);
                }
                else if (Tarea.Presupuesto != null && Tarea.Presupuesto.Articulos.Count > 0)
                {
                    Factura.Articulos.AddRange(Tarea.Presupuesto.Articulos);
                    Factura.Descuento = Tarea.Presupuesto.Descuento;
                }

                if (EntradaImportePresupuesto.ValueDecimal > 0)
                {
                    Lbl.Comprobantes.DetalleArticulo Art = new Lbl.Comprobantes.DetalleArticulo(Factura);

                    Art.Nombre   = this.Elemento.ToString();
                    Art.Unitario = EntradaImportePresupuesto.ValueDecimal;
                    Art.Cantidad = 1;

                    Factura.Articulos.Add(Art);
                }
            }

            Lfc.FormularioEdicion FormularioFactura = Lfc.Instanciador.InstanciarFormularioEdicion(Factura);
            FormularioFactura.MdiParent      = this.ParentForm.MdiParent;
            FormularioFactura.ControlDestino = EntradaComprobanteId;

            FormularioFactura.Show();
            return(new Lfx.Types.SuccessOperationResult());
        }
Example #39
0
 private void BotonEliminar_Click(object sender, System.EventArgs e)
 {
         if (Listado.SelectedItems.Count > 0 && Listado.SelectedItems[0] != null) {
                 string NombreCarpeta = Listado.SelectedItems[0].Text;
                 Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Puede eliminar una copia de seguridad antigua o que ya no sea de utilidad. Al eliminar una copia de seguridad no se modificarán los datos actualmente almacenados en el sistema, ni tampoco se impide que el sistema haga nuevas copias de seguridad.", "¿Desea eliminar la copia de seguridad seleccionada?");
                 Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                 if (Pregunta.ShowDialog() == DialogResult.OK) {
                         this.BackupManager.Delete(NombreCarpeta);
                         MostrarListaBackups();
                 }
         }
 }
Example #40
0
                public override Lfx.Types.OperationResult Ok()
                {
                        int PV = EntradaPV.ValueInt;
                        int Desde = EntradaDesde.ValueInt;
                        int Hasta = EntradaHasta.ValueInt;
                        int Cantidad = Hasta - Desde + 1;

                        int DesdeReal, HastaReal;
                        if (EntradaOrden.TextKey == "1") {
                                DesdeReal = Hasta;
                                HastaReal = Desde - 1;
                        } else {
                                DesdeReal = Desde;
                                HastaReal = Hasta + 1;
                        }

                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Por favor verifique que impresora tenga " + Cantidad.ToString() + " comprobantes, iniciando con el Nº " + PV.ToString("0000") + "-" + DesdeReal.ToString("00000000"), "¿Está seguro de que desea reimprimir " + Cantidad.ToString() + " comprobantes?");
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                        if (Pregunta.ShowDialog() == DialogResult.OK) {
                                System.Threading.ThreadStart ThreadFiltro = delegate { ProcesarReimpresion(EntradaTipo.TextKey, PV, DesdeReal, HastaReal); ; };
                                System.Threading.Thread Thr = new System.Threading.Thread(ThreadFiltro);
                                Thr.IsBackground = true;
                                Thr.Start();

                                ProximosNumeros.Clear();

                                EntradaDesde.Text = "0";
                                EntradaHasta.Text = "0";
                                EntradaDesde.Focus();

                                return new Lfx.Types.CancelOperationResult();
                        } else {
                                return new Lfx.Types.FailureOperationResult("La operación fue cancelada.");
                        }
                }
Example #41
0
        private void Imprimir()
        {
            Lfx.Types.OperationResult Res;
            if (this.ReadOnly)
            {
                Res = new Lfx.Types.SuccessOperationResult();
            }
            else
            {
                if (this.Elemento.Existe == false)
                {
                    // Si es nuevo, lo guardo sin preguntar.
                    Res = this.Save();
                }
                else if (this.Changed)
                {
                    // Si es edición, y hay cambios, pregunto si quiere guardar
                    using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Hay modificaciones sin guardar (subrayadas en color rojo). Antes de imprimir el ducumento se guardarán las modificaciones. ¿Desea continuar?", "Imprimir")) {
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                        this.ShowChanged       = true;
                        if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            Res = this.Save();
                        }
                        else
                        {
                            Res = new Lfx.Types.CancelOperationResult();
                        }
                        this.ShowChanged = false;
                    }
                }
                else
                {
                    // Es edición y no hay cambios... continúo
                    Res = new Lfx.Types.SuccessOperationResult();
                }
            }

            if (Res.Success)
            {
                Res = this.ControlUnico.BeforePrint();
            }

            if (Res.Success)
            {
                Lbl.Impresion.Impresora Impresora = null;
                if ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) == Keys.Shift)
                {
                    using (Lui.Printing.PrinterSelectionDialog FormularioSeleccionarImpresora = new Lui.Printing.PrinterSelectionDialog()) {
                        if (FormularioSeleccionarImpresora.ShowDialog() == DialogResult.OK)
                        {
                            Impresora = FormularioSeleccionarImpresora.SelectedPrinter;
                        }
                        else
                        {
                            return;
                        }
                    }
                }

                string NombreDocumento          = Elemento.ToString();
                Lbl.Impresion.CargasPapel Carga = Lbl.Impresion.CargasPapel.Automatica;
                if (Impresora != null && Impresora.CargaPapel == Lbl.Impresion.CargasPapel.Manual)
                {
                    Carga = Lbl.Impresion.CargasPapel.Manual;
                }
                else if (this.Elemento is Lbl.Comprobantes.ComprobanteConArticulos)
                {
                    Lbl.Comprobantes.ComprobanteConArticulos Comprob = this.Elemento as Lbl.Comprobantes.ComprobanteConArticulos;

                    if (Lbl.Comprobantes.PuntoDeVenta.TodosPorNumero[Comprob.PV].Tipo == Lbl.Comprobantes.TipoPv.Fiscal)
                    {
                        Carga = Lbl.Impresion.CargasPapel.Automatica;
                    }
                    else
                    {
                        // El tipo de comprobante puede forzar a una carga manual
                        Carga = Comprob.Tipo.CargaPapel;

                        // Intento averiguar el número de comprobante, en caso de que aun no esté numerado
                        if (Comprob.Numero == 0)
                        {
                            int ProximoNumero = Lbl.Comprobantes.Numerador.ProximoNumero(Comprob);
                            NombreDocumento = NombreDocumento.Replace("00000000", ProximoNumero.ToString("00000000"));
                        }
                    }
                }

                if (Carga == Lbl.Impresion.CargasPapel.Manual)
                {
                    using (Lui.Printing.ManualFeedDialog FormularioCargaManual = new Lui.Printing.ManualFeedDialog()) {
                        FormularioCargaManual.DocumentName = NombreDocumento;
                        // Muestro el nombre de la impresora
                        if (Impresora != null)
                        {
                            FormularioCargaManual.PrinterName = Impresora.Nombre;
                        }
                        else
                        {
                            System.Drawing.Printing.PrinterSettings ObjPrint = new System.Drawing.Printing.PrinterSettings();
                            FormularioCargaManual.PrinterName = ObjPrint.PrinterName;
                        }
                        if (FormularioCargaManual.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                }

                if (Impresora != null && Impresora.EsVistaPrevia)
                {
                    Lazaro.Impresion.ImpresorElemento ImpresorVistaPrevia = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, null);
                    ImpresorVistaPrevia.PrintController = new System.Drawing.Printing.PreviewPrintController();
                    Lui.Printing.PrintPreviewForm VistaPrevia = new Lui.Printing.PrintPreviewForm();
                    VistaPrevia.MdiParent             = this.ParentForm.MdiParent;
                    VistaPrevia.PrintPreview.Document = ImpresorVistaPrevia;
                    VistaPrevia.Show();
                }
                else
                {
                    Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Imprimiendo", "El documento se está enviando a la impresora.");
                    if (Impresora != null)
                    {
                        Progreso.Description = "El documento se está enviando a la impresora " + Impresora.ToString();
                    }
                    Progreso.Modal = false;
                    Progreso.Begin();

                    using (IDbTransaction Trans = this.Elemento.Connection.BeginTransaction()) {
                        Lazaro.Impresion.ImpresorElemento Impresor = Lazaro.Impresion.Instanciador.InstanciarImpresor(this.Elemento, Trans);
                        Impresor.Impresora = Impresora;
                        try {
                            Res = Impresor.Imprimir();
                        } catch (Exception ex) {
                            Res = new Lfx.Types.FailureOperationResult(ex.Message);
                        }
                        Progreso.End();
                        if (Res.Success == false)
                        {
                            if (Impresor.Transaction != null)
                            {
                                // Puede que la transacción ya haya sido finalizada por el impresor
                                Impresor.Transaction.Rollback();
                            }
                            Lui.Forms.MessageBox.Show(Res.Message, "Error");
                        }
                        else
                        {
                            if (Impresor.Transaction != null)
                            {
                                // Puede que la transacción ya haya sido finalizada por el impresor
                                Impresor.Transaction.Commit();
                            }
                            this.Elemento.Cargar();
                            this.FromRow(this.Elemento);
                            this.ControlUnico.AfterPrint();
                        }
                    }
                }
            }

            if (Res.Success == false && Res.Message != null)
            {
                Lui.Forms.MessageBox.Show(Res.Message, "Imprimir");
            }
        }
Example #42
0
                private void EventoProgramador(object source, System.Timers.ElapsedEventArgs e)
                {
                        Programador.Stop();
                        Watchdog_LastOp = System.DateTime.Now;

                        //Busco un PV que corresponda a esta terminal
                        if (this.PV == 0) {
                                Programador.Start();
                                return;
                        }

                        Watchdog.Stop();
                        try {
                                using (IDbTransaction Trans = this.Impresora.DataBase.BeginTransaction()) {
                                        qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
                                        Actualizar.Fields.AddWithValue("lsa", qGen.SqlFunctions.Now);
                                        this.Impresora.DataBase.Execute(Actualizar);
                                        Trans.Commit();
                                }
                        } catch {
                                // Nada
                                }

                        Lfx.Services.Task ProximaTarea = Lfx.Workspace.Master.DefaultScheduler.GetNextTask("fiscal" + this.PV.ToString());
                        if (ProximaTarea != null) {
                                string Comando = ProximaTarea.Command;
                                string SubComando = Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim().ToUpper();

                                Lazaro.Impresion.Comprobantes.Fiscal.Respuesta Res;
                                switch (SubComando) {
                                        case "REBOOT":
                                                FormEstado.MostrarEstado("Reiniciando...");
                                                Impresora.EstadoServidor = Lazaro.Impresion.Comprobantes.Fiscal.EstadoServidorFiscal.Reiniciando;
                                                //this.End(true);
                                                break;

                                        case "END":
                                                FormEstado.MostrarEstado("Cerrando...");
                                                Impresora.EstadoServidor = Lazaro.Impresion.Comprobantes.Fiscal.EstadoServidorFiscal.Apagando;
                                                //this.End(false);
                                                break;

                                        case "CIERRE":
                                                FormEstado.MostrarEstado("Imprimiendo cierre...");
                                                Res = Impresora.ObtenerEstadoImpresora();
                                                if (Res.EstadoFiscal.DocumentoFiscalAbierto) {
                                                        Res = Impresora.CancelarDocumentoFiscal();
                                                        System.Threading.Thread.Sleep(500);
                                                } else if (Res.Error == Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok) {
                                                        string SubComandoCierre = Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim().ToUpper();
                                                        Lazaro.Impresion.Comprobantes.Fiscal.Respuesta ResultadoCierre = Impresora.Cierre(SubComandoCierre, true);
                                                        if (SubComandoCierre == "Z" && ResultadoCierre.Error == Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok) {
                                                                //Si hizo un cierre Z correctamente, actualizo la variable LCZ
                                                                using (IDbTransaction Trans = this.Impresora.DataBase.BeginTransaction()) {
                                                                        qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
                                                                        Actualizar.Fields.AddWithValue("ultimoz", qGen.SqlFunctions.Now);
                                                                        this.Impresora.DataBase.Execute(Actualizar);
                                                                        Trans.Commit();
                                                                }
                                                        }
                                                        if (ResultadoCierre.Error != Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok) {
                                                                MostrarErrorFiscal(ResultadoCierre);
                                                        }
                                                        System.Threading.Thread.Sleep(100);
                                                }
                                                break;

                                        case "CANCELAR":
                                                FormEstado.MostrarEstado("Cancelando comprobante...");
                                                string ItemCancelar = Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim().ToUpper();
                                                switch (ItemCancelar) {
                                                        case "FISCAL":
                                                                Impresora.CancelarDocumentoFiscal();
                                                                System.Threading.Thread.Sleep(500);
                                                                break;
                                                }
                                                break;

                                        case "IMPRIMIR":
                                                FormEstado.MostrarEstado("Imprimiendo...");
                                                int IdFactura = Lfx.Types.Parsing.ParseInt(Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim());
                                                Res = Impresora.ObtenerEstadoImpresora();

                                                if (Res.EstadoFiscal.DocumentoFiscalAbierto) {
                                                        Res = Impresora.CancelarDocumentoFiscal();
                                                        System.Threading.Thread.Sleep(500);
                                                }

                                                if (Res.HacerCierreZ) {
                                                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Hacer Cierre Z", "Es obligatorio hacer un Cierre Z antes de continuar. ¿Desea hacer el cierre ahora?");
                                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                                                        if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                                                                // Hago el cierre, y Res es el resultado del cierre
                                                                Res = Impresora.Cierre("Z", true);
                                                                System.Threading.Thread.Sleep(500);
                                                        } else {
                                                                // No quiso hacer el cierre. Devuelvo un error
                                                                Programador.Start();
                                                                Watchdog.Start();
                                                                return;
                                                        }
                                                }

                                                if (Res.Error == Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok)
                                                        Res = Impresora.ImprimirComprobante(IdFactura);

                                                if (Res.Error != Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok) {
                                                        MostrarErrorFiscal(Res);
                                                        FormEstado.MostrarEstado("Cancelando documento...");
                                                        if (Res.EstadoFiscal.DocumentoFiscalAbierto)
                                                                Res = Impresora.CancelarDocumentoFiscal();
                                                        Programador.Start();
                                                        Watchdog.Start();
                                                        return;
                                                }
                                                break;
                                }
                        }
                        Programador.Start();
                        Watchdog.Start();
                }
Example #43
0
        private void EventoProgramador(object source, System.Timers.ElapsedEventArgs e)
        {
            Programador.Stop();
            Watchdog_LastOp = System.DateTime.Now;

            //Busco un PV que corresponda a esta terminal
            if (this.PV == 0)
            {
                Programador.Start();
                return;
            }

            Watchdog.Stop();
            try {
                using (IDbTransaction Trans = this.Impresora.DataBase.BeginTransaction()) {
                    qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
                    Actualizar.Fields.AddWithValue("lsa", qGen.SqlFunctions.Now);
                    this.Impresora.DataBase.Execute(Actualizar);
                    Trans.Commit();
                }
            } catch {
                // Nada
            }

            Lfx.Services.Task ProximaTarea = Lfx.Workspace.Master.DefaultScheduler.GetNextTask("fiscal" + this.PV.ToString());
            if (ProximaTarea != null)
            {
                string Comando    = ProximaTarea.Command;
                string SubComando = Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim().ToUpper();

                Lazaro.Impresion.Comprobantes.Fiscal.Respuesta Res;
                switch (SubComando)
                {
                case "REBOOT":
                    FormEstado.MostrarEstado("Reiniciando...");
                    Impresora.EstadoServidor = Lazaro.Impresion.Comprobantes.Fiscal.EstadoServidorFiscal.Reiniciando;
                    //this.End(true);
                    break;

                case "END":
                    FormEstado.MostrarEstado("Cerrando...");
                    Impresora.EstadoServidor = Lazaro.Impresion.Comprobantes.Fiscal.EstadoServidorFiscal.Apagando;
                    //this.End(false);
                    break;

                case "CIERRE":
                    FormEstado.MostrarEstado("Imprimiendo cierre...");
                    Res = Impresora.ObtenerEstadoImpresora();
                    if (Res.EstadoFiscal.DocumentoFiscalAbierto)
                    {
                        Res = Impresora.CancelarDocumentoFiscal();
                        System.Threading.Thread.Sleep(500);
                    }
                    else if (Res.Error == Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok)
                    {
                        string SubComandoCierre = Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim().ToUpper();
                        Lazaro.Impresion.Comprobantes.Fiscal.Respuesta ResultadoCierre = Impresora.Cierre(SubComandoCierre, true);
                        if (SubComandoCierre == "Z" && ResultadoCierre.Error == Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok)
                        {
                            //Si hizo un cierre Z correctamente, actualizo la variable LCZ
                            using (IDbTransaction Trans = this.Impresora.DataBase.BeginTransaction()) {
                                qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
                                Actualizar.Fields.AddWithValue("ultimoz", qGen.SqlFunctions.Now);
                                this.Impresora.DataBase.Execute(Actualizar);
                                Trans.Commit();
                            }
                        }
                        if (ResultadoCierre.Error != Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok)
                        {
                            MostrarErrorFiscal(ResultadoCierre);
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                    break;

                case "CANCELAR":
                    FormEstado.MostrarEstado("Cancelando comprobante...");
                    string ItemCancelar = Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim().ToUpper();
                    switch (ItemCancelar)
                    {
                    case "FISCAL":
                        Impresora.CancelarDocumentoFiscal();
                        System.Threading.Thread.Sleep(500);
                        break;
                    }
                    break;

                case "IMPRIMIR":
                    FormEstado.MostrarEstado("Imprimiendo...");
                    int IdFactura = Lfx.Types.Parsing.ParseInt(Lfx.Types.Strings.GetNextToken(ref Comando, " ").Trim());
                    Res = Impresora.ObtenerEstadoImpresora();

                    if (Res.EstadoFiscal.DocumentoFiscalAbierto)
                    {
                        Res = Impresora.CancelarDocumentoFiscal();
                        System.Threading.Thread.Sleep(500);
                    }

                    if (Res.HacerCierreZ)
                    {
                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Hacer Cierre Z", "Es obligatorio hacer un Cierre Z antes de continuar. ¿Desea hacer el cierre ahora?");
                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;

                        if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            // Hago el cierre, y Res es el resultado del cierre
                            Res = Impresora.Cierre("Z", true);
                            System.Threading.Thread.Sleep(500);
                        }
                        else
                        {
                            // No quiso hacer el cierre. Devuelvo un error
                            Programador.Start();
                            Watchdog.Start();
                            return;
                        }
                    }

                    if (Res.Error == Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok)
                    {
                        Res = Impresora.ImprimirComprobante(IdFactura);
                    }

                    if (Res.Error != Lazaro.Impresion.Comprobantes.Fiscal.ErroresFiscales.Ok)
                    {
                        MostrarErrorFiscal(Res);
                        FormEstado.MostrarEstado("Cancelando documento...");
                        if (Res.EstadoFiscal.DocumentoFiscalAbierto)
                        {
                            Res = Impresora.CancelarDocumentoFiscal();
                        }
                        Programador.Start();
                        Watchdog.Start();
                        return;
                    }
                    break;
                }
            }
            Programador.Start();
            Watchdog.Start();
        }
Example #44
0
 private void BotonCambiarPais_Click(object sender, System.EventArgs e)
 {
         using (Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Al cambiar el país, Lázaro cambiará varios ajustes del sistema como la moneda, las tasas del IVA y los tipos de comprobante. ¿Está seguro de que quiere cambiar el país?", "Cambiar país")) {
                 Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                 if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                         EntradaPais.ReadOnly = false;
                         BotonCambiarPais.Visible = false;
                         EntradaPais.Focus();
                 }
         }
 }
                private void Listado_KeyDown(object sender, KeyEventArgs e)
                {
                        if (e.Shift == false && e.Alt == false && e.Control == false) {
                                switch (e.KeyCode) {
                                        case Keys.Return:
                                                if (Listado.SelectedItems.Count > 0) {
                                                        e.Handled = true;
                                                        Lfx.Types.OperationResult Res = this.OnItemClick(Listado.SelectedItems[0]);
                                                        if (Res.Success == false && Res.Message != null)
                                                                Lui.Forms.MessageBox.Show(Res.Message, "Error");
                                                }
                                                break;
                                        case Keys.Delete:
                                                if (this.HabilitarBorrar || this.EstadosEstandar) {
                                                        e.Handled = true;
                                                        Lbl.ListaIds Codigos = this.CodigosSeleccionados;

                                                        if (Lbl.Sys.Config.Actual.UsuarioConectado.TienePermiso(this.Definicion.ElementoTipo, Lbl.Sys.Permisos.Operaciones.Eliminar)) {
                                                                if (Codigos != null && Codigos.Count > 0) {
                                                                        string EstaSeguro = "¿Está seguro de que desea desactivar ";
                                                                        if (Codigos.Count == 1)
                                                                                EstaSeguro += "el elemento seleccionado?";
                                                                        else
                                                                                EstaSeguro += "los " + Codigos.Count.ToString() + " elementos seleccionado?";
                                                                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog(EstaSeguro, "Desactivar");
                                                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                                                        if (Pregunta.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                                                                                Lfx.Types.OperationResult Res = this.SolicitudEliminacion(Codigos);
                                                                                if (Res.Success == false && string.IsNullOrEmpty(Res.Message) == false)
                                                                                        Lfx.Workspace.Master.RunTime.Toast(Res.Message, "Error");
                                                                        }
                                                                }
                                                        } else {
                                                                Lfx.Workspace.Master.RunTime.Toast("No tiene permiso para desactivar registros.", "Aviso");
                                                        }
                                                } else {
                                                        Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Los elementos de este listado no se pueden eliminar ni desactivar. ¿Le gustaría ver una página web con más información sobre el tema?", "Eliminación");
                                                        Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                                        if (Pregunta.ShowDialog() == DialogResult.OK)
                                                                Help.ShowHelp(this, "http://www.lazarogestion.com/?q=node/49");
                                                }
                                                break;
                                }
                        }
                }
Example #46
0
                public override Lfx.Types.OperationResult ValidarControl()
                {
                        if (EntradaContrasena.Text.Length > 0) {
                                if (EntradaContrasena.Text.Length < 6 || EntradaContrasena.Text.Length > 32)
                                        return new Lfx.Types.FailureOperationResult("La contraseña debe tener entre 6 y 32 caracteres");
                        }

                        if (Listado.Items.Count == 0) {
                                Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("El usuario no tiene ningún permiso asignado y por lo tanto no podrá operar con el sistema. ¿Desea continuar de todos modos?", "Permisos");
                                Pregunta.DialogButtons = Lui.Forms.DialogButtons.YesNo;
                                if(Pregunta.ShowDialog() != DialogResult.OK)
                                        return new Lfx.Types.FailureOperationResult("Debe asignar al menos un permiso al usuario. Utilice la tecla 'Agregar' (F6) para asignar uno o más permisos.");
                        }

                        return base.ValidarControl();
                }