Beispiel #1
0
        /// <summary>
        /// Guarda los cambios que se hayan efectuado en las etiquetas.
        /// </summary>
        public void GuardarEtiquetas()
        {
            if (this.Existe == false)
            {
                throw new Lfx.Types.DomainException("No se pueden agregar etiquetas a un elemento que aun no ha sido guardado.");
            }

            // Elimino las etiquetas que ya no están.
            ColeccionGenerica <Etiqueta> ListaEtiquetas = this.Etiquetas.Quitados(m_EtiquetasOriginal);

            if (ListaEtiquetas != null && ListaEtiquetas.Count > 0)
            {
                qGen.Delete EliminarEtiquetas = new qGen.Delete("sys_labels_values");
                EliminarEtiquetas.WhereClause = new qGen.Where("item_id", this.Id);
                EliminarEtiquetas.WhereClause.Add(new qGen.ComparisonCondition("id_label", qGen.ComparisonOperators.In, ListaEtiquetas.GetAllIds()));
                this.Connection.ExecuteNonQuery(EliminarEtiquetas);
            }

            // Agrego las etiquetas nuevas.
            ListaEtiquetas = this.Etiquetas.Agregados(m_EtiquetasOriginal);
            if (ListaEtiquetas != null && ListaEtiquetas.Count > 0)
            {
                foreach (ElementoDeDatos El in ListaEtiquetas)
                {
                    qGen.Insert CrearEtiquetas = new qGen.Insert("sys_labels_values");
                    CrearEtiquetas.ColumnValues.AddWithValue("id_label", El.Id);
                    CrearEtiquetas.ColumnValues.AddWithValue("item_id", this.Id);
                    this.Connection.ExecuteNonQuery(CrearEtiquetas);
                }
            }
        }
Beispiel #2
0
        public void Desduplicar()
        {
            IDbTransaction Trans = null;

            if (this.Connection.InTransaction == false)
            {
                Trans = this.Connection.BeginTransaction(IsolationLevel.Serializable);
            }

            // Le doy tratamiento especial a algunas situaciones
            switch (TablaOriginal)
            {
            case "personas":
                // Quito la imagen del elemento duplicado... para que no choque con la original
                qGen.Delete QuitarImagen = new qGen.Delete("personas_imagenes");
                QuitarImagen.WhereClause = new qGen.Where("id_persona", this.IdDuplicado);
                this.Connection.ExecuteNonQuery(QuitarImagen);
                break;
            }

            // Busco una lista de relaciones entre tablas
            var Rels = this.ListaRelaciones();

            foreach (Lazaro.Orm.Data.Relation Rel in Rels)
            {
                // Cambio todas las referencias que apuntan al registro duplicado hacia el registro original
                qGen.Update Upd = new qGen.Update(Rel.ReferenceTable);
                Upd.ColumnValues.AddWithValue(Rel.ReferenceColumn, IdOriginal);
                Upd.WhereClause = new qGen.Where(Rel.ReferenceColumn, IdDuplicado);
                this.Connection.ExecuteNonQuery(Upd);
            }

            // Ahora que no queda nada apuntando al registro duplicado, lo elimino
            qGen.Delete Del = new qGen.Delete(this.TablaOriginal);
            Del.WhereClause = new qGen.Where(this.CampoIdOriginal, this.IdDuplicado);
            this.Connection.ExecuteNonQuery(Del);

            // Le doy tratamiento especial a algunas situaciones
            switch (TablaOriginal)
            {
            case "personas":
                // En personas, recalculo la cuenta corriente, ya que la nueva cuenta corriente es la fusión de las dos anteriores
                Lbl.Personas.Persona PersonaOriginal = new Lbl.Personas.Persona(this.Connection, IdOriginal);
                PersonaOriginal.CuentaCorriente.Recalcular();
                PersonaOriginal.AgregarComentario("Desduplicador: Se fusionaron los datos del elemento " + IdDuplicado);
                break;
                // En artículos, debería recalcular el historial de movimientos y el stock actual, pedidos, etc.
            }

            if (Trans != null)
            {
                Trans.Commit();
            }
        }
Beispiel #3
0
                public void Desduplicar()
                {
                        IDbTransaction Trans = null;

                        if(this.DataBase.InTransaction == false)
                                Trans = this.DataBase.BeginTransaction(IsolationLevel.Serializable);

                        // Le doy tratamiento especial a algunas situaciones
                        switch (TablaOriginal) {
                                case "personas":
                                        // Quito la imagen del elemento duplicado... para que no choque con la original
                                        qGen.Delete QuitarImagen = new qGen.Delete("personas_imagenes");
                                        QuitarImagen.WhereClause = new qGen.Where("id_persona", this.IdDuplicado);
                                        this.DataBase.Execute(QuitarImagen);
                                        break;
                        }

                        // Busco una lista de relaciones entre tablas
                        System.Collections.Generic.List<Lfx.Data.Relation> Rels = this.ListaRelaciones();
                        foreach (Lfx.Data.Relation Rel in Rels) {
                                // Cambio todas las referencias que apuntan al registro duplicado hacia el registro original
                                qGen.Update Upd = new qGen.Update(Rel.ReferenceTable);
                                Upd.Fields.AddWithValue(Rel.ReferenceColumn, IdOriginal);
                                Upd.WhereClause = new qGen.Where(Rel.ReferenceColumn, IdDuplicado);
                                this.DataBase.Execute(Upd);
                        }

                        // Ahora que no queda nada apuntando al registro duplicado, lo elimino
                        qGen.Delete Del = new qGen.Delete(this.TablaOriginal);
                        Del.WhereClause = new qGen.Where(this.CampoIdOriginal, this.IdDuplicado);
                        this.DataBase.Execute(Del);

                        // Le doy tratamiento especial a algunas situaciones
                        switch (TablaOriginal) {
                                case "personas":
                                        // En personas, recalculo la cuenta corriente, ya que la nueva cuenta corriente es la fusión de las dos anteriores
                                        Lbl.Personas.Persona PersonaOriginal = new Lbl.Personas.Persona(this.DataBase, IdOriginal);
                                        PersonaOriginal.CuentaCorriente.Recalcular();
                                        PersonaOriginal.AgregarComentario("Desduplicador: Se fusionaron los datos del elemento " + IdDuplicado);
                                        break;
                                        // En artículos, debería recalcular el historial de movimientos y el stock actual, pedidos, etc.
                        }

                        if (Trans != null)
                                Trans.Commit();
                }
Beispiel #4
0
        public bool DeleteGlobalSetting(string settingName, int branch)
        {
            if (branch == 0)
            {
                branch = Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual;
            }

            qGen.Delete DeleteCommand = new qGen.Delete("sys_config");
            DeleteCommand.WhereClause = new qGen.Where(qGen.AndOr.And);
            DeleteCommand.WhereClause.Add(new qGen.ComparisonCondition("nombre", settingName));
            DeleteCommand.WhereClause.Add(new qGen.ComparisonCondition("id_sucursal", branch));
            Connection.Delete(DeleteCommand);

            string CacheSettingName = "*/" + branch.ToString() + "/" + settingName;

            if (this.SysConfigCache.ContainsKey(CacheSettingName))
            {
                this.SysConfigCache.Remove(CacheSettingName);
            }
            return(true);
        }
Beispiel #5
0
        public bool DeleteGlobalSetting(string settingName, string terminalName)
        {
            if (terminalName == null || terminalName.Length == 0)
            {
                terminalName = Lfx.Environment.SystemInformation.MachineName;
            }

            qGen.Delete DeleteCommand = new qGen.Delete("sys_config");
            DeleteCommand.WhereClause          = new qGen.Where();
            DeleteCommand.WhereClause.Operator = qGen.AndOr.And;
            DeleteCommand.WhereClause.Add(new qGen.ComparisonCondition("nombre", settingName));
            DeleteCommand.WhereClause.Add(new qGen.ComparisonCondition("estacion", terminalName));
            Connection.Delete(DeleteCommand);

            string CacheSettingName = terminalName + "/0/" + settingName;

            if (this.SysConfigCache.ContainsKey(CacheSettingName))
            {
                this.SysConfigCache.Remove(CacheSettingName);
            }
            return(true);
        }
Beispiel #6
0
        public override Lfx.Types.OperationResult Guardar()
        {
            decimal PvpOriginal = 0, CostoOriginal = 0;

            if (this.Existe)
            {
                PvpOriginal   = System.Convert.ToDecimal(this.RegistroOriginal["pvp"]);
                CostoOriginal = System.Convert.ToDecimal(this.RegistroOriginal["costo"]);
            }

            qGen.IStatement Comando;

            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                Comando.ColumnValues.AddWithValue("fecha_creado", new qGen.SqlExpression("NOW()"));
                Comando.ColumnValues.AddWithValue("fecha_precio", new qGen.SqlExpression("NOW()"));
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.ColumnValues.AddWithValue("codigo1", this.Codigo1);
            Comando.ColumnValues.AddWithValue("codigo2", this.Codigo2);
            Comando.ColumnValues.AddWithValue("codigo3", this.Codigo3);
            Comando.ColumnValues.AddWithValue("codigo4", this.Codigo4);

            if (this.Categoria == null)
            {
                Comando.ColumnValues.AddWithValue("id_categoria", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_categoria", this.Categoria.Id);
            }

            if (this.Marca == null)
            {
                Comando.ColumnValues.AddWithValue("id_marca", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_marca", this.Marca.Id);
            }

            if (this.Caja == null)
            {
                Comando.ColumnValues.AddWithValue("id_caja", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_caja", this.Caja.Id);
            }

            Comando.ColumnValues.AddWithValue("modelo", this.Modelo);
            Comando.ColumnValues.AddWithValue("serie", this.Serie);
            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);
            Comando.ColumnValues.AddWithValue("url", this.Url);

            if (this.Proveedor == null)
            {
                Comando.ColumnValues.AddWithValue("id_proveedor", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_proveedor", this.Proveedor.Id);
            }

            Comando.ColumnValues.AddWithValue("descripcion", this.Descripcion);
            Comando.ColumnValues.AddWithValue("descripcion2", this.Descripcion2);
            Comando.ColumnValues.AddWithValue("destacado", this.Destacado);
            Comando.ColumnValues.AddWithValue("costo", this.Costo);

            if (this.Margen == null)
            {
                Comando.ColumnValues.AddWithValue("id_margen", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_margen", this.Margen.Id);
            }

            Comando.ColumnValues.AddWithValue("pvp", this.Pvp);
            Comando.ColumnValues.AddWithValue("control_stock", (int)(this.TipoDeArticulo));
            Comando.ColumnValues.AddWithValue("seguimiento", (int)(this.Seguimiento));
            Comando.ColumnValues.AddWithValue("periodicidad", (int)(this.Periodicidad));
            Comando.ColumnValues.AddWithValue("stock_minimo", this.PuntoDeReposicion);
            if (this.Existe)
            {
                Comando.ColumnValues.AddWithValue("stock_actual", this.ObtenerExistencias());
            }
            Comando.ColumnValues.AddWithValue("unidad_stock", this.Unidad);
            Comando.ColumnValues.AddWithValue("rendimiento", this.Rendimiento);
            Comando.ColumnValues.AddWithValue("unidad_rend", this.UnidadRendimiento);
            Comando.ColumnValues.AddWithValue("garantia", this.Garantia);
            Comando.ColumnValues.AddWithValue("estado", this.Estado);
            switch (this.Publicacion)
            {
            case Publicacion.Nunca:
                Comando.ColumnValues.AddWithValue("web", 0);
                break;

            case Publicacion.SoloSiHayExistenciasOPedidos:
                Comando.ColumnValues.AddWithValue("web", 1);
                break;

            case Publicacion.Siempre:
            default:
                Comando.ColumnValues.AddWithValue("web", 2);
                break;
            }
            Comando.ColumnValues.AddWithValue("conotramoneda", this.ConOtraMoneda);
            Comando.ColumnValues.AddWithValue("cotiza", this.Cotiza);
            Comando.ColumnValues.AddWithValue("id_moneda", this.Moneda);
            Comando.ColumnValues.AddWithValue("estante", this.Estante);
            Comando.ColumnValues.AddWithValue("estanteria", this.Estanteria);
            if (this.ConceptoVenta == null)
            {
                Comando.ColumnValues.AddWithValue("id_conceptoventa", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_conceptoventa", this.ConceptoVenta.Id);
            }
            if (this.ConceptoCompra == null)
            {
                Comando.ColumnValues.AddWithValue("id_conceptocompra", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_conceptocompra", this.ConceptoCompra.Id);
            }


            this.AgregarTags(Comando);

            this.Connection.ExecuteNonQuery(Comando);

            if (this.Existe == false)
            {
                this.ActualizarId();

                if (this.ExistenciasInicial != 0)
                {
                    // Hago el movimiento de stock inicial
                    this.MoverExistencias(null, this.ExistenciasInicial, "Creación del artículo - Existencias iniciales", null, new Situacion(this.Connection, 1), null);
                }
            }
            else
            {
                if (CostoOriginal != this.Costo)
                {
                    // Cambió el costo
                    this.RecalcularCostoSuperArticulos();
                }
                if (PvpOriginal != this.Pvp)
                {
                    // Cambió el PVP
                    // Actualizo la fecha del precio
                    qGen.Update ActualizarPrecio = new qGen.Update(this.TablaDatos);
                    ActualizarPrecio.ColumnValues.AddWithValue("pvp", this.Pvp);
                    ActualizarPrecio.ColumnValues.AddWithValue("fecha_precio", new qGen.SqlExpression("NOW()"));
                    ActualizarPrecio.WhereClause = new qGen.Where(this.CampoId, this.Id);
                    this.Connection.ExecuteNonQuery(ActualizarPrecio);

                    // Y creo un evento en el historial de precios
                    qGen.Insert AgregarAlHistorialDePrecios = new qGen.Insert("articulos_precios");
                    AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("id_articulo", this.Id);
                    AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("costo", this.Costo);
                    AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
                    if (this.Margen == null)
                    {
                        AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("id_margen", null);
                    }
                    else
                    {
                        AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("id_margen", this.Margen.Id);
                    }
                    AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("pvp", this.Pvp);
                    AgregarAlHistorialDePrecios.ColumnValues.AddWithValue("id_persona", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                    this.Connection.ExecuteNonQuery(AgregarAlHistorialDePrecios);
                }
            }

            // Si hay una receta guardada, la elimino
            qGen.Delete EliminarReceta = new qGen.Delete("articulos_recetas");
            EliminarReceta.WhereClause = new qGen.Where("id_articulo", this.Id);
            this.Connection.ExecuteNonQuery(EliminarReceta);

            // Guardar la receta del artículo, si corresponde
            if (this.TipoDeArticulo == Articulos.TiposDeArticulo.ProductoCompuesto && this.Receta != null)
            {
                foreach (ItemReceta Itm in this.Receta)
                {
                    qGen.Insert InsertarItemReceta = new qGen.Insert("articulos_recetas");
                    InsertarItemReceta.ColumnValues.AddWithValue("id_articulo", this.Id);
                    InsertarItemReceta.ColumnValues.AddWithValue("id_item", Itm.Articulo.Id);
                    InsertarItemReceta.ColumnValues.AddWithValue("cantidad", Itm.Cantidad);
                    this.Connection.ExecuteNonQuery(InsertarItemReceta);
                }
            }


            if (this.ConOtraMoneda != 0)
            {
                qGen.IStatement cot_ins_Comando = new qGen.Insert("articulos_cotiza");
                cot_ins_Comando.ColumnValues.AddWithValue("id_articulo", this.Id);
                cot_ins_Comando.ColumnValues.AddWithValue("id_moneda", this.Moneda);
                cot_ins_Comando.ColumnValues.AddWithValue("cotiza", this.Cotiza);
                cot_ins_Comando.ColumnValues.AddWithValue("estado", 1);
                cot_ins_Comando.ColumnValues.AddWithValue("fecha", DateTime.Now);
                this.Connection.ExecuteNonQuery(cot_ins_Comando);
            }

            return(base.Guardar());
        }
Beispiel #7
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;

            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                Comando.ColumnValues.AddWithValue("fecha_ingreso", new qGen.SqlExpression("NOW()"));
                Comando.ColumnValues.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual);
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.ColumnValues.AddWithValue("id_persona", this.Cliente.Id);
            if (this.Tipo == null)
            {
                Comando.ColumnValues.AddWithValue("id_tipo_ticket", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_tipo_ticket", this.Tipo.Id);
            }
            if (this.Encargado == null)
            {
                Comando.ColumnValues.AddWithValue("id_tecnico_recibe", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_tecnico_recibe", this.Encargado.Id);
            }
            Comando.ColumnValues.AddWithValue("prioridad", this.Prioridad);
            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);
            Comando.ColumnValues.AddWithValue("descripcion", this.GetFieldValue <string>("descripcion"));
            Comando.ColumnValues.AddWithValue("estado", this.Estado);
            Comando.ColumnValues.AddWithValue("articulos_descuento", this.DescuentoArticulos);
            Comando.ColumnValues.AddWithValue("entrega_estimada", this.FechaEstimada);
            Comando.ColumnValues.AddWithValue("entrega_limite", this.FechaLimite);
            Comando.ColumnValues.AddWithValue("presupuesto", this.Importe);
            if (this.Presupuesto == null)
            {
                Comando.ColumnValues.AddWithValue("id_presupuesto", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_presupuesto", this.Presupuesto.Id);
            }
            if (this.Factura == null)
            {
                Comando.ColumnValues.AddWithValue("id_comprob", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_comprob", this.Factura.Id);
            }
            Comando.ColumnValues.AddWithValue("obs", this.Obs);

            this.AgregarTags(Comando);

            this.Connection.ExecuteNonQuery(Comando);
            this.ActualizarId();

            if (this.RegistroOriginal != null && this.RegistroOriginal["estado"] != this.Registro["estado"])
            {
                this.AgregarComentario("Actualización de Estado: " + Lbl.Tareas.EstadoTarea.TodosPorNumero[this.Estado].ToString());
            }

            if (this.Articulos != null && this.Articulos.HayCambios)
            {
                qGen.Delete EliminarArticulos = new qGen.Delete("tickets_articulos");
                EliminarArticulos.WhereClause = new qGen.Where("id_ticket", this.Id);
                this.Connection.ExecuteNonQuery(EliminarArticulos);

                int i = 1;
                foreach (Lbl.Comprobantes.DetalleArticulo Det in this.Articulos)
                {
                    qGen.Insert InsertarArticulo = new qGen.Insert("tickets_articulos");
                    InsertarArticulo.ColumnValues.AddWithValue("id_ticket", this.Id);
                    if (Det.Articulo == null)
                    {
                        InsertarArticulo.ColumnValues.AddWithValue("id_articulo", null);
                        InsertarArticulo.ColumnValues.AddWithValue("nombre", Det.Nombre);
                    }
                    else
                    {
                        InsertarArticulo.ColumnValues.AddWithValue("id_articulo", Det.Articulo.Id);
                        InsertarArticulo.ColumnValues.AddWithValue("nombre", Det.Articulo.Nombre);
                    }

                    InsertarArticulo.ColumnValues.AddWithValue("orden", i++);
                    InsertarArticulo.ColumnValues.AddWithValue("cantidad", Det.Cantidad);
                    InsertarArticulo.ColumnValues.AddWithValue("precio", Det.ImporteUnitario);
                    InsertarArticulo.ColumnValues.AddWithValue("descuento", Det.Descuento);
                    Connection.ExecuteNonQuery(InsertarArticulo);
                }
            }

            return(base.Guardar());
        }
Beispiel #8
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;

                        if (this.Existe == false) {
                                Comando = new qGen.Insert(this.Connection, this.TablaDatos);
                        } else {
                                Comando = new qGen.Update(this.Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        Comando.Fields.AddWithValue("letra", this.Nomenclatura);
                        Comando.Fields.AddWithValue("letrasola", this.Letra == null ? "" : this.Letra);
                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("nombrelargo", this.NombreLargo);
                        Comando.Fields.AddWithValue("mueve_stock", this.MueveExistencias);
                        Comando.Fields.AddWithValue("direc_ctacte", this.DireccionCtaCte);
                        Comando.Fields.AddWithValue("compra", this.PermiteCompra ? 1 : 0);
                        Comando.Fields.AddWithValue("venta", this.PermiteVenta ? 1 : 0);
                        Comando.Fields.AddWithValue("numerar_guardar", this.NumerarAlGuardar ? 1 : 0);
                        Comando.Fields.AddWithValue("numerar_imprimir", this.NumerarAlImprimir ? 1 : 0);
                        Comando.Fields.AddWithValue("imprimir_guardar", this.ImprimirAlGuardar ? 1 : 0);
                        Comando.Fields.AddWithValue("imprimir_repetir", this.PermiteImprimirVariasVeces ? 1 : 0);
                        Comando.Fields.AddWithValue("imprimir_modificar", this.PermiteModificarImpresos ? 1 : 0);
                        Comando.Fields.AddWithValue("cargapapel", (int)(this.CargaPapel));

                        if (this.SituacionOrigen == null)
                                Comando.Fields.AddWithValue("situacionorigen", null);
                        else
                                Comando.Fields.AddWithValue("situacionorigen", this.SituacionOrigen.Id);

                        if (this.SituacionDestino == null)
                                Comando.Fields.AddWithValue("situaciondestino", null);
                        else
                                Comando.Fields.AddWithValue("situaciondestino", this.SituacionDestino.Id);

                        this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

                        if (this.Impresoras != null && this.Impresoras.HayCambios) {
                                // Eliminar todas las impresoras asociadas con el tipo
                                qGen.Delete EliminarImpresorasActuales = new qGen.Delete("comprob_tipo_impresoras");
                                EliminarImpresorasActuales.WhereClause = new qGen.Where("id_tipo", this.Id);
                                this.Connection.Execute(EliminarImpresorasActuales);

                                // Guardar la nueva lista de permisos del usuario
                                foreach (Lbl.Impresion.TipoImpresora Impr in this.Impresoras) {
                                        qGen.Insert InsertarImpresora = new qGen.Insert("comprob_tipo_impresoras");
                                        InsertarImpresora.Fields.AddWithValue("id_tipo", this.Id);
                                        InsertarImpresora.Fields.AddWithValue("id_impresora", Impr.Impresora.Id);
                                        if (Impr.Sucursal == null)
                                                InsertarImpresora.Fields.AddWithValue("id_sucursal", null);
                                        else
                                                InsertarImpresora.Fields.AddWithValue("id_sucursal", Impr.Sucursal.Id);
                                        if (Impr.PuntoDeVenta == null)
                                                InsertarImpresora.Fields.AddWithValue("id_pv", null);
                                        else
                                                InsertarImpresora.Fields.AddWithValue("id_pv", Impr.PuntoDeVenta.Id);
                                        InsertarImpresora.Fields.AddWithValue("estacion", Impr.Estacion);
                                        InsertarImpresora.Fields.AddWithValue("nombre", Impr.Nombre);

                                        this.Connection.Execute(InsertarImpresora);
                                }
                        }

                        return base.Guardar();
                }
Beispiel #9
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;

            if (this.Existe == false)
            {
                throw new InvalidOperationException("Sólo se pueden editar permisos de personas existentes");
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            if (string.IsNullOrEmpty(this.NombreUsuario))
            {
                Comando.ColumnValues.AddWithValue("nombreusuario", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("nombreusuario", this.NombreUsuario);
            }

            if (this.CambioContrasena)
            {
                if (this.Contrasena == null || this.Contrasena.Length < 6 || this.Contrasena.Length > 32)
                {
                    throw new InvalidOperationException("La contraseña debe tener entre 6 y 32 caracteres");
                }

                if (this.ContrasenaSal == null || this.ContrasenaSal.Length == 0)
                {
                    // Guardo la contraseña en texto plano
                    Comando.ColumnValues.AddWithValue("contrasena", Contrasena);
                }
                else
                {
                    // Guardo un hash SHA256 de la contraseña
                    Comando.ColumnValues.AddWithValue("contrasena", Lfx.Types.Strings.SHA256(Contrasena + "{" + this.ContrasenaSal + "}"));
                }
                Comando.ColumnValues.AddWithValue("contrasena_sal", this.ContrasenaSal);
                Comando.ColumnValues.AddWithValue("contrasena_fecha", new qGen.SqlExpression("NOW()"));
            }

            Comando.ColumnValues.AddWithValue("tipo", this.Tipo);

            this.Connection.ExecuteNonQuery(Comando);

            // Eliminar todos los permisos asociados con el usuario
            qGen.Delete EliminarPermisosActuales = new qGen.Delete("sys_permisos");
            EliminarPermisosActuales.WhereClause = new qGen.Where("id_persona", this.Id);
            this.Connection.ExecuteNonQuery(EliminarPermisosActuales);

            // Guardar la nueva lista de permisos del usuario
            foreach (Sys.Permisos.Permiso Perm in this.Pemisos)
            {
                qGen.Insert InsertarPermiso = new qGen.Insert("sys_permisos");
                InsertarPermiso.ColumnValues.AddWithValue("id_persona", this.Id);
                InsertarPermiso.ColumnValues.AddWithValue("id_objeto", Perm.Objeto.Id);
                if (Perm.Item == null)
                {
                    InsertarPermiso.ColumnValues.AddWithValue("items", null);
                }
                else
                {
                    InsertarPermiso.ColumnValues.AddWithValue("items", Perm.Item.ToString());
                }
                InsertarPermiso.ColumnValues.AddWithValue("ops", (int)(Perm.Operaciones));
                this.Connection.ExecuteNonQuery(InsertarPermiso);
            }

            return(base.Guardar());
        }
Beispiel #10
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.TableCommand Comando;

            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.Connection, this.TablaDatos);
            }
            else
            {
                Comando             = new qGen.Update(this.Connection, this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.Fields.AddWithValue("letra", this.Nomenclatura);
            Comando.Fields.AddWithValue("letrasola", this.Letra == null ? "" : this.Letra);
            Comando.Fields.AddWithValue("nombre", this.Nombre);
            Comando.Fields.AddWithValue("nombrelargo", this.NombreLargo);
            Comando.Fields.AddWithValue("mueve_stock", this.MueveExistencias);
            Comando.Fields.AddWithValue("direc_ctacte", this.DireccionCtaCte);
            Comando.Fields.AddWithValue("compra", this.PermiteCompra ? 1 : 0);
            Comando.Fields.AddWithValue("venta", this.PermiteVenta ? 1 : 0);
            Comando.Fields.AddWithValue("numerar_guardar", this.NumerarAlGuardar ? 1 : 0);
            Comando.Fields.AddWithValue("numerar_imprimir", this.NumerarAlImprimir ? 1 : 0);
            Comando.Fields.AddWithValue("imprimir_guardar", this.ImprimirAlGuardar ? 1 : 0);
            Comando.Fields.AddWithValue("imprimir_repetir", this.PermiteImprimirVariasVeces ? 1 : 0);
            Comando.Fields.AddWithValue("imprimir_modificar", this.PermiteModificarImpresos ? 1 : 0);
            Comando.Fields.AddWithValue("cargapapel", (int)(this.CargaPapel));

            if (this.SituacionOrigen == null)
            {
                Comando.Fields.AddWithValue("situacionorigen", null);
            }
            else
            {
                Comando.Fields.AddWithValue("situacionorigen", this.SituacionOrigen.Id);
            }

            if (this.SituacionDestino == null)
            {
                Comando.Fields.AddWithValue("situaciondestino", null);
            }
            else
            {
                Comando.Fields.AddWithValue("situaciondestino", this.SituacionDestino.Id);
            }

            this.AgregarTags(Comando);

            this.Connection.Execute(Comando);

            if (this.Impresoras != null && this.Impresoras.HayCambios)
            {
                // Eliminar todas las impresoras asociadas con el tipo
                qGen.Delete EliminarImpresorasActuales = new qGen.Delete("comprob_tipo_impresoras");
                EliminarImpresorasActuales.WhereClause = new qGen.Where("id_tipo", this.Id);
                this.Connection.Execute(EliminarImpresorasActuales);

                // Guardar la nueva lista de permisos del usuario
                foreach (Lbl.Impresion.TipoImpresora Impr in this.Impresoras)
                {
                    qGen.Insert InsertarImpresora = new qGen.Insert("comprob_tipo_impresoras");
                    InsertarImpresora.Fields.AddWithValue("id_tipo", this.Id);
                    InsertarImpresora.Fields.AddWithValue("id_impresora", Impr.Impresora.Id);
                    if (Impr.Sucursal == null)
                    {
                        InsertarImpresora.Fields.AddWithValue("id_sucursal", null);
                    }
                    else
                    {
                        InsertarImpresora.Fields.AddWithValue("id_sucursal", Impr.Sucursal.Id);
                    }
                    if (Impr.PuntoDeVenta == null)
                    {
                        InsertarImpresora.Fields.AddWithValue("id_pv", null);
                    }
                    else
                    {
                        InsertarImpresora.Fields.AddWithValue("id_pv", Impr.PuntoDeVenta.Id);
                    }
                    InsertarImpresora.Fields.AddWithValue("estacion", Impr.Estacion);
                    InsertarImpresora.Fields.AddWithValue("nombre", Impr.Nombre);

                    this.Connection.Execute(InsertarImpresora);
                }
            }

            return(base.Guardar());
        }
Beispiel #11
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;

                        if (this.Existe == false) {
                                Comando = new qGen.Insert(this.Connection, this.TablaDatos);
                                Comando.Fields.AddWithValue("fecha_ingreso", qGen.SqlFunctions.Now);
                                Comando.Fields.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual);
                        } else {
                                Comando = new qGen.Update(this.Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        Comando.Fields.AddWithValue("id_persona", this.Cliente.Id);
                        if (this.Tipo == null)
                                Comando.Fields.AddWithValue("id_tipo_ticket", null);
                        else
                                Comando.Fields.AddWithValue("id_tipo_ticket", this.Tipo.Id);
                        if (this.Encargado == null)
                                Comando.Fields.AddWithValue("id_tecnico_recibe", null);
                        else
                                Comando.Fields.AddWithValue("id_tecnico_recibe", this.Encargado.Id);
                        Comando.Fields.AddWithValue("prioridad", this.Prioridad);
                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("descripcion", this.GetFieldValue<string>("descripcion"));
                        Comando.Fields.AddWithValue("estado", this.Estado);
                        Comando.Fields.AddWithValue("articulos_descuento", this.DescuentoArticulos);
                        Comando.Fields.AddWithValue("entrega_estimada", this.FechaEstimada);
                        Comando.Fields.AddWithValue("entrega_limite", this.FechaLimite);
                        Comando.Fields.AddWithValue("presupuesto", this.Importe);
                        if (this.Presupuesto == null)
                                Comando.Fields.AddWithValue("id_presupuesto", null);
                        else
                                Comando.Fields.AddWithValue("id_presupuesto", this.Presupuesto.Id);
                        if (this.Factura == null)
                                Comando.Fields.AddWithValue("id_comprob", null);
                        else
                                Comando.Fields.AddWithValue("id_comprob", this.Factura.Id);
                        Comando.Fields.AddWithValue("obs", this.Obs);

                        this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);
                        this.ActualizarId();

                        if (this.RegistroOriginal != null && this.RegistroOriginal["estado"] != this.Registro["estado"])
                                this.AgregarComentario("Actualización de Estado: " + Lbl.Tareas.Estado.TodosPorNumero[this.Estado].ToString());

                        if (this.Articulos != null && this.Articulos.HayCambios) {
                                qGen.Delete EliminarArticulos = new qGen.Delete("tickets_articulos");
                                EliminarArticulos.WhereClause = new qGen.Where("id_ticket", this.Id);
                                this.Connection.Execute(EliminarArticulos);

                                int i = 1;
                                foreach (Lbl.Comprobantes.DetalleArticulo Det in this.Articulos) {
                                        qGen.Insert InsertarArticulo = new qGen.Insert(Connection, "tickets_articulos");
                                        InsertarArticulo.Fields.AddWithValue("id_ticket", this.Id);
                                        if (Det.Articulo == null) {
                                                InsertarArticulo.Fields.AddWithValue("id_articulo", null);
                                                InsertarArticulo.Fields.AddWithValue("nombre", Det.Descripcion);
                                        } else {
                                                InsertarArticulo.Fields.AddWithValue("id_articulo", Det.Articulo.Id);
                                                InsertarArticulo.Fields.AddWithValue("nombre", Det.Articulo.Nombre);
                                        }
                                        
                                        InsertarArticulo.Fields.AddWithValue("orden", i++);
                                        InsertarArticulo.Fields.AddWithValue("cantidad", Det.Cantidad);
                                        InsertarArticulo.Fields.AddWithValue("precio", Det.Unitario);
                                        Connection.Execute(InsertarArticulo);
                                }
                        }

                        return base.Guardar();
                }
Beispiel #12
0
        public void Restore(string backupName)
        {
            string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar;

            Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

            if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta))
            {
                bool UsandoArchivoComprimido = false;

                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa");
                Progreso.Modal = true;

                /* Progreso.ChangeStatus("Descomprimiendo");
                 * // Descomprimir backup si está comprimido
                 * if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) {
                 *      Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z");
                 *      ArchivoComprimido.ExtractAll(BackupPath + Carpeta);
                 *      UsandoArchivoComprimido = true;
                 * } */

                Progreso.ChangeStatus("Eliminando datos actuales");
                using (Lfx.Data.Connection DataBase = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad")) {
                    Progreso.ChangeStatus("Acomodando estructuras");
                    Lfx.Workspace.Master.Structure.TagList.Clear();
                    Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml");
                    Lfx.Workspace.Master.CheckAndUpdateDataBaseVersion(true, true);

                    using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd"))
                        using (IDbTransaction Trans = DataBase.BeginTransaction()) {
                            DataBase.EnableConstraints(false);

                            Progreso.ChangeStatus("Incorporando tablas de datos");

                            Progreso.Max = (int)(Lector.Length / 1024);
                            string           TablaActual   = null;
                            string[]         ListaCampos   = null;
                            object[]         ValoresCampos = null;
                            int              CampoActual   = 0;
                            bool             EndTable      = false;
                            qGen.BuilkInsert Insertador    = new qGen.BuilkInsert();
                            do
                            {
                                string Comando = Lector.ReadString(4);
                                switch (Comando)
                                {
                                case ":TBL":
                                    TablaActual = Lector.ReadPrefixedString4();
                                    string NombreTabla;
                                    if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null)
                                    {
                                        NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label;
                                    }
                                    else
                                    {
                                        NombreTabla = TablaActual.ToTitleCase();
                                    }
                                    EndTable = false;
                                    Progreso.ChangeStatus("Cargando " + NombreTabla);

                                    qGen.Delete DelCmd = new qGen.Delete(TablaActual);
                                    DelCmd.EnableDeleleteWithoutWhere = true;
                                    DataBase.Execute(DelCmd);
                                    break;

                                case ":FDL":
                                    ListaCampos   = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":FLD":
                                    ValoresCampos[CampoActual++] = Lector.ReadField();
                                    break;

                                case ".ROW":
                                    qGen.Insert Insertar = new qGen.Insert(TablaActual);
                                    for (int i = 0; i < ListaCampos.Length; i++)
                                    {
                                        Insertar.Fields.AddWithValue(ListaCampos[i], ValoresCampos[i]);
                                    }
                                    Insertador.Add(Insertar);

                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":REM":
                                    Lector.ReadPrefixedString4();
                                    break;

                                case ".TBL":
                                    EndTable = true;
                                    break;
                                }
                                if (EndTable || Insertador.Count >= 1000)
                                {
                                    if (Insertador.Count > 0)
                                    {
                                        DataBase.Execute(Insertador);
                                    }
                                    Insertador.Clear();
                                    Progreso.Value = (int)(Lector.Position / 1024);
                                }
                            } while (Lector.Position < Lector.Length);
                            Lector.Close();

                            if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql)
                            {
                                // PostgreSql: Tengo que actualizar las secuencias
                                Progreso.ChangeStatus("Actualizando secuencias");
                                string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)";
                                foreach (string Tabla in Lfx.Data.DataBaseCache.DefaultCache.GetTableNames())
                                {
                                    string OID = DataBase.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'");
                                    System.Data.DataTable Campos = DataBase.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum");
                                    foreach (System.Data.DataRow Campo in Campos.Rows)
                                    {
                                        if (Campo[2] != DBNull.Value && Campo[2] != null)
                                        {
                                            string DefaultCampo = System.Convert.ToString(Campo[2]);
                                            if (Regex.IsMatch(DefaultCampo, PatronSecuencia))
                                            {
                                                string NombreCampo = System.Convert.ToString(Campo[0]);
                                                foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia))
                                                {
                                                    string Secuencia = Ocurrencia.Groups[1].ToString();
                                                    int    MaxId     = DataBase.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1;
                                                    DataBase.ExecuteSql("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst"))
                            {
                                // Incorporar Blobs
                                Progreso.ChangeStatus("Incorporando imágenes");
                                System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default);
                                string InfoImagen = null;
                                do
                                {
                                    InfoImagen = LectorBlobs.ReadLine();
                                    if (InfoImagen != null && InfoImagen.Length > 0)
                                    {
                                        string Tabla               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string Campo               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string CampoId             = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");

                                        // Guardar blob nuevo
                                        qGen.Update ActualizarBlob = new qGen.Update(DataBase, Tabla);
                                        ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId);

                                        System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                        byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1];
                                        ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length));
                                        ArchivoImagen.Close();

                                        ActualizarBlob.Fields.AddWithValue(Campo, Contenido);
                                        DataBase.Execute(ActualizarBlob);
                                    }
                                }while (InfoImagen != null);
                                LectorBlobs.Close();
                            }

                            if (UsandoArchivoComprimido)
                            {
                                Progreso.ChangeStatus("Eliminando archivos temporales");
                                // Borrar los archivos que descomprim temporalmente
                                System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta);
                                foreach (System.IO.FileInfo DirItem in Dir.GetFiles())
                                {
                                    if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt")
                                    {
                                        System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name);
                                    }
                                }
                            }
                            Progreso.ChangeStatus("Terminando transacción");
                            Trans.Commit();
                        }
                    Progreso.End();
                }

                Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada");
            }
        }
Beispiel #13
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;

                        if (this.Existe == false) {
                                throw new InvalidOperationException("Sólo se pueden editar permisos de personas existentes");
                        } else {
                                Comando = new qGen.Update(this.Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        if (string.IsNullOrEmpty(this.NombreUsuario)) {
                                Comando.Fields.AddWithValue("nombreusuario", null);
                        } else {
                                Comando.Fields.AddWithValue("nombreusuario", this.NombreUsuario);
                        }

                        if (this.CambioContrasena) {
                                if (this.Contrasena == null || this.Contrasena.Length < 6 || this.Contrasena.Length > 32)
                                        throw new InvalidOperationException("La contraseña debe tener entre 6 y 32 caracteres");

                                if (this.ContrasenaSal == null || this.ContrasenaSal.Length == 0) {
                                        // Guardo la contraseña en texto plano
                                        Comando.Fields.AddWithValue("contrasena", Contrasena);
                                } else {
                                        // Guardo un hash SHA256 de la contraseña
                                        Comando.Fields.AddWithValue("contrasena", Lfx.Types.Strings.SHA256(Contrasena + "{" + this.ContrasenaSal + "}"));
                                }
                                Comando.Fields.AddWithValue("contrasena_sal", this.ContrasenaSal);
                                Comando.Fields.AddWithValue("contrasena_fecha", qGen.SqlFunctions.Now);
                        }

                        Comando.Fields.AddWithValue("tipo", this.Tipo);

                        this.Connection.Execute(Comando);

                        // Eliminar todos los permisos asociados con el usuario
                        qGen.Delete EliminarPermisosActuales = new qGen.Delete("sys_permisos");
                        EliminarPermisosActuales.WhereClause = new qGen.Where("id_persona", this.Id);
                        this.Connection.Execute(EliminarPermisosActuales);
                        
                        // Guardar la nueva lista de permisos del usuario
                        foreach (Sys.Permisos.Permiso Perm in this.Pemisos) {
                                qGen.Insert InsertarPermiso = new qGen.Insert("sys_permisos");
                                InsertarPermiso.Fields.AddWithValue("id_persona", this.Id);
                                InsertarPermiso.Fields.AddWithValue("id_objeto", Perm.Objeto.Id);
                                if (Perm.Item == null)
                                        InsertarPermiso.Fields.AddWithValue("items", null);
                                else
                                        InsertarPermiso.Fields.AddWithValue("items", Perm.Item.ToString());
                                InsertarPermiso.Fields.AddWithValue("ops", (int)(Perm.Operaciones));
                                this.Connection.Execute(InsertarPermiso);
                        }

                        return base.Guardar();
                }
Beispiel #14
0
                public void Restore(string backupName)
                {
                        string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar;

                        Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

                        if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta)) {
                                bool UsandoArchivoComprimido = false;

                                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa");
                                Progreso.Modal = true;

                                /* Progreso.ChangeStatus("Descomprimiendo");
                                // Descomprimir backup si está comprimido
                                if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) {
                                        Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z");
                                        ArchivoComprimido.ExtractAll(BackupPath + Carpeta);
                                        UsandoArchivoComprimido = true;
                                } */

                                Progreso.ChangeStatus("Eliminando datos actuales");
                                using (Lfx.Data.Connection DataBase = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad")) {

                                        Progreso.ChangeStatus("Acomodando estructuras");
                                        Lfx.Workspace.Master.Structure.TagList.Clear();
                                        Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml");
                                        Lfx.Workspace.Master.CheckAndUpdateDataBaseVersion(true, true);

                                        using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd"))
                                        using (IDbTransaction Trans = DataBase.BeginTransaction()) {
                                                DataBase.EnableConstraints(false);

                                                Progreso.ChangeStatus("Incorporando tablas de datos");

                                                Progreso.Max = (int)(Lector.Length / 1024);
                                                string TablaActual = null;
                                                string[] ListaCampos = null;
                                                object[] ValoresCampos = null;
                                                int CampoActual = 0;
                                                bool EndTable = false;
                                                qGen.BuilkInsert Insertador = new qGen.BuilkInsert();
                                                do {
                                                        string Comando = Lector.ReadString(4);
                                                        switch (Comando) {
                                                                case ":TBL":
                                                                        TablaActual = Lector.ReadPrefixedString4();
                                                                        string NombreTabla;
                                                                        if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null) {
                                                                                NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label;
                                                                        } else {
                                                                                NombreTabla = TablaActual.ToTitleCase();
                                                                        }
                                                                        EndTable = false;
                                                                        Progreso.ChangeStatus("Cargando " + NombreTabla);

                                                                        qGen.Delete DelCmd = new qGen.Delete(TablaActual);
                                                                        DelCmd.EnableDeleleteWithoutWhere = true;
                                                                        DataBase.Execute(DelCmd);
                                                                        break;
                                                                case ":FDL":
                                                                        ListaCampos = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                                                        ValoresCampos = new object[ListaCampos.Length];
                                                                        CampoActual = 0;
                                                                        break;
                                                                case ":FLD":
                                                                        ValoresCampos[CampoActual++] = Lector.ReadField();
                                                                        break;
                                                                case ".ROW":
                                                                        qGen.Insert Insertar = new qGen.Insert(TablaActual);
                                                                        for (int i = 0; i < ListaCampos.Length; i++) {
                                                                                Insertar.Fields.AddWithValue(ListaCampos[i], ValoresCampos[i]);
                                                                        }
                                                                        Insertador.Add(Insertar);

                                                                        ValoresCampos = new object[ListaCampos.Length];
                                                                        CampoActual = 0;
                                                                        break;
                                                                case ":REM":
                                                                        Lector.ReadPrefixedString4();
                                                                        break;
                                                                case ".TBL":
                                                                        EndTable = true;
                                                                        break;
                                                        }
                                                        if (EndTable || Insertador.Count >= 1000) {
                                                                if (Insertador.Count > 0)
                                                                        DataBase.Execute(Insertador);
                                                                Insertador.Clear();
                                                                Progreso.Value = (int)(Lector.Position / 1024);
                                                        }
                                                } while (Lector.Position < Lector.Length);
                                                Lector.Close();

                                                if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql) {
                                                        // PostgreSql: Tengo que actualizar las secuencias
                                                        Progreso.ChangeStatus("Actualizando secuencias");
                                                        string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)";
                                                        foreach (string Tabla in Lfx.Data.DataBaseCache.DefaultCache.GetTableNames()) {
                                                                string OID = DataBase.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'");
                                                                System.Data.DataTable Campos = DataBase.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum");
                                                                foreach (System.Data.DataRow Campo in Campos.Rows) {
                                                                        if (Campo[2] != DBNull.Value && Campo[2] != null) {
                                                                                string DefaultCampo = System.Convert.ToString(Campo[2]);
                                                                                if (Regex.IsMatch(DefaultCampo, PatronSecuencia)) {
                                                                                        string NombreCampo = System.Convert.ToString(Campo[0]);
                                                                                        foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia)) {
                                                                                                string Secuencia = Ocurrencia.Groups[1].ToString();
                                                                                                int MaxId = DataBase.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1;
                                                                                                DataBase.ExecuteSql("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString());
                                                                                        }
                                                                                }
                                                                        }
                                                                }
                                                        }
                                                }

                                                if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst")) {
                                                        // Incorporar Blobs
                                                        Progreso.ChangeStatus("Incorporando imágenes");
                                                        System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default);
                                                        string InfoImagen = null;
                                                        do {
                                                                InfoImagen = LectorBlobs.ReadLine();
                                                                if (InfoImagen != null && InfoImagen.Length > 0) {
                                                                        string Tabla = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                                                        string Campo = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                                                        string CampoId = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                                                        string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");

                                                                        // Guardar blob nuevo
                                                                        qGen.Update ActualizarBlob = new qGen.Update(DataBase, Tabla);
                                                                        ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId);

                                                                        System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                                                        byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1];
                                                                        ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length));
                                                                        ArchivoImagen.Close();

                                                                        ActualizarBlob.Fields.AddWithValue(Campo, Contenido);
                                                                        DataBase.Execute(ActualizarBlob);
                                                                }
                                                        }
                                                        while (InfoImagen != null);
                                                        LectorBlobs.Close();
                                                }

                                                if (UsandoArchivoComprimido) {
                                                        Progreso.ChangeStatus("Eliminando archivos temporales");
                                                        // Borrar los archivos que descomprim temporalmente
                                                        System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta);
                                                        foreach (System.IO.FileInfo DirItem in Dir.GetFiles()) {
                                                                if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt") {
                                                                        System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name);
                                                                }
                                                        }
                                                }
                                                Progreso.ChangeStatus("Terminando transacción");
                                                Trans.Commit();
                                        }
                                        Progreso.End();
                                }

                                Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada");
                        }
                }
Beispiel #15
0
        /// <summary>
        /// Guarda todos los cambios en la base de datos. Si se trata de un elemento nuevo, se agrega un registro a la base de datos.
        /// Si se trata de un elemento existente, se modifica el registro original.
        /// </summary>
        public virtual Lfx.Types.OperationResult Guardar()
        {
            if (this.Id == 0)
            {
                // Acabo de insertar, averiguo mi propio id
                this.ActualizarId();
            }
            else
            {
                // Es un registro antiguo, lo elimino de la caché
                Lfx.Workspace.Master.Tables[this.TablaDatos].FastRows.RemoveFromCache(this.Id);
            }
            this.Registro.IsModified = false;
            this.Registro.IsNew      = false;

            if (this.m_ImagenCambio)
            {
                // Hay cambios en el campo imagen
                if (this.Imagen == null)
                {
                    // Eliminó la imagen
                    if (this.TablaImagenes == this.TablaDatos)
                    {
                        // La imagen reside en un campo de la misma tabla
                        qGen.Update ActualizarImagen = new qGen.Update(this.TablaImagenes);
                        ActualizarImagen.ColumnValues.AddWithValue("imagen", null);
                        ActualizarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        this.Connection.ExecuteNonQuery(ActualizarImagen);
                    }
                    else
                    {
                        // Usa una tabla separada para las imágenes
                        qGen.Delete EliminarImagen = new qGen.Delete(this.TablaImagenes);
                        EliminarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        this.Connection.ExecuteNonQuery(EliminarImagen);
                    }
                    Lbl.Sys.Config.ActionLog(this.Connection, Sys.Log.Acciones.Save, this, "Se eliminó la imagen");
                }
                else
                {
                    // Cargar imagen nueva
                    using (System.IO.MemoryStream ByteStream = new System.IO.MemoryStream()) {
                        System.Drawing.Imaging.ImageCodecInfo   CodecInfo = null;
                        System.Drawing.Imaging.ImageCodecInfo[] Codecs    = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
                        foreach (System.Drawing.Imaging.ImageCodecInfo Codec in Codecs)
                        {
                            if (Codec.MimeType == "image/jpeg")
                            {
                                CodecInfo = Codec;
                            }
                        }

                        if (CodecInfo == null)
                        {
                            this.Imagen.Save(ByteStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else
                        {
                            System.Drawing.Imaging.Encoder QualityEncoder = System.Drawing.Imaging.Encoder.Quality;
                            using (System.Drawing.Imaging.EncoderParameters EncoderParams = new System.Drawing.Imaging.EncoderParameters(1)) {
                                EncoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(QualityEncoder, 33L);

                                this.Imagen.Save(ByteStream, CodecInfo, EncoderParams);
                            }
                        }
                        byte[] ImagenBytes = ByteStream.ToArray();

                        qGen.IStatement CambiarImagen;
                        if (this.TablaImagenes != this.TablaDatos)
                        {
                            qGen.Delete EliminarImagen = new qGen.Delete(this.TablaImagenes);
                            EliminarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                            this.Connection.ExecuteNonQuery(EliminarImagen);

                            CambiarImagen = new qGen.Insert(this.TablaImagenes);
                            CambiarImagen.ColumnValues.AddWithValue(this.CampoId, this.Id);
                        }
                        else
                        {
                            CambiarImagen             = new qGen.Update(this.TablaImagenes);
                            CambiarImagen.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        CambiarImagen.ColumnValues.AddWithValue("imagen", ImagenBytes);
                        this.Connection.ExecuteNonQuery(CambiarImagen);
                        Lbl.Sys.Config.ActionLog(this.Connection, Sys.Log.Acciones.Save, this, "Se cargó una imagen nueva");
                    }
                }
            }

            this.GuardarEtiquetas();
            this.GuardarLog();
            Lfx.Workspace.Master.NotifyTableChange(this.TablaDatos, this.Id);

            this.m_RegistroOriginal  = this.m_Registro.Clone();
            this.m_EtiquetasOriginal = this.m_Etiquetas.Clone();
            this.m_ImagenCambio      = false;

            return(new Lfx.Types.SuccessOperationResult());
        }
                private void GuardarDetalle()
                {
                        this.Articulos.ElementoPadre = this;

                        qGen.Delete EliminarDetallesViejos = new qGen.Delete("comprob_detalle");
                        EliminarDetallesViejos.WhereClause = new qGen.Where("id_comprob", this.Id);
                        this.Connection.Execute(EliminarDetallesViejos);

                        int i = 1;
                        for (int Pasada = 1; Pasada <= 2; Pasada++) {
                                foreach (Lbl.Comprobantes.DetalleArticulo Art in m_Articulos) {
                                        // En la primera pasada, guardo sólo importes y cantidades positivos (o cero)
                                        // en la segunda pasada, guardo sólo los negativos.
                                        // De esa manera, los negativos siempre quedan últimos
                                        // lo cual es un requerimiento de las fiscales Hasar.
                                        if ((Pasada == 1 && Art.Cantidad >= 0 && Art.Unitario >= 0)
                                                || (Pasada == 2 && (Art.Cantidad < 0 || Art.Unitario < 0))) {
                                                qGen.TableCommand Comando = new qGen.Insert(this.Connection, "comprob_detalle");
                                                Comando.Fields.AddWithValue("id_comprob", this.Id);
                                                Comando.Fields.AddWithValue("orden", i);

                                                if (Art.Articulo == null) {
                                                        Comando.Fields.AddWithValue("id_articulo", null);
                                                        Comando.Fields.AddWithValue("nombre", Art.Nombre);
                                                        Comando.Fields.AddWithValue("descripcion", "");
                                                } else {
                                                        Comando.Fields.AddWithValue("id_articulo", Art.Articulo.Id);
                                                        Comando.Fields.AddWithValue("nombre", Art.Nombre);
                                                        Comando.Fields.AddWithValue("descripcion", Art.Articulo.Descripcion);
                                                }

                                                Comando.Fields.AddWithValue("cantidad", Art.Cantidad);
                                                Comando.Fields.AddWithValue("precio", Art.Unitario);
                                                Comando.Fields.AddWithValue("iva", Art.ImporteIva);
                                                Comando.Fields.AddWithValue("recargo", Art.Recargo);
                                                if (Art.Costo == 0 && Art.Articulo != null)
                                                        Comando.Fields.AddWithValue("costo", Art.Articulo.Costo);
                                                else
                                                        Comando.Fields.AddWithValue("costo", Art.Costo);
                                                Comando.Fields.AddWithValue("importe", Art.ImporteAImprimir);
                                                Comando.Fields.AddWithValue("total", Art.ImporteConIva);
                                                Comando.Fields.AddWithValue("series", Art.DatosSeguimiento);
                                                Comando.Fields.AddWithValue("obs", Art.Obs);

                                                this.AgregarTags(Comando, Art.Registro, "comprob_detalle");

                                                this.Connection.Execute(Comando);
                                                i++;
                                        }
                                }
                        }
                }
Beispiel #17
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        decimal PvpOriginal = 0, CostoOriginal = 0;

                        if (this.Existe) {
                                PvpOriginal = System.Convert.ToDecimal(this.RegistroOriginal["pvp"]);
                                CostoOriginal = System.Convert.ToDecimal(this.RegistroOriginal["costo"]);
                        }

			qGen.TableCommand Comando;

                        if (this.Existe == false) {
				Comando = new qGen.Insert(this.Connection, this.TablaDatos);
				Comando.Fields.AddWithValue("fecha_creado", qGen.SqlFunctions.Now);
				Comando.Fields.AddWithValue("fecha_precio", qGen.SqlFunctions.Now);
			} else {
				Comando = new qGen.Update(this.Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
			}

                        Comando.Fields.AddWithValue("codigo1", this.Codigo1);
                        Comando.Fields.AddWithValue("codigo2", this.Codigo2);
                        Comando.Fields.AddWithValue("codigo3", this.Codigo3);
                        Comando.Fields.AddWithValue("codigo4", this.Codigo4);

                        if (this.Categoria == null)
                                Comando.Fields.AddWithValue("id_categoria", null);
                        else
                                Comando.Fields.AddWithValue("id_categoria", this.Categoria.Id);

                        if (this.Marca == null)
                                Comando.Fields.AddWithValue("id_marca", null);
                        else
                                Comando.Fields.AddWithValue("id_marca", this.Marca.Id);

                        if (this.Caja == null)
                                Comando.Fields.AddWithValue("id_caja", null);
                        else
                                Comando.Fields.AddWithValue("id_caja", this.Caja.Id);

                        Comando.Fields.AddWithValue("modelo", this.Modelo);
                        Comando.Fields.AddWithValue("serie", this.Serie);
                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("url", this.Url);

                        if (this.Proveedor == null)
                                Comando.Fields.AddWithValue("id_proveedor", null);
                        else
                                Comando.Fields.AddWithValue("id_proveedor", this.Proveedor.Id);

                        Comando.Fields.AddWithValue("descripcion", this.Descripcion);
                        Comando.Fields.AddWithValue("descripcion2", this.Descripcion2);
                        Comando.Fields.AddWithValue("destacado", this.Destacado);
                        Comando.Fields.AddWithValue("costo", this.Costo);

                        if (this.Margen == null)
                                Comando.Fields.AddWithValue("id_margen", null);
                        else
                                Comando.Fields.AddWithValue("id_margen", this.Margen.Id);
                        
                        Comando.Fields.AddWithValue("pvp", this.Pvp);
                        Comando.Fields.AddWithValue("control_stock", (int)(this.TipoDeArticulo));
                        Comando.Fields.AddWithValue("seguimiento", (int)(this.Seguimiento));
                        Comando.Fields.AddWithValue("periodicidad", (int)(this.Periodicidad));
                        Comando.Fields.AddWithValue("stock_minimo", this.PuntoDeReposicion);
                        if (this.Existe)
                                Comando.Fields.AddWithValue("stock_actual", this.ObtenerExistencias());
                        Comando.Fields.AddWithValue("unidad_stock", this.Unidad);
                        Comando.Fields.AddWithValue("rendimiento", this.Rendimiento);
                        Comando.Fields.AddWithValue("unidad_rend", this.UnidadRendimiento);
                        Comando.Fields.AddWithValue("garantia", this.Garantia);
                        Comando.Fields.AddWithValue("estado", this.Estado);
                        switch(this.Publicacion)
                        {
                                case Publicacion.Nunca:
                                        Comando.Fields.AddWithValue("web", 0);
                                        break;
                                case Publicacion.SoloSiHayExistenciasOPedidos:
                                        Comando.Fields.AddWithValue("web", 1);
                                        break;
                                case Publicacion.Siempre:
                                default:
                                        Comando.Fields.AddWithValue("web", 2);
                                        break;
                        }

			this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

                        if (this.Existe == false) {
                                this.ActualizarId();

                                if (this.ExistenciasInicial != 0)
                                        // Hago el movimiento de stock inicial
                                        this.MoverExistencias(null, this.ExistenciasInicial, "Creación del artículo - Existencias iniciales", null, new Situacion(this.Connection, 1), null);
                        } else {
                                if (CostoOriginal != this.Costo) {
                                        // Cambió el costo
                                        this.RecalcularCostoSuperArticulos();
                                }
                                if (PvpOriginal != this.Pvp) {
                                        // Cambió el PVP
                                        // Actualizo la fecha del precio
                                        qGen.Update ActualizarPrecio = new qGen.Update(this.TablaDatos);
                                        ActualizarPrecio.Fields.AddWithValue("pvp", this.Pvp);
                                        ActualizarPrecio.Fields.AddWithValue("fecha_precio", qGen.SqlFunctions.Now);
                                        ActualizarPrecio.WhereClause = new qGen.Where(this.CampoId, this.Id);
                                        this.Connection.Execute(ActualizarPrecio);

                                        // Y creo un evento en el historial de precios
					qGen.Insert AgregarAlHistorialDePrecios = new qGen.Insert(this.Connection, "articulos_precios");
                                        AgregarAlHistorialDePrecios.Fields.AddWithValue("id_articulo", this.Id);
                                        AgregarAlHistorialDePrecios.Fields.AddWithValue("costo", this.Costo);
                                        AgregarAlHistorialDePrecios.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                                        if (this.Margen == null)
                                                AgregarAlHistorialDePrecios.Fields.AddWithValue("id_margen", null);
                                        else
                                                AgregarAlHistorialDePrecios.Fields.AddWithValue("id_margen", this.Margen.Id);
                                        AgregarAlHistorialDePrecios.Fields.AddWithValue("pvp", this.Pvp);
                                        AgregarAlHistorialDePrecios.Fields.AddWithValue("id_persona", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                                        this.Connection.Execute(AgregarAlHistorialDePrecios);
                                }
                        }

                        // Si hay una receta guardada, la elimino
                        qGen.Delete EliminarReceta = new qGen.Delete("articulos_recetas");
                        EliminarReceta.WhereClause = new qGen.Where("id_articulo", this.Id);
                        this.Connection.Execute(EliminarReceta);

                        // Guardar la receta del artículo, si corresponde
                        if (this.TipoDeArticulo == Articulos.TiposDeArticulo.ProductoCompuesto && this.Receta != null) {
                                foreach (ItemReceta Itm in this.Receta) {
                                        qGen.Insert InsertarItemReceta = new qGen.Insert(this.Connection, "articulos_recetas");
                                        InsertarItemReceta.Fields.AddWithValue("id_articulo", this.Id);
                                        InsertarItemReceta.Fields.AddWithValue("id_item", Itm.Articulo.Id);
                                        InsertarItemReceta.Fields.AddWithValue("cantidad", Itm.Cantidad);
                                        this.Connection.Execute(InsertarItemReceta);
                                }
                        }

                        return base.Guardar();
                }