Ejemplo n.º 1
0
        /// <summary>
        /// Finds all entities using a search crtieria.
        /// </summary>
        /// <typeparam name="T">The entity type.</typeparam>
        /// <param name="where">The search crtieria.</param>
        /// <param name="orderBy">The order of the resulting set.</param>
        /// <returns>An EntityRepository with zero or more entities.</returns>
        public List <T> FindBy <T>(qGen.Where where, string orderBy) where T : new()
        {
            // Get class metadata
            var EntityType    = typeof(T);
            var ClassName     = EntityType.FullName;
            var ClassMetadata = this.MetadataFactory.GetMetadataForClass(EntityType);

            // Construct select
            var IdCols = ClassMetadata.Columns.GetIdColumns();
            var Select = new qGen.Select(ClassMetadata.TableName);

            Select.WhereClause = where;
            Select.Order       = orderBy;

            // Execute query
            var DataTable = this.Connection.Select(Select);
            var Res       = new List <T>();

            // Fill the list
            if (DataTable.Rows.Count > 0)
            {
                foreach (DataRow Row in DataTable.Rows)
                {
                    Res.Add(this.HydrateEntity <T>(ClassMetadata, Row));
                }
            }

            return(Res);
        }
Ejemplo n.º 2
0
        public decimal ObtenerSaldoAFecha(DateTime date)
        {
            var Where = new qGen.Where(
                new List <qGen.ICondition>()
            {
                new qGen.ComparisonCondition("id_caja", Caja.Id),
                new qGen.ComparisonCondition("fecha", qGen.ComparisonOperators.LessOrEqual, date)
            }

                );

            var UltimoMovim = this.Em.FindOneBy <Lbl.Cajas.Movimiento>(
                Where,
                "id_movim DESC",
                new qGen.Window(1)
                );

            if (UltimoMovim == null)
            {
                // En el caso de que la persona sea nueva y no tenga moviemientos en la Ctacte
                return(0);
            }

            Log.Debug("ObtenerSaldoAFecha(): " + UltimoMovim.Saldo.ToString());

            return(UltimoMovim.Saldo);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Obtiene una lista de todos los elementos de esta tabla
 /// </summary>
 /// <returns>Una colección con los id y nombre de todos los elementos de la tabla</returns>
 public ColeccionCodigoDetalle ObtenerTodos(qGen.Where filter)
 {
     qGen.Select Sel = new qGen.Select(this.TablaDatos);
     Sel.Fields = this.CampoId + ", " + this.CampoNombre;
     if (filter != null)
     {
         Sel.WhereClause = filter;
     }
     System.Data.DataTable Tabla = this.Connection.Select(Sel);
     return(new ColeccionCodigoDetalle(Tabla));
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Obtiene una lista de todos los elementos de esta tabla
 /// </summary>
 /// <returns>Una colección con los id y nombre de todos los elementos de la tabla</returns>
 public ColeccionCodigoDetalle ObtenerTodos(qGen.Where filter)
 {
     qGen.Select Sel = new qGen.Select(this.TablaDatos);
     Sel.Columns = new qGen.SqlIdentifierCollection()
     {
         this.CampoId, this.CampoNombre
     };
     if (filter != null)
     {
         Sel.WhereClause = filter;
     }
     System.Data.DataTable Tabla = this.Connection.Select(Sel);
     return(new ColeccionCodigoDetalle(Tabla));
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Finds the first entity using a search crtieria.
        /// </summary>
        /// <typeparam name="T">The entity type.</typeparam>
        /// <param name="where">The search crtieria.</param>
        /// <param name="orderBy">The order of the resulting set.</param>
        /// <returns>An entity or null.</returns>
        public T FindOneBy <T>(qGen.Where where, string orderBy = null, qGen.Window window = null) where T : new()
        {
            // Get class metadata
            var EntityType    = typeof(T);
            var ClassName     = EntityType.FullName;
            var ClassMetadata = this.MetadataFactory.GetMetadataForClass(EntityType);

            // Construct select
            var IdCols = ClassMetadata.Columns.GetIdColumns();
            var Select = new qGen.Select(ClassMetadata.TableName);

            Select.WhereClause = where;

            if (orderBy != null)
            {
                Select.Order = orderBy;
            }
            if (window != null)
            {
                Select.Window = window;
            }

            // Execute query
            var DataTable = this.Connection.Select(Select);
            var Res       = new EntityCollection <T>();

            // Fill the list
            if (DataTable.Rows.Count > 0)
            {
                return(this.HydrateEntity <T>(ClassMetadata, DataTable.Rows[0]));
            }
            else
            {
                return(default(T));
            }
        }
Ejemplo n.º 6
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;
            if (this.Existe == false)
            {
                Comando = new qGen.Insert("chequeras");
                Comando.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
            }
            else
            {
                Comando             = new qGen.Update("chequeras");
                Comando.WhereClause = new qGen.Where("id_chequera", m_ItemId);
            }

            if (this.Banco == null)
            {
                Comando.ColumnValues.AddWithValue("id_banco", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_banco", this.Banco.Id);
            }
            Comando.ColumnValues.AddWithValue("prefijo", this.Prefijo);
            Comando.ColumnValues.AddWithValue("desde", this.Desde);
            Comando.ColumnValues.AddWithValue("hasta", this.Hasta);
            Comando.ColumnValues.AddWithValue("cheques_total", this.Hasta - this.Desde);
            if (this.Caja == null)
            {
                Comando.ColumnValues.AddWithValue("id_caja", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_caja", this.Caja.Id);
            }
            if (this.Sucursal == null)
            {
                Comando.ColumnValues.AddWithValue("id_sucursal", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_sucursal", this.Sucursal.Id);
            }
            Comando.ColumnValues.AddWithValue("titular", this.Titular);
            Comando.ColumnValues.AddWithValue("estado", this.Estado);

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

            if (this.Desde > 0 && this.Hasta > 0 && this.Hasta > this.Desde)
            {
                qGen.Update Actua = new qGen.Update("bancos_cheques");
                Actua.ColumnValues.AddWithValue("id_chequera", this.Id);
                Actua.WhereClause = new qGen.Where();
                Actua.WhereClause.AddWithValue("emitido", 1);
                Actua.WhereClause.AddWithValue("id_banco", this.Banco.Id);
                Actua.WhereClause.AddWithValue("numero", this.Desde, this.Hasta);
                Connection.ExecuteNonQuery(Actua);

                Actua = new qGen.Update("bancos_cheques");
                Actua.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("id_chequera", Lazaro.Orm.ColumnTypes.Integer, null));
                Actua.WhereClause = new qGen.Where();
                Actua.WhereClause.AddWithValue("emitido", 1);
                Actua.WhereClause.AddWithValue("id_banco", this.Banco.Id);
                Actua.WhereClause.AddWithValue("id_chequera", this.Id);
                qGen.Where Numeros = new qGen.Where(qGen.AndOr.Or);
                Numeros.AddWithValue("numero", qGen.ComparisonOperators.LessThan, this.Desde);
                Numeros.AddWithValue("numero", qGen.ComparisonOperators.GreaterThan, this.Hasta);
                Actua.WhereClause.AddWithValue(Numeros);
                Connection.ExecuteNonQuery(Actua);
            }

            return(base.Guardar());
        }
Ejemplo n.º 7
0
                public Task GetNextTask(string component)
                {
                        if (Workspace == null)
                                return null;

                        if (this.DataBase.State != System.Data.ConnectionState.Open)
                                this.DataBase.Open();

                        qGen.Where WhereEstacion = new qGen.Where(qGen.AndOr.Or);
                        WhereEstacion.AddWithValue("estacion", this.DataBase.EscapeString(Lfx.Environment.SystemInformation.MachineName));
                        WhereEstacion.AddWithValue("estacion", "*");

                        qGen.Where WhereFecha = new qGen.Where(qGen.AndOr.Or);
                        WhereFecha.AddWithValue("fechaejecutar", qGen.ComparisonOperators.LessOrEqual, qGen.SqlFunctions.Now);
                        WhereFecha.AddWithValue("fechaejecutar", null);

                        m_LastGetTask = DateTime.Now;
                        qGen.Select NextTask = new qGen.Select("sys_programador");
                        NextTask.WhereClause = new qGen.Where("estado", 0);
                        NextTask.WhereClause.AddWithValue("componente", component);
                        NextTask.WhereClause.AddWithValue(WhereEstacion);
                        NextTask.WhereClause.AddWithValue(WhereFecha);

                        NextTask.Order = "id_evento";

                        Lfx.Data.Row TaskRow;
                        try {
                                TaskRow = this.DataBase.FirstRowFromSelect(NextTask);
                        } catch {
                                TaskRow = null;
                        }
                        if (TaskRow != null) {
                                Task Result = new Task();

                                Result.Id = System.Convert.ToInt32(TaskRow["id_evento"]);
                                Result.Command = TaskRow["comando"].ToString();
                                Result.Component = TaskRow["componente"].ToString();
                                Result.Creator = TaskRow["crea_usuario"].ToString();
                                Result.CreatorComputerName = TaskRow["crea_estacion"].ToString();
                                Result.ComputerName = TaskRow["estacion"].ToString();
                                Result.Schedule = System.Convert.ToDateTime(TaskRow["fecha"]);
                                Result.Status = System.Convert.ToInt32(TaskRow["estado"]);

                                //Elimino tareas viejas
                                qGen.Update Actualizar = new qGen.Update("sys_programador", new qGen.Where("id_evento", Result.Id));
                                Actualizar.Fields.AddWithValue("estado", 1);

                                using (System.Data.IDbTransaction Trans = this.DataBase.BeginTransaction()) {
                                        this.DataBase.Execute(Actualizar);
                                        this.DataBase.Execute(new qGen.Delete("sys_programador", new qGen.Where("fecha", qGen.ComparisonOperators.LessThan, System.DateTime.Now.AddDays(-7))));
                                        Trans.Commit();
                                }

                                return Result;
                        } else
                                return null;
                }
Ejemplo n.º 8
0
                public void Poll()
                {
                        if (this.Connection.State != System.Data.ConnectionState.Open)
                                this.Connection.Open();

                        qGen.Where WhereUsuario = new qGen.Where(qGen.AndOr.Or);
                        WhereUsuario.AddWithValue("id_destinatario", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                        WhereUsuario.AddWithValue("id_destinatario", null);
                        if (Lbl.Sys.Config.Actual.UsuarioConectado.Persona.Grupo != null)
                                WhereUsuario.AddWithValue("id_grupo", Lbl.Sys.Config.Actual.UsuarioConectado.Persona.Grupo.Id);
                        if (Lbl.Sys.Config.Actual.UsuarioConectado.Persona.SubGrupo != null)
                                WhereUsuario.AddWithValue("id_grupo", Lbl.Sys.Config.Actual.UsuarioConectado.Persona.SubGrupo.Id);


                        qGen.Select SelMensajesSinLeer = new qGen.Select("sys_mensajes");

                        SelMensajesSinLeer.WhereClause = new qGen.Where();
                        //SelMensajesSinLeer.WhereClause.AddWithValue("estacion_recibe", Lfx.Environment.SystemInformation.MachineName);
                        SelMensajesSinLeer.WhereClause.AddWithValue("id_mensaje", qGen.ComparisonOperators.GreaterThan, this.LastMessageId);
                        SelMensajesSinLeer.WhereClause.AddWithValue(WhereUsuario);
                        SelMensajesSinLeer.Order = "id_mensaje";

                        System.Data.DataTable TablaMensajes;
                        try {
                                TablaMensajes = this.Connection.Select(SelMensajesSinLeer);
                                foreach (System.Data.DataRow Mensaje in TablaMensajes.Rows) {
                                        INotificacion Res = new NotificacionRegistro(this.Connection, (Lfx.Data.Row)(Mensaje));
                                        this.LastMessageId = System.Convert.ToInt32(Mensaje["id_mensaje"]);
                                        string Destino = System.Convert.ToString(Mensaje["destino"]);
                                        if (Lfx.Components.Manager.ComponentesCargados.ContainsKey(Destino)) {
                                                // Lo notifico via IPC
                                                Lfx.Workspace.Master.RunTime.Notify(Destino, Res);

                                                // Se lo notifico directamente al componente
                                                if (Lfx.Components.Manager.ComponentesCargados[Destino].Funciones.ContainsKey("Notify")) {
                                                        Lfx.Components.Manager.ComponentesCargados[Destino].Funciones["Notify"].Instancia.Arguments = new object[] { Res };
                                                        Lfx.Components.Manager.ComponentesCargados[Destino].Funciones["Notify"].Run();
                                                }
                                        } else {
                                                Lfx.Workspace.Master.RunTime.Notify(Destino, Res);
                                        }
                                }

                                qGen.Insert ActualizarEstado = new qGen.Insert("sys_mensajeria");
                                ActualizarEstado.OnDuplicateKeyUpdate = true;
                                ActualizarEstado.Fields.AddWithValue("id_usuario", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                                ActualizarEstado.Fields.AddWithValue("estacion", Lfx.Environment.SystemInformation.MachineName);
                                ActualizarEstado.Fields.AddWithValue("nombre", Lbl.Sys.Config.Actual.UsuarioConectado.Nombre);
                                ActualizarEstado.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                                if (this.LastMessageId > 0)
                                        ActualizarEstado.Fields.AddWithValue("id_ultimomensaje", this.LastMessageId);

                                this.Connection.Execute(ActualizarEstado);
                        } catch (Exception ex) {
                                System.Console.WriteLine(ex.Message);
                                if (Lfx.Environment.SystemInformation.DesignMode)
                                        throw;
                                else
                                        return;
                        }
                }
Ejemplo n.º 9
0
                private void MostrarVistaPrevia()
                {
                        int PV = EntradaPV.ValueInt;
                        int Desde = EntradaDesde.ValueInt;

                        if (EntradaHasta.ValueInt < Desde && this.ActiveControl != EntradaHasta)
                                EntradaHasta.ValueInt = Desde;

                        int Hasta = EntradaHasta.ValueInt;
                        int Cantidad = Hasta - Desde + 1;

                        string[] IncluyeTipos;

                        switch (EntradaTipo.TextKey) {
                                case "A":
                                        IncluyeTipos = new string[] { "FA", "NCA", "NDA" };
                                        break;

                                case "B":
                                        IncluyeTipos = new string[] { "FB", "NCB", "NDB" };
                                        break;

                                case "C":
                                        IncluyeTipos = new string[] { "FC", "NCC", "NDC" };
                                        break;

                                case "E":
                                        IncluyeTipos = new string[] { "FE", "NCE", "NDE" };
                                        break;

                                case "M":
                                        IncluyeTipos = new string[] { "FM", "NCM", "NDM" };
                                        break;

                                case "T":
                                        IncluyeTipos = new string[] { "T" };
                                        break;

                                default:
                                        IncluyeTipos = new string[] { EntradaTipo.TextKey };
                                        break;
                        }

                        qGen.Where WhereAnular = new qGen.Where();
                        WhereAnular.AddWithValue("impresa", qGen.ComparisonOperators.NotEqual, 0);
                        WhereAnular.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, IncluyeTipos);
                        WhereAnular.AddWithValue("pv", PV);

                        if (ProximosNumeros.ContainsKey(PV) == false) {
                                qGen.Select SelProxNum = new qGen.Select("comprob");
                                SelProxNum.Fields = "MAX(numero)";
                                SelProxNum.WhereClause = WhereAnular;
                                ProximosNumeros[PV] = this.Connection.FieldInt(SelProxNum) + 1;
                        }

                        if (PV <= 0 || Desde <= 0 || Cantidad <= 0) {
                                EtiquetaAviso.Text = "El rango seleccionado no es válido.";
                                ComprobanteVistaPrevia.Visible = false;
                                ListadoFacturas.Visible = false;
                                OkButton.Visible = false;
                                return;
                        }

                        if (Desde > ProximosNumeros[PV]) {
                                EtiquetaAviso.Text = "No se puede anular el rango seleccionado porque todavía no se utilizaron los comprobantes desde el " + ProximosNumeros[PV].ToString() + " al " + (Desde - 1).ToString();
                                ComprobanteVistaPrevia.Visible = false;
                                ListadoFacturas.Visible = false;
                                OkButton.Visible = false;
                                return;
                        }

                        ComprobanteVistaPrevia.Visible = Cantidad == 1;
                        ListadoFacturas.Visible = Cantidad > 1;

                        if (Cantidad == 1) {
                                qGen.Select SelDesde = new qGen.Select("comprob");
                                SelDesde.Fields = "id_comprob";
                                SelDesde.WhereClause = WhereAnular.Clone();
                                SelDesde.WhereClause.AddWithValue("numero", Desde);

                                int IdFactura = this.Connection.FieldInt(SelDesde);

                                Lbl.Comprobantes.ComprobanteConArticulos FacturaInicial = null;
                                if (IdFactura > 0)
                                        FacturaInicial = new Lbl.Comprobantes.ComprobanteConArticulos(this.Connection, IdFactura);

                                if (FacturaInicial != null && FacturaInicial.Existe) {
                                        ComprobanteVistaPrevia.Elemento = FacturaInicial;
                                        ComprobanteVistaPrevia.ActualizarControl();
                                        ComprobanteVistaPrevia.TemporaryReadOnly = true;
                                        ComprobanteVistaPrevia.Visible = true;

                                        if (FacturaInicial.Anulado) {
                                                EtiquetaAviso.Text = "El comprobante ya fue anulado y no puede anularse nuevamente.";
                                                OkButton.Visible = false;
                                        } else {
                                                EtiquetaAviso.Text = "Recuerde que necesitar archivar todas las copias del comprobante anulado.";
                                                OkButton.Visible = true;
                                                if (FacturaInicial.FormaDePago.Tipo == Lbl.Pagos.TiposFormasDePago.CuentaCorriente) {
                                                        EntradaAnularPagos.TextKey = "1";
                                                } else {
                                                        EntradaAnularPagos.TextKey = "0";
                                                }
                                        }
                                } else {
                                        ComprobanteVistaPrevia.Visible = false;

                                        if (Desde == ProximosNumeros[PV]) {
                                                EtiquetaAviso.Text = "El comprobante " + EntradaTipo.TextKey + " " + PV.ToString("0000") + "-" + Desde.ToString("00000000") + " aun no fue impreso, pero es el próximo en el talonario. Si lo anula, el sistema salteará dicho comprobante.";
                                                EntradaAnularPagos.TextKey = "0";
                                                OkButton.Visible = true;
                                        } else {
                                                EtiquetaAviso.Text = "El comprobante " + EntradaTipo.TextKey + " " + PV.ToString("0000") + "-" + Lfx.Types.Parsing.ParseInt(EntradaDesde.Text).ToString("00000000") + " aun no fue impreso y no puede anularse.";
                                                EntradaAnularPagos.TextKey = "0";
                                                OkButton.Visible = false;
                                        }
                                }
                        } else if (Cantidad > 1) {
                                EntradaAnularPagos.TextKey = "1";

                                qGen.Select SelComprobs = new qGen.Select("comprob");
                                SelComprobs.Fields = "*";
                                SelComprobs.WhereClause = WhereAnular.Clone();
                                SelComprobs.WhereClause.AddWithValue("numero", Desde, Hasta);

                                System.Data.DataTable TablaFacturas = this.Connection.Select(SelComprobs);
                                Lbl.Comprobantes.ColeccionComprobanteConArticulos Facturas = new Lbl.Comprobantes.ColeccionComprobanteConArticulos(this.Connection, TablaFacturas);
                                ListadoFacturas.BeginUpdate();
                                ListadoFacturas.Items.Clear();
                                foreach (Lbl.Comprobantes.ComprobanteConArticulos Fac in Facturas) {
                                        ListViewItem Itm = ListadoFacturas.Items.Add(Fac.Tipo.ToString());
                                        Itm.SubItems.Add(Fac.PV.ToString("0000") + "-" + Fac.Numero.ToString("00000000"));
                                        Itm.SubItems.Add(Fac.Fecha.ToString(Lfx.Types.Formatting.DateTime.ShortDatePattern));
                                        Itm.SubItems.Add(Fac.Cliente.ToString());
                                        Itm.SubItems.Add(Lfx.Types.Formatting.FormatCurrency(Fac.Total));
                                }
                                ListadoFacturas.EndUpdate();
                                EtiquetaAviso.Text = "Se van a anular " + Cantidad.ToString() + " comprobantes, incluyendo los que se detallan a continuación.";
                                this.OkButton.Visible = true;
                        } else {
                                EtiquetaAviso.Text = "Debe seleccionar un rango que inlcuya al menos 1 comprobante.";
                                ListadoFacturas.Items.Clear();
                                this.OkButton.Visible = false;
                        }
                }
Ejemplo n.º 10
0
        public Task GetNextTask(string component)
        {
            if (Workspace == null)
            {
                return(null);
            }

            if (this.DataBase.State != System.Data.ConnectionState.Open)
            {
                this.DataBase.Open();
            }

            qGen.Where WhereEstacion = new qGen.Where(qGen.AndOr.Or);
            WhereEstacion.AddWithValue("estacion", this.DataBase.EscapeString(Lfx.Environment.SystemInformation.MachineName));
            WhereEstacion.AddWithValue("estacion", "*");

            qGen.Where WhereFecha = new qGen.Where(qGen.AndOr.Or);
            WhereFecha.AddWithValue("fechaejecutar", qGen.ComparisonOperators.LessOrEqual, new qGen.SqlExpression("NOW()"));
            WhereFecha.AddWithValue("fechaejecutar", null);

            m_LastGetTask = DateTime.Now;
            qGen.Select NextTask = new qGen.Select("sys_programador");
            NextTask.WhereClause = new qGen.Where("estado", 0);
            NextTask.WhereClause.AddWithValue("componente", component);
            NextTask.WhereClause.AddWithValue(WhereEstacion);
            NextTask.WhereClause.AddWithValue(WhereFecha);

            NextTask.Order = "id_evento";

            Lfx.Data.Row TaskRow;
            try {
                TaskRow = this.DataBase.FirstRowFromSelect(NextTask);
            } catch {
                TaskRow = null;
            }
            if (TaskRow != null)
            {
                Task Result = new Task();

                Result.Id                  = System.Convert.ToInt32(TaskRow["id_evento"]);
                Result.Command             = TaskRow["comando"].ToString();
                Result.Component           = TaskRow["componente"].ToString();
                Result.Creator             = TaskRow["crea_usuario"].ToString();
                Result.CreatorComputerName = TaskRow["crea_estacion"].ToString();
                Result.ComputerName        = TaskRow["estacion"].ToString();
                Result.Schedule            = System.Convert.ToDateTime(TaskRow["fecha"]);
                Result.Status              = System.Convert.ToInt32(TaskRow["estado"]);

                //Elimino tareas viejas
                qGen.Update Actualizar = new qGen.Update("sys_programador", new qGen.Where("id_evento", Result.Id));
                Actualizar.ColumnValues.AddWithValue("estado", 1);

                using (System.Data.IDbTransaction Trans = this.DataBase.BeginTransaction()) {
                    this.DataBase.ExecuteNonQuery(Actualizar);
                    this.DataBase.ExecuteNonQuery(new qGen.Delete("sys_programador", new qGen.Where("fecha", qGen.ComparisonOperators.LessThan, System.DateTime.Now.AddDays(-7))));
                    Trans.Commit();
                }

                return(Result);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 11
0
 public EntityCollection <T> FindBy(qGen.Where where, string orderBy)
 {
     return(this.EntityManager.FindBy <T>(where, orderBy));
 }
Ejemplo n.º 12
0
 public NestedCondition(Where where)
 {
         this.Where = where;
 }
Ejemplo n.º 13
0
 public List <T> FindBy(qGen.Where where, string orderBy)
 {
     return(this.EntityManager.FindBy <T>(where, orderBy));
 }
Ejemplo n.º 14
0
 public RelationFilter(string label, Lfx.Data.Relation relation, qGen.Where filter)
     : this(label, relation)
 {
     this.Filter = filter;
 }
Ejemplo n.º 15
0
                /// <summary>
                /// Cancela saldos en comprobantes hasta el importe solicitado.
                /// </summary>
                /// <param name="importe">El importe a cancelar.</param>
                /// <returns>El importe cancelado. Puede ser igual o menor al importe solicitado.</returns>
                private decimal CancelarComprobantes(decimal importe)
                {
                        qGen.Where WhereConSaldo = new qGen.Where();
                        WhereConSaldo.AddWithValue("impresa", qGen.ComparisonOperators.NotEqual, 0);
                        WhereConSaldo.AddWithValue("anulada", 0);
                        WhereConSaldo.AddWithValue("numero", qGen.ComparisonOperators.NotEqual, 0);
                        WhereConSaldo.AddWithValue("id_formapago", qGen.ComparisonOperators.In, new int[] { 1, 3, 99 });
                        WhereConSaldo.AddWithValue("id_cliente", this.Persona.Id);
                        WhereConSaldo.AddWithValue("cancelado", qGen.ComparisonOperators.LessThan, new qGen.SqlExpression("total"));
                        // impresa>0 AND anulada=0 AND numero>0 AND id_formapago IN (1, 3, 99) AND cancelado<total AND id_cliente=this.Persona.Id

                        if (importe > 0) {
                                // Es un crédito, cancelo Facturas y Notas de Débito de venta y Notas de Crédito de compra
                                qGen.Where WhereTipoCredVenta = new qGen.Where();
                                WhereTipoCredVenta.AddWithValue("compra", 0);
                                WhereTipoCredVenta.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "FA", "FB", "FC", "FE", "FM", "NDA", "NDB", "NDC", "NDE", "NDM", "T" });

                                qGen.Where WhereTipoCredCompra = new qGen.Where();
                                WhereTipoCredCompra.AddWithValue("compra", 1);
                                WhereTipoCredCompra.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "NCA", "NCB", "NCC", "NCE", "NCM" });

                                qGen.Where WhereTipoCred = new qGen.Where(qGen.AndOr.Or);
                                WhereTipoCred.AddWithValue(WhereTipoCredVenta);
                                WhereTipoCred.AddWithValue(WhereTipoCredCompra);

                                WhereConSaldo.AddWithValue(WhereTipoCred);

                                /*  AND (compra=0 AND tipo_fac IN ('FA', 'FB', 'FC', 'FE', 'FM', 'NDA', 'NDB', 'NDC', 'NDE', 'NDM')
                                    OR (compra=1 AND tipo_fac IN ('NCA', 'NCB', 'NCC', 'NCE', 'NCM') */

                        } else {
                                // Es un débito. Cancelo Notas de Crédito de venta y Facturas y Notas de Débito de compra
                                qGen.Where WhereTipoCredVenta = new qGen.Where();
                                WhereTipoCredVenta.AddWithValue("compra", 1);
                                WhereTipoCredVenta.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "FA", "FB", "FC", "FE", "FM", "NDA", "NDB", "NDC", "NDE", "NDM", "T" });

                                qGen.Where WhereTipoCredCompra = new qGen.Where();
                                WhereTipoCredCompra.AddWithValue("compra", 0);
                                WhereTipoCredCompra.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "NCA", "NCB", "NCC", "NCE", "NCM" });

                                qGen.Where WhereTipoCred = new qGen.Where(qGen.AndOr.Or);
                                WhereTipoCred.AddWithValue(WhereTipoCredVenta);
                                WhereTipoCred.AddWithValue(WhereTipoCredCompra);

                                WhereConSaldo.AddWithValue(WhereTipoCred);

                                /*  AND (compra=1 AND tipo_fac IN ('FA', 'FB', 'FC', 'FE', 'FM', 'NDA', 'NDB', 'NDC', 'NDE', 'NDM')
                                    OR (compra=0 AND tipo_fac IN ('NCA', 'NCB', 'NCC', 'NCE', 'NCM') */
                        }

                        qGen.Select SelFacturasConSaldo = new qGen.Select("comprob", true);
                        SelFacturasConSaldo.Fields = "id_comprob,total,cancelado";
                        SelFacturasConSaldo.WhereClause = WhereConSaldo;
                        SelFacturasConSaldo.Order = "id_comprob";
                        System.Data.DataTable FacturasConSaldo = this.Connection.Select(SelFacturasConSaldo);

                        decimal ImporteCancelar = Math.Abs(importe);
                        decimal ImporteCancelado = 0;

                        foreach (System.Data.DataRow Factura in FacturasConSaldo.Rows) {
                                decimal SaldoComprob = System.Convert.ToDecimal(Factura["total"]) - System.Convert.ToDecimal(Factura["cancelado"]);
                                decimal ImporteCancelarComprob = SaldoComprob;

                                if (ImporteCancelarComprob > ImporteCancelar)
                                        ImporteCancelarComprob = ImporteCancelar;

                                qGen.Update ActCancelarComprob = new qGen.Update("comprob");
                                ActCancelarComprob.Fields.AddWithValue("cancelado", System.Convert.ToDecimal(Factura["cancelado"]) + ImporteCancelarComprob);
                                ActCancelarComprob.WhereClause = new qGen.Where("id_comprob", System.Convert.ToInt32(Factura["id_comprob"]));
                                this.Connection.Execute(ActCancelarComprob);
                                ImporteCancelar -= ImporteCancelarComprob;
                                ImporteCancelado += ImporteCancelarComprob;

                                if (ImporteCancelar <= 0)
                                        break;
                        }

                        return ImporteCancelado;
                }
Ejemplo n.º 16
0
        private void MostrarVistaPrevia()
        {
            int PV    = EntradaPV.ValueInt;
            int Desde = EntradaDesde.ValueInt;

            if (EntradaHasta.ValueInt < Desde && this.ActiveControl != EntradaHasta)
            {
                EntradaHasta.ValueInt = Desde;
            }

            int Hasta    = EntradaHasta.ValueInt;
            int Cantidad = Hasta - Desde + 1;

            string[] IncluyeTipos;

            switch (EntradaTipo.TextKey)
            {
            case "A":
                IncluyeTipos = new string[] { "FA", "NCA", "NDA" };
                break;

            case "B":
                IncluyeTipos = new string[] { "FB", "NCB", "NDB" };
                break;

            case "C":
                IncluyeTipos = new string[] { "FC", "NCC", "NDC" };
                break;

            case "E":
                IncluyeTipos = new string[] { "FE", "NCE", "NDE" };
                break;

            case "M":
                IncluyeTipos = new string[] { "FM", "NCM", "NDM" };
                break;

            case "T":
                IncluyeTipos = new string[] { "T" };
                break;

            default:
                IncluyeTipos = new string[] { EntradaTipo.TextKey };
                break;
            }

            qGen.Where WhereAnular = new qGen.Where();
            WhereAnular.AddWithValue("compra", m_DeCompra ? 1 : 0);
            WhereAnular.AddWithValue("impresa", qGen.ComparisonOperators.NotEqual, 0);
            WhereAnular.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, IncluyeTipos);
            WhereAnular.AddWithValue("pv", PV);

            if (ProximosNumeros.ContainsKey(PV) == false)
            {
                qGen.Select SelProxNum = new qGen.Select("comprob");
                SelProxNum.Columns = new List <string> {
                    "MAX(numero)"
                };
                SelProxNum.WhereClause = WhereAnular;
                ProximosNumeros[PV]    = this.Connection.FieldInt(SelProxNum) + 1;
            }

            if (PV <= 0 || Desde <= 0 || Cantidad <= 0)
            {
                EtiquetaAviso.Text             = "El rango seleccionado no es válido.";
                ComprobanteVistaPrevia.Visible = false;
                ListadoFacturas.Visible        = false;
                OkButton.Visible = false;
                return;
            }

            if (Desde > ProximosNumeros[PV])
            {
                EtiquetaAviso.Text             = "No se puede anular el rango seleccionado porque todavía no se utilizaron los comprobantes desde el " + ProximosNumeros[PV].ToString() + " al " + (Desde - 1).ToString();
                ComprobanteVistaPrevia.Visible = false;
                ListadoFacturas.Visible        = false;
                OkButton.Visible = false;
                return;
            }

            ComprobanteVistaPrevia.Visible = Cantidad == 1;
            ListadoFacturas.Visible        = Cantidad > 1;

            if (Cantidad == 1)
            {
                qGen.Select SelDesde = new qGen.Select("comprob");
                SelDesde.Columns = new List <string> {
                    "id_comprob"
                };
                SelDesde.WhereClause = WhereAnular.Clone();
                SelDesde.WhereClause.AddWithValue("numero", Desde);
                SelDesde.Order = "anulada";

                int IdFactura = this.Connection.FieldInt(SelDesde);

                Lbl.Comprobantes.ComprobanteConArticulos FacturaInicial = null;
                if (IdFactura > 0)
                {
                    FacturaInicial = new Lbl.Comprobantes.ComprobanteConArticulos(this.Connection, IdFactura);
                }

                if (FacturaInicial != null && FacturaInicial.Existe)
                {
                    ComprobanteVistaPrevia.Elemento = FacturaInicial;
                    ComprobanteVistaPrevia.ActualizarControl();
                    ComprobanteVistaPrevia.TemporaryReadOnly = true;
                    ComprobanteVistaPrevia.Visible           = true;

                    if (FacturaInicial.Anulado)
                    {
                        EtiquetaAviso.Text = "El comprobante ya fue anulado y no puede anularse nuevamente.";
                        OkButton.Visible   = false;
                    }
                    else
                    {
                        if (this.DeCompra)
                        {
                            EtiquetaAviso.Text = "Al anular comprobantes de compra, estos serán excluidos de los listados.";
                        }
                        else
                        {
                            EtiquetaAviso.Text = "Recuerde que necesitar archivar todas las copias del comprobante anulado.";
                        }
                        OkButton.Visible = true;
                        if (FacturaInicial.FormaDePago.Tipo == Lbl.Pagos.TiposFormasDePago.CuentaCorriente)
                        {
                            EntradaAnularPagos.TextKey = "1";
                        }
                        else
                        {
                            EntradaAnularPagos.TextKey = "0";
                        }
                    }
                }
                else
                {
                    ComprobanteVistaPrevia.Visible = false;

                    if (Desde == ProximosNumeros[PV])
                    {
                        EtiquetaAviso.Text         = "El comprobante " + EntradaTipo.TextKey + " " + PV.ToString("0000") + "-" + Desde.ToString("00000000") + " aun no fue impreso, pero es el próximo en el talonario. Si lo anula, el sistema salteará dicho comprobante.";
                        EntradaAnularPagos.TextKey = "0";
                        OkButton.Visible           = true;
                    }
                    else
                    {
                        EtiquetaAviso.Text         = "El comprobante " + EntradaTipo.TextKey + " " + PV.ToString("0000") + "-" + Lfx.Types.Parsing.ParseInt(EntradaDesde.Text).ToString("00000000") + " aun no fue impreso y no puede anularse.";
                        EntradaAnularPagos.TextKey = "0";
                        OkButton.Visible           = false;
                    }
                }
            }
            else if (Cantidad > 1)
            {
                EntradaAnularPagos.TextKey = "1";

                qGen.Select SelComprobs = new qGen.Select("comprob");
                SelComprobs.Columns = new List <string> {
                    "*"
                };
                SelComprobs.WhereClause = WhereAnular.Clone();
                SelComprobs.WhereClause.AddWithValue("numero", Desde, Hasta);

                System.Data.DataTable TablaFacturas = this.Connection.Select(SelComprobs);
                Lbl.Comprobantes.ColeccionComprobanteConArticulos Facturas = new Lbl.Comprobantes.ColeccionComprobanteConArticulos(this.Connection, TablaFacturas);
                ListadoFacturas.BeginUpdate();
                ListadoFacturas.Items.Clear();
                foreach (Lbl.Comprobantes.ComprobanteConArticulos Fac in Facturas)
                {
                    ListViewItem Itm = ListadoFacturas.Items.Add(Fac.Tipo.ToString());
                    Itm.SubItems.Add(Fac.PV.ToString("0000") + "-" + Fac.Numero.ToString("00000000"));
                    Itm.SubItems.Add(Fac.Fecha.ToString(Lfx.Types.Formatting.DateTime.ShortDatePattern));
                    Itm.SubItems.Add(Fac.Cliente.ToString());
                    Itm.SubItems.Add(Lfx.Types.Formatting.FormatCurrency(Fac.Total));
                }
                ListadoFacturas.EndUpdate();
                EtiquetaAviso.Text    = "Se van a anular " + Cantidad.ToString() + " comprobantes, incluyendo los que se detallan a continuación.";
                this.OkButton.Visible = true;
            }
            else
            {
                EtiquetaAviso.Text = "Debe seleccionar un rango que inlcuya al menos 1 comprobante.";
                ListadoFacturas.Items.Clear();
                this.OkButton.Visible = false;
            }
        }
Ejemplo n.º 17
0
 public NestedCondition(Where where)
 {
     this.Where = where;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Cancela saldos en comprobantes hasta el importe solicitado.
        /// </summary>
        /// <param name="importe">El importe a cancelar.</param>
        /// <returns>El importe cancelado. Puede ser igual o menor al importe solicitado.</returns>
        private decimal CancelarComprobantes(decimal importe)
        {
            qGen.Where WhereConSaldo = new qGen.Where();
            WhereConSaldo.AddWithValue("impresa", qGen.ComparisonOperators.NotEqual, 0);
            WhereConSaldo.AddWithValue("anulada", 0);
            WhereConSaldo.AddWithValue("numero", qGen.ComparisonOperators.NotEqual, 0);
            WhereConSaldo.AddWithValue("id_formapago", qGen.ComparisonOperators.In, new int[] { 1, 3, 99 });
            WhereConSaldo.AddWithValue("id_cliente", this.Persona.Id);
            WhereConSaldo.AddWithValue("cancelado", qGen.ComparisonOperators.LessThan, new qGen.SqlExpression("total"));
            // impresa>0 AND anulada=0 AND numero>0 AND id_formapago IN (1, 3, 99) AND cancelado<total AND id_cliente=this.Persona.Id

            if (importe > 0)
            {
                // Es un crédito, cancelo Facturas y Notas de Débito de venta y Notas de Crédito de compra
                qGen.Where WhereTipoCredVenta = new qGen.Where();
                WhereTipoCredVenta.AddWithValue("compra", 0);
                WhereTipoCredVenta.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "FA", "FB", "FC", "FE", "FM", "NDA", "NDB", "NDC", "NDE", "NDM", "T" });

                qGen.Where WhereTipoCredCompra = new qGen.Where();
                WhereTipoCredCompra.AddWithValue("compra", 1);
                WhereTipoCredCompra.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "NCA", "NCB", "NCC", "NCE", "NCM" });

                qGen.Where WhereTipoCred = new qGen.Where(qGen.AndOr.Or);
                WhereTipoCred.AddWithValue(WhereTipoCredVenta);
                WhereTipoCred.AddWithValue(WhereTipoCredCompra);

                WhereConSaldo.AddWithValue(WhereTipoCred);

                /*  AND (compra=0 AND tipo_fac IN ('FA', 'FB', 'FC', 'FE', 'FM', 'NDA', 'NDB', 'NDC', 'NDE', 'NDM')
                 *  OR (compra=1 AND tipo_fac IN ('NCA', 'NCB', 'NCC', 'NCE', 'NCM') */
            }
            else
            {
                // Es un débito. Cancelo Notas de Crédito de venta y Facturas y Notas de Débito de compra
                qGen.Where WhereTipoCredVenta = new qGen.Where();
                WhereTipoCredVenta.AddWithValue("compra", 1);
                WhereTipoCredVenta.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "FA", "FB", "FC", "FE", "FM", "NDA", "NDB", "NDC", "NDE", "NDM", "T" });

                qGen.Where WhereTipoCredCompra = new qGen.Where();
                WhereTipoCredCompra.AddWithValue("compra", 0);
                WhereTipoCredCompra.AddWithValue("tipo_fac", qGen.ComparisonOperators.In, new string[] { "NCA", "NCB", "NCC", "NCE", "NCM" });

                qGen.Where WhereTipoCred = new qGen.Where(qGen.AndOr.Or);
                WhereTipoCred.AddWithValue(WhereTipoCredVenta);
                WhereTipoCred.AddWithValue(WhereTipoCredCompra);

                WhereConSaldo.AddWithValue(WhereTipoCred);

                /*  AND (compra=1 AND tipo_fac IN ('FA', 'FB', 'FC', 'FE', 'FM', 'NDA', 'NDB', 'NDC', 'NDE', 'NDM')
                 *  OR (compra=0 AND tipo_fac IN ('NCA', 'NCB', 'NCC', 'NCE', 'NCM') */
            }

            qGen.Select SelFacturasConSaldo = new qGen.Select("comprob", true);
            SelFacturasConSaldo.Fields      = "id_comprob,total,cancelado";
            SelFacturasConSaldo.WhereClause = WhereConSaldo;
            SelFacturasConSaldo.Order       = "id_comprob";
            System.Data.DataTable FacturasConSaldo = this.Connection.Select(SelFacturasConSaldo);

            decimal ImporteCancelar  = Math.Abs(importe);
            decimal ImporteCancelado = 0;

            foreach (System.Data.DataRow Factura in FacturasConSaldo.Rows)
            {
                decimal SaldoComprob           = System.Convert.ToDecimal(Factura["total"]) - System.Convert.ToDecimal(Factura["cancelado"]);
                decimal ImporteCancelarComprob = SaldoComprob;

                if (ImporteCancelarComprob > ImporteCancelar)
                {
                    ImporteCancelarComprob = ImporteCancelar;
                }

                qGen.Update ActCancelarComprob = new qGen.Update("comprob");
                ActCancelarComprob.Fields.AddWithValue("cancelado", System.Convert.ToDecimal(Factura["cancelado"]) + ImporteCancelarComprob);
                ActCancelarComprob.WhereClause = new qGen.Where("id_comprob", System.Convert.ToInt32(Factura["id_comprob"]));
                this.Connection.Execute(ActCancelarComprob);
                ImporteCancelar  -= ImporteCancelarComprob;
                ImporteCancelado += ImporteCancelarComprob;

                if (ImporteCancelar <= 0)
                {
                    break;
                }
            }

            return(ImporteCancelado);
        }
Ejemplo n.º 19
0
        public void Poll()
        {
            if (this.Connection.State != System.Data.ConnectionState.Open)
            {
                this.Connection.Open();
            }

            qGen.Where WhereUsuario = new qGen.Where(qGen.AndOr.Or);
            WhereUsuario.AddWithValue("id_destinatario", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
            WhereUsuario.AddWithValue("id_destinatario", null);
            if (Lbl.Sys.Config.Actual.UsuarioConectado.Persona.Grupo != null)
            {
                WhereUsuario.AddWithValue("id_grupo", Lbl.Sys.Config.Actual.UsuarioConectado.Persona.Grupo.Id);
            }
            if (Lbl.Sys.Config.Actual.UsuarioConectado.Persona.SubGrupo != null)
            {
                WhereUsuario.AddWithValue("id_grupo", Lbl.Sys.Config.Actual.UsuarioConectado.Persona.SubGrupo.Id);
            }


            qGen.Select SelMensajesSinLeer = new qGen.Select("sys_mensajes");

            SelMensajesSinLeer.WhereClause = new qGen.Where();
            //SelMensajesSinLeer.WhereClause.AddWithValue("estacion_recibe", Lfx.Environment.SystemInformation.MachineName);
            SelMensajesSinLeer.WhereClause.AddWithValue("id_mensaje", qGen.ComparisonOperators.GreaterThan, this.LastMessageId);
            SelMensajesSinLeer.WhereClause.AddWithValue(WhereUsuario);
            SelMensajesSinLeer.Order = "id_mensaje";

            System.Data.DataTable TablaMensajes;
            try {
                TablaMensajes = this.Connection.Select(SelMensajesSinLeer);
                foreach (System.Data.DataRow Mensaje in TablaMensajes.Rows)
                {
                    INotificacion Res = new NotificacionRegistro(this.Connection, (Lfx.Data.Row)(Mensaje));
                    this.LastMessageId = System.Convert.ToInt32(Mensaje["id_mensaje"]);
                    string Destino = System.Convert.ToString(Mensaje["destino"]);
                    if (Lfx.Components.Manager.ComponentesCargados.ContainsKey(Destino))
                    {
                        // Lo notifico via IPC
                        Lfx.Workspace.Master.RunTime.Notify(Destino, Res);

                        // Se lo notifico directamente al componente
                        Lfx.Components.Manager.ComponentesCargados[Destino].ComponentInstance.Do("Notify", new object[] { Res });
                    }
                    else
                    {
                        Lfx.Workspace.Master.RunTime.Notify(Destino, Res);
                    }
                }

                qGen.Insert ActualizarEstado = new qGen.Insert("sys_mensajeria");
                ActualizarEstado.OnDuplicateKeyUpdate = true;
                ActualizarEstado.ColumnValues.AddWithValue("id_usuario", Lbl.Sys.Config.Actual.UsuarioConectado.Id);
                ActualizarEstado.ColumnValues.AddWithValue("estacion", Lfx.Environment.SystemInformation.MachineName);
                ActualizarEstado.ColumnValues.AddWithValue("nombre", Lbl.Sys.Config.Actual.UsuarioConectado.Nombre);
                ActualizarEstado.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
                if (this.LastMessageId > 0)
                {
                    ActualizarEstado.ColumnValues.AddWithValue("id_ultimomensaje", this.LastMessageId);
                }

                this.Connection.ExecuteNonQuery(ActualizarEstado);
            } catch (Exception ex) {
                System.Console.WriteLine(ex.Message);
                if (Lfx.Environment.SystemInformation.DesignMode)
                {
                    throw;
                }
                else
                {
                    return;
                }
            }
        }
Ejemplo n.º 20
0
                protected qGen.Select SelectCommand(string agrFunction, string onField, qGen.Where additionalFilters)
                {
                        if (this.Connection != null && this.Definicion != null && this.Definicion.TableName != null) {
                                qGen.Select ComandoSelect = new qGen.Select(this.Connection.SqlMode);

                                // Genero la lista de tablas, con JOIN y todo
                                string ListaTablas = null;
                                ListaTablas = this.Definicion.TableName;

                                if (this.Definicion.Joins != null && this.Definicion.Joins.Count > 0)
                                        ComandoSelect.Joins = this.Definicion.Joins;

                                foreach (Lazaro.Pres.Field Fld in this.Definicion.Columns) {
                                        if (Fld.DataType == Lfx.Data.InputFieldTypes.Relation && Fld.Relation != null) {
                                                qGen.Join RelJoin = new qGen.Join(Fld.Relation);
                                                if (ComandoSelect.Joins.Contains(RelJoin) == false)
                                                        ComandoSelect.Joins.Add(RelJoin);
                                        }
                                }

                                string ListaCampos;
                                if (agrFunction != null) {
                                        if (onField == null)
                                                onField = this.Definicion.KeyColumn.Name;
                                        string Alias = agrFunction + "_" + onField.Replace(".", "_");
                                        ListaCampos = agrFunction + "(" + onField + ") AS " + Alias;
                                } else {
                                        // Genero la lista de campos
                                        ListaCampos = this.Definicion.KeyColumn.Name;
                                        foreach (Lazaro.Pres.Field CurField in this.Definicion.Columns)
                                                ListaCampos += "," + CurField.Name;
                                }

                                // Genero las condiciones del WHERE
                                qGen.Where WhereBuscarTexto = new qGen.Where();
                                WhereBuscarTexto.Operator = qGen.AndOr.Or;

                                if (this.SearchText != string.Empty) {
                                        bool EsNumero = this.SearchText.IsNumericInt() || this.SearchText.IsNumericFloat();
                                        if (this.SearchText.IsNumericInt())
                                                WhereBuscarTexto.AddWithValue(this.Definicion.KeyColumn.Name, Lfx.Types.Parsing.ParseInt(this.SearchText).ToString());

                                        if (this.Definicion.Columns != null) {
                                                
                                                
                                                foreach (Lazaro.Pres.Field CurField in this.Definicion.Columns) {
                                                        if (CurField.Name.IndexOf(" AS ") == -1 && CurField.Name.IndexOf("(") == -1) {
                                                                switch (CurField.DataType) {
                                                                        case Lfx.Data.InputFieldTypes.Binary:
                                                                        case Lfx.Data.InputFieldTypes.Image:
                                                                        case Lfx.Data.InputFieldTypes.Bool:
                                                                        case Lfx.Data.InputFieldTypes.Set:
                                                                                // En estos tipos de campos no se busca
                                                                                break;
                                                                        case Lfx.Data.InputFieldTypes.Date:
                                                                        case Lfx.Data.InputFieldTypes.DateTime:
                                                                                // En estos campos, busco atento a que se trata de una fecha
                                                                                NullableDateTime Fecha = SearchText.ParseDateTime();    // TODO: cachear el valor para que no lo parsee en cada iteración
                                                                                if (Fecha != null) {
                                                                                        DateTime SearchDate = Fecha.Value;
                                                                                        DateTime FromDate = new DateTime(SearchDate.Year, SearchDate.Month, SearchDate.Day, 0, 0, 0);
                                                                                        DateTime ToDate = new DateTime(SearchDate.Year, SearchDate.Month, SearchDate.Day, 23, 59, 59);
                                                                                        WhereBuscarTexto.AddWithValue(CurField.Name, FromDate, ToDate);
                                                                                }
                                                                                break;
                                                                        case Lfx.Data.InputFieldTypes.Currency:
                                                                        case Lfx.Data.InputFieldTypes.Integer:
                                                                        case Lfx.Data.InputFieldTypes.Numeric:
                                                                        case Lfx.Data.InputFieldTypes.NumericSet:
                                                                        case Lfx.Data.InputFieldTypes.Serial:
                                                                                // En estos tipos de campos busco sólo números
                                                                                if (EsNumero)
                                                                                        WhereBuscarTexto.AddWithValue(CurField.Name, qGen.ComparisonOperators.InsensitiveLike, "%" + this.SearchText + "%");
                                                                                break;
                                                                        case Lfx.Data.InputFieldTypes.Relation:
                                                                        default:
                                                                                WhereBuscarTexto.AddWithValue(CurField.Name, qGen.ComparisonOperators.InsensitiveLike, "%" + this.SearchText + "%");
                                                                                break;
                                                                }

                                                        }
                                                }
                                        }
                                        if (this.Definicion.ExtraSearchColumns != null) {
                                                foreach (Lazaro.Pres.Field CurField in this.Definicion.ExtraSearchColumns) {
                                                        switch (CurField.DataType) {
                                                                case Lfx.Data.InputFieldTypes.Binary:
                                                                case Lfx.Data.InputFieldTypes.Image:
                                                                        // En estos tipos de campos no se busca
                                                                        break;
                                                                case Lfx.Data.InputFieldTypes.Currency:
                                                                case Lfx.Data.InputFieldTypes.Integer:
                                                                case Lfx.Data.InputFieldTypes.Numeric:
                                                                case Lfx.Data.InputFieldTypes.NumericSet:
                                                                case Lfx.Data.InputFieldTypes.Serial:
                                                                        // En estos tipos de campos busco sólo números
                                                                        if (EsNumero)
                                                                                WhereBuscarTexto.AddWithValue(CurField.Name, qGen.ComparisonOperators.InsensitiveLike, "%" + this.SearchText + "%");
                                                                        break;
                                                                case Lfx.Data.InputFieldTypes.Relation:
                                                                default:
                                                                        WhereBuscarTexto.AddWithValue(CurField.Name, qGen.ComparisonOperators.InsensitiveLike, "%" + this.SearchText + "%");
                                                                        break;
                                                        }
                                                }
                                        }
                                }

                                qGen.Where WhereCompleto = new qGen.Where();
                                WhereCompleto.Operator = qGen.AndOr.And;

                                if (m_Labels != null) {
                                        if (m_LabelField == null || m_LabelField.Length == 0)
                                                m_LabelField = this.Definicion.KeyColumn.Name;
                                        if (m_Labels.Count == 1) {
                                                // Ids negativos sólo cuando hay una sola etiqueta
                                                if (m_Labels[0] > 0)
                                                        WhereCompleto.AddWithValue(m_LabelField, qGen.ComparisonOperators.In, new qGen.SqlExpression("(SELECT item_id FROM sys_labels_values WHERE id_label=" + m_Labels[0].ToString() + ")"));
                                                else
                                                        WhereCompleto.AddWithValue(m_LabelField, qGen.ComparisonOperators.NotIn, new qGen.SqlExpression("(SELECT item_id FROM sys_labels_values WHERE id_label=" + (-m_Labels[0]).ToString() + ")"));
                                        } else if (m_Labels.Count > 1) {
                                                string[] LabelsString = Array.ConvertAll<int, string>(m_Labels.ToArray(), new Converter<int, string>(Convert.ToString));
                                                WhereCompleto.AddWithValue(m_LabelField, qGen.ComparisonOperators.In, new qGen.SqlExpression("(SELECT item_id FROM sys_labels_values WHERE id_label IN (" + string.Join(",", LabelsString) + "))"));
                                        }
                                }

                                if (WhereBuscarTexto.Count > 0)
                                        WhereCompleto.AddWithValue(WhereBuscarTexto);

                                if (m_CustomFilters != null && m_CustomFilters.Count > 0)
                                        WhereCompleto.AddWithValue(m_CustomFilters);

                                if (m_FixedFilters != null && m_FixedFilters.Count > 0)
                                        WhereCompleto.AddWithValue(m_FixedFilters);

                                if (additionalFilters != null && additionalFilters.Count > 0)
                                        WhereCompleto.AddWithValue(additionalFilters);

                                ComandoSelect.Tables = ListaTablas;
                                ComandoSelect.Fields = ListaCampos;
                                ComandoSelect.WhereClause = WhereCompleto;

                                if (this.Definicion.GroupBy != null && agrFunction == null)
                                        ComandoSelect.Group = this.Definicion.GroupBy.Name;

                                if (this.Definicion.Having != null)
                                        ComandoSelect.HavingClause = this.Definicion.Having;

                                if (agrFunction == null)
                                        ComandoSelect.Order = this.Definicion.OrderBy;

                                return ComandoSelect;
                        } else {
                                return null;
                        }
                }
Ejemplo n.º 21
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;
                        if (this.Existe == false) {
                                Comando = new qGen.Insert(Connection, "chequeras");
                                Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        } else {
                                Comando = new qGen.Update(Connection, "chequeras");
                                Comando.WhereClause = new qGen.Where("id_chequera", m_ItemId);
                        }

                        if (this.Banco == null)
                                Comando.Fields.AddWithValue("id_banco", null);
                        else
                                Comando.Fields.AddWithValue("id_banco", this.Banco.Id);
                        Comando.Fields.AddWithValue("prefijo", this.Prefijo);
                        Comando.Fields.AddWithValue("desde", this.Desde);
                        Comando.Fields.AddWithValue("hasta", this.Hasta);
                        if (this.Caja == null)
                                Comando.Fields.AddWithValue("id_caja", null);
                        else
                                Comando.Fields.AddWithValue("id_caja", this.Caja.Id);
                        if (this.Sucursal == null)
                                Comando.Fields.AddWithValue("id_sucursal", null);
                        else
                                Comando.Fields.AddWithValue("id_sucursal", this.Sucursal.Id);
                        Comando.Fields.AddWithValue("titular", this.Titular);
                        Comando.Fields.AddWithValue("estado", this.Estado);

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

                        if (this.Desde > 0 && this.Hasta > 0 && this.Hasta > this.Desde) {
				qGen.Update Actua = new qGen.Update("bancos_cheques");
				Actua.Fields.AddWithValue("id_chequera", this.Id);
				Actua.WhereClause = new qGen.Where();
                                Actua.WhereClause.AddWithValue("emitido", 1);
                                Actua.WhereClause.AddWithValue("id_banco", this.Banco.Id);
                                Actua.WhereClause.AddWithValue("numero", this.Desde, this.Hasta);
				Connection.Execute(Actua);
				
				Actua = new qGen.Update("bancos_cheques");
				Actua.Fields.Add(new Lfx.Data.Field("id_chequera", Lfx.Data.DbTypes.Integer, null));
				Actua.WhereClause = new qGen.Where();
                                Actua.WhereClause.AddWithValue("emitido", 1);
                                Actua.WhereClause.AddWithValue("id_banco", this.Banco.Id);
                                Actua.WhereClause.AddWithValue("id_chequera", this.Id);
                                qGen.Where Numeros = new qGen.Where(qGen.AndOr.Or);
                                Numeros.AddWithValue("numero", qGen.ComparisonOperators.LessThan, this.Desde);
                                Numeros.AddWithValue("numero", qGen.ComparisonOperators.GreaterThan, this.Hasta);
                                Actua.WhereClause.AddWithValue(Numeros);
				Connection.Execute(Actua);

                        }

                        return base.Guardar();
                }