Пример #1
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("fecha", this.Fecha);
                        Comando.Fields.AddWithValue("auto", this.Auto ? 1 : 0);
                        Comando.Fields.AddWithValue("concepto", this.Nombre);
                        Comando.Fields.AddWithValue("id_cliente", this.IdCliente);
                        Comando.Fields.AddWithValue("importe", this.Importe);
                        Comando.Fields.AddWithValue("comprob", this.Comprobantes);
                        Comando.Fields.AddWithValue("obs", this.Obs);

                        if (this.IdConcepto == 0)
                                Comando.Fields.AddWithValue("id_concepto", null);
                        else
                                Comando.Fields.AddWithValue("id_concepto", this.IdConcepto);

                        this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

                        return base.Guardar();
                }
Пример #2
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", qGen.SqlFunctions.Now);
                        } else {
                                Comando = new qGen.Update(this.Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        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("obs", this.Obs);
			Comando.Fields.AddWithValue("estado", this.Estado);

			this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

			return base.Guardar();
		}
Пример #3
0
        public override Lfx.Types.OperationResult Imprimir()
        {
            if (this.Comprobante.Impreso && this.Reimpresion == false)
            {
                this.Reimpresion = true;
            }

            Lfx.Types.OperationResult ResultadoImprimir = this.Comprobante.VerificarSeries();

            if (ResultadoImprimir.Success == false)
            {
                return(ResultadoImprimir);
            }

            if (this.Comprobante.Tipo.EsFactura && this.Comprobante.FormaDePago == null)
            {
                throw new InvalidOperationException("La factura no tiene forma de pago.");
            }

            if (this.Impresora == null)
            {
                this.Impresora = this.ObtenerImpresora();
            }

            if (this.Reimpresion == false && Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sistema.Documentos.ActualizaCostoAlFacturar", 1) != 0)
            {
                // Asiento los precios de costo de los artículos de la factura (con fines estadsticos)
                foreach (Lbl.Comprobantes.DetalleArticulo Det in this.Comprobante.Articulos)
                {
                    if (Det.Articulo != null)
                    {
                        qGen.Update Act = new qGen.Update("comprob_detalle");
                        Act.ColumnValues.AddWithValue("costo", Det.Articulo.CostoLocal);
                        Act.WhereClause = new qGen.Where("id_comprob_detalle", Det.Id);
                        this.Connection.ExecuteNonQuery(Act);
                    }
                }
            }

            ResultadoImprimir = base.Imprimir();

            // Los movimientos de stock y de dinero los asienta el servidor fiscal en los comprobantes fiscales
            if (this.Reimpresion == false && ResultadoImprimir.Success == true && this.ImprimiLocal)
            {
                //Resto el stock si corresponde
                this.Comprobante.MoverExistencias(false);

                // Asentar pagos si corresponde
                this.Comprobante.AsentarPago(false);
            }

            return(ResultadoImprimir);
        }
Пример #4
0
        /// <summary>
        /// Numera el comprobante (usando el número especificado), guardando automáticamente los cambios.
        /// </summary>
        /// <param name="numero">El número que se asignó a este comprobante.</param>
        /// <param name="cae">El CAE (sólo factura electrónica AFIP).</param>
        /// <param name="vencimientoCae">La fecha de vencimiento del CAE.</param>
        /// <param name="yMarcarComoImpreso">Si es Verdadero, el comprobante se marca como impreso y se actualiza la fecha.</param>
        public void Numerar(int numero, string cae, DateTime?vencimientoCae, bool yMarcarComoImpreso)
        {
            qGen.Update ActualizarComprob = new qGen.Update(this.Comprob.TablaDatos);

            // Modifico Registro para no volver a cargar el comprobante desde la BD
            this.Comprob.Numero             = numero;
            this.Comprob.Registro["numero"] = this.Comprob.Numero;
            ActualizarComprob.ColumnValues.AddWithValue("numero", numero);

            string Nombre = this.Comprob.PV.ToString("0000") + "-" + numero.ToString("00000000");

            this.Comprob.Nombre             = Nombre;
            this.Comprob.Registro["nombre"] = this.Comprob.Nombre;
            ActualizarComprob.ColumnValues.AddWithValue("nombre", Nombre);

            if (yMarcarComoImpreso)
            {
                this.Comprob.Estado             = 1;
                this.Comprob.Registro["estado"] = this.Comprob.Estado;
                ActualizarComprob.ColumnValues.AddWithValue("estado", 1);

                this.Comprob.Fecha             = this.Comprob.Connection.ServerDateTime;
                this.Comprob.Registro["fecha"] = this.Comprob.Fecha;
                ActualizarComprob.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));

                if (this.Comprob.TablaDatos == "recibos")
                {
                    this.Comprob.Impreso             = true;
                    this.Comprob.Registro["impreso"] = this.Comprob.Impreso ? 1 : 0;
                    ActualizarComprob.ColumnValues.AddWithValue("impreso", 1);
                }
                else
                {
                    this.Comprob.Impreso             = true;
                    this.Comprob.Registro["impresa"] = this.Comprob.Impreso ? 1 : 0;
                    ActualizarComprob.ColumnValues.AddWithValue("impresa", 1);
                }
            }

            if (this.Comprob is ComprobanteFacturable && string.IsNullOrEmpty(cae) == false && vencimientoCae.HasValue)
            {
                var ComprobFact = Comprob as ComprobanteFacturable;
                ComprobFact.CaeNumero = cae;
                ActualizarComprob.ColumnValues.AddWithValue("cae_numero", ComprobFact.CaeNumero);
                ComprobFact.CaeVencimiento = vencimientoCae.Value;
                ActualizarComprob.ColumnValues.AddWithValue("cae_vencimiento", ComprobFact.CaeVencimiento);
            }

            ActualizarComprob.WhereClause = new qGen.Where(this.Comprob.CampoId, this.Comprob.Id);

            this.Comprob.Connection.ExecuteNonQuery(ActualizarComprob);
        }
Пример #5
0
        public void Anular()
        {
            if (this.Anulado == false)
            {
                // Marco el cheque como anulado
                qGen.Update Act = new qGen.Update(this.TablaDatos);
                Act.ColumnValues.AddWithValue("estado", 1);
                Act.WhereClause = new qGen.Where(this.CampoId, this.Id);
                this.Connection.ExecuteNonQuery(Act);

                Lbl.Sys.Config.ActionLog(this.Connection, Lbl.Sys.Log.Acciones.Delete, this, null);
            }
        }
Пример #6
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;
            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                Comando.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.ColumnValues.AddWithValue("prefijo", this.Prefijo);
            Comando.ColumnValues.AddWithValue("numero", this.Numero);
            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);

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

            if (this.Impresora == null)
            {
                Comando.ColumnValues.AddWithValue("id_impresora", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_impresora", this.Impresora.Id);
            }
            Comando.ColumnValues.AddWithValue("tipo", (int)(this.Tipo));
            Comando.ColumnValues.AddWithValue("tipo_fac", this.TipoFac);
            Comando.ColumnValues.AddWithValue("detalonario", this.UsaTalonario ? 1 : 0);
            Comando.ColumnValues.AddWithValue("estacion", this.Estacion);
            Comando.ColumnValues.AddWithValue("carga", this.CargaManual ? 1 : 0);
            Comando.ColumnValues.AddWithValue("modelo", (int)(this.FiscalModeloImpresora));
            Comando.ColumnValues.AddWithValue("puerto", this.FiscalPuerto);
            Comando.ColumnValues.AddWithValue("bps", this.FiscalBps);
            Comando.ColumnValues.AddWithValue("variante", (int)this.Variante);

            this.AgregarTags(Comando);

            Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #7
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.TableCommand Comando;
            if (this.Existe == false)
            {
                Comando = new qGen.Insert(Connection, this.TablaDatos);
                Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
            }
            else
            {
                Comando             = new qGen.Update(Connection, this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.Fields.AddWithValue("prefijo", this.Prefijo);
            Comando.Fields.AddWithValue("numero", this.Numero);
            Comando.Fields.AddWithValue("nombre", this.Nombre);

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

            if (this.Impresora == null)
            {
                Comando.Fields.AddWithValue("id_impresora", null);
            }
            else
            {
                Comando.Fields.AddWithValue("id_impresora", this.Impresora.Id);
            }
            Comando.Fields.AddWithValue("tipo", (int)(this.Tipo));
            Comando.Fields.AddWithValue("tipo_fac", this.TipoFac);
            Comando.Fields.AddWithValue("detalonario", this.UsaTalonario ? 1 : 0);
            Comando.Fields.AddWithValue("estacion", this.Estacion);
            Comando.Fields.AddWithValue("carga", this.CargaManual ? 1 : 0);
            Comando.Fields.AddWithValue("modelo", (int)(this.ModeloImpresoraFiscal));
            Comando.Fields.AddWithValue("puerto", this.Puerto);
            Comando.Fields.AddWithValue("bps", this.Bps);

            this.AgregarTags(Comando);

            Connection.Execute(Comando);

            return(base.Guardar());
        }
Пример #8
0
        public void Pagar(Lbl.Cajas.Caja cajaOrigen)
        {
            cajaOrigen.Movimiento(true, this.Concepto,
                                  this.Concepto.Nombre,
                                  this.Cliente, -this.Importe,
                                  "Pago de " + this.ToString(),
                                  null,
                                  this.ReciboCobro != null ? this.ReciboCobro : this.ReciboPago,
                                  null);

            qGen.Update ActualizarEstado = new qGen.Update(this.TablaDatos);
            ActualizarEstado.ColumnValues.AddWithValue("estado", 10);
            ActualizarEstado.WhereClause = new qGen.Where(this.CampoId, this.Id);
            this.Connection.ExecuteNonQuery(ActualizarEstado);
        }
Пример #9
0
        public void CheckTable(Lfx.Types.OperationProgress progreso, Lfx.Data.Table table)
        {
            Lfx.Data.TableStructure CurrentTableDef = this.Connection.GetTableStructure(table.Name, true);
            progreso.ChangeStatus("Verificando tabla " + table.Name);

            foreach (Lfx.Data.ConstraintDefinition Cons in CurrentTableDef.Constraints.Values)
            {
                // Elimino valores 0 (los pongo en NULL)
                qGen.Update PonerNullablesEnNull = new qGen.Update(table.Name);
                PonerNullablesEnNull.ColumnValues.AddWithValue(Cons.Column, null);
                PonerNullablesEnNull.WhereClause = new qGen.Where(Cons.Column, 0);
                this.Connection.ExecuteNonQuery(PonerNullablesEnNull);

                // Busco problemas de integridad referencial
                if (Cons.TableName != Cons.ReferenceTable)
                {
                    qGen.Select RefValidas = new qGen.Select(Cons.ReferenceTable);
                    RefValidas.Columns = new qGen.SqlIdentifierCollection()
                    {
                        Cons.ReferenceColumn
                    };

                    qGen.Update ElimRefInvalidas = new qGen.Update(table.Name);
                    switch (Cons.ReferenceTable)
                    {
                    case "bancos":
                        // Los bancos inexistentes los remplazo por "otro banco"
                        ElimRefInvalidas.ColumnValues.AddWithValue(Cons.Column, 99);
                        break;

                    case "personas":
                        // Las personas inexistentes las paso a Administrador
                        ElimRefInvalidas.ColumnValues.AddWithValue(Cons.Column, 1);
                        break;

                    default:
                        // El resto lo pongo en null
                        ElimRefInvalidas.ColumnValues.AddWithValue(Cons.Column, null);
                        break;
                    }
                    ElimRefInvalidas.WhereClause = new qGen.Where(Cons.Column, qGen.ComparisonOperators.NotIn, RefValidas);

                    System.Console.WriteLine(ElimRefInvalidas.ToString());
                    this.Connection.ExecuteNonQuery(ElimRefInvalidas);
                }
            }
        }
Пример #10
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();
                }
Пример #11
0
        /// <summary>
        /// Propaga los cambios de costo hacia arriba.
        /// Es decir, si este artículo es ingrediente en la receta de otros artículos, actualizar los artículos padre para que reflejen el cambio de costo de este ingrediente.
        /// </summary>
        public void RecalcularCostoSuperArticulos()
        {
            ColeccionGenerica <Articulo> SuperArts = this.SuperArticulos();

            if (SuperArts != null)
            {
                foreach (Articulo SuperArt in SuperArts)
                {
                    SuperArt.Cargar();
                    qGen.Update UpdateSuperArt = new qGen.Update("articulos");
                    UpdateSuperArt.ColumnValues.AddWithValue("costo", SuperArt.ObtenerCosto());
                    UpdateSuperArt.WhereClause = new qGen.Where("id_articulo", SuperArt.Id);
                    this.Connection.ExecuteNonQuery(UpdateSuperArt);
                    SuperArt.RecalcularCostoSuperArticulos();
                }
            }
        }
Пример #12
0
        public bool WriteGlobalSetting(string settingName, string stringValue, string terminalName, int sucursal)
        {
            if (terminalName == null || terminalName.Length == 0)
            {
                terminalName = Lfx.Environment.SystemInformation.MachineName;
            }

            string CurrentValue = ReadGlobalSetting <string>(settingName, null, terminalName, sucursal);

            if (CurrentValue == null)
            {
                //Crear el valor
                qGen.Insert InsertCommand = new qGen.Insert("sys_config");
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("estacion", Lazaro.Orm.ColumnTypes.VarChar, terminalName));
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("id_sucursal", Lazaro.Orm.ColumnTypes.Integer, sucursal));
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("nombre", Lazaro.Orm.ColumnTypes.VarChar, settingName));
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("valor", Lazaro.Orm.ColumnTypes.VarChar, stringValue));
                Connection.Insert(InsertCommand);
            }
            else
            {
                //Actualizar el valor
                qGen.Update UpdateCommand = new qGen.Update("sys_config");
                UpdateCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("valor", Lazaro.Orm.ColumnTypes.VarChar, stringValue));
                UpdateCommand.WhereClause          = new qGen.Where();
                UpdateCommand.WhereClause.Operator = qGen.AndOr.And;
                UpdateCommand.WhereClause.Add(new qGen.ComparisonCondition("nombre", settingName));
                UpdateCommand.WhereClause.Add(new qGen.ComparisonCondition("estacion", terminalName));
                UpdateCommand.WhereClause.Add(new qGen.ComparisonCondition("id_sucursal", sucursal));
                Connection.Update(UpdateCommand);
            }

            string CacheSettingName = terminalName + "/" + sucursal.ToString() + "/" + settingName;

            if (this.SysConfigCache.ContainsKey(CacheSettingName))
            {
                this.SysConfigCache[CacheSettingName] = stringValue;
            }
            else
            {
                this.SysConfigCache.Add(CacheSettingName, stringValue);
            }

            return(true);
        }
Пример #13
0
 private void DepositarPagar_Click(object sender, System.EventArgs e)
 {
     if (this.Emitidos == false)
     {
         //Depositar
         Lbl.ListaIds Codigos = this.CodigosSeleccionados;
         if (Codigos == null || Codigos.Count == 0)
         {
             Lui.Forms.MessageBox.Show("Por favor seleccione uno o más cheques.", "Error");
         }
         else
         {
             Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Al depositar un cheque en una cuenta bancaria propia, puede marcarlo como depositado para control interno.\nSirve sólamente para depositos en cajas propias. Para depósitos en cajas de terceros utilice la opción 'Efectivizar'.", "¿Desea marcar los cheques seleccionados como depositados?");
             if (Pregunta.ShowDialog() == DialogResult.OK)
             {
                 using (IDbTransaction Trans = this.Connection.BeginTransaction()) {
                     qGen.Update Depo = new qGen.Update("bancos_cheques");
                     Depo.ColumnValues.AddWithValue("estado", 5);
                     Depo.WhereClause = new qGen.Where();
                     Depo.WhereClause.AddWithValue("estado", 0);
                     Depo.WhereClause.AddWithValue("id_cheque", qGen.ComparisonOperators.In, Codigos);
                     this.Connection.ExecuteNonQuery(Depo);
                     Trans.Commit();
                 }
                 foreach (System.Windows.Forms.ListViewItem itm in Listado.Items)
                 {
                     if (itm.Checked)
                     {
                         itm.Checked = false;
                     }
                 }
                 this.RefreshList();
             }
         }
     }
     else
     {
         Lfx.Types.OperationResult Res = this.Pagar();
         if (Res.Success == false && Res.Message != null)
         {
             Lfx.Workspace.Master.RunTime.Toast(Res.Message, "Error");
         }
     }
 }
Пример #14
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("nombre", this.Nombre);
            Comando.Fields.AddWithValue("nombresing", this.NombreSingular);
            Comando.Fields.AddWithValue("stock_minimo", this.PuntoDeReposicion);
            Comando.Fields.AddWithValue("web", this.PublicacionWeb);
            Comando.Fields.AddWithValue("requierens", ((int)(this.Seguimiento)));
            Comando.Fields.AddWithValue("obs", this.Obs);
            if (this.Rubro == null)
            {
                Comando.Fields.AddWithValue("id_rubro", null);
            }
            else
            {
                Comando.Fields.AddWithValue("id_rubro", this.Rubro.Id);
            }
            if (this.Alicuota == null)
            {
                Comando.Fields.AddWithValue("id_alicuota", null);
            }
            else
            {
                Comando.Fields.AddWithValue("id_alicuota", this.Alicuota.Id);
            }
            Comando.Fields.AddWithValue("garantia", this.Garantia);

            this.AgregarTags(Comando);

            this.Connection.Execute(Comando);

            return(base.Guardar());
        }
Пример #15
0
 private void UpdatePV(string campo = "ultimoz")
 {
     try
     {
         //Si hizo un cierre Z correctamente, actualizo la variable LCZ
         using (IDbTransaction Trans = this.Impresora.Connection.BeginTransaction())
         {
             qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
             Actualizar.ColumnValues.AddWithValue(campo, new qGen.SqlExpression("NOW()"));
             this.Impresora.Connection.ExecuteNonQuery(Actualizar);
             Trans.Commit();
             Trans.Dispose();
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex.Message);
     }
 }
Пример #16
0
        public override Lfx.Types.OperationResult Guardar(Lfx.Data.IConnection conn)
        {
            qGen.IStatement Comando;

            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                Comando.ColumnValues.AddWithValue(CampoId, IdComprob);
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, IdComprob);
            }
            Comando.ColumnValues.AddWithValue("cliente_free", this.Nombre);
            conn.ExecuteNonQuery(Comando);

            return(new Lfx.Types.SuccessOperationResult());
        }
                public override Lfx.Types.OperationResult Imprimir()
                {
                        if (this.Comprobante.Impreso && this.Reimpresion == false)
                                this.Reimpresion = true;

                        Lfx.Types.OperationResult ResultadoImprimir = this.Comprobante.VerificarSeries();

                        if (ResultadoImprimir.Success == false)
                                return ResultadoImprimir;

                        if (this.Comprobante.Tipo.EsFactura && this.Comprobante.FormaDePago == null)
                                throw new InvalidOperationException("La factura no tiene forma de pago.");

                        if (this.Impresora == null)
                                this.Impresora = this.ObtenerImpresora();

                        if (this.Reimpresion == false && Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting<int>("Sistema.Documentos.ActualizaCostoAlFacturar", 1) != 0) {
                                // Asiento los precios de costo de los artículos de la factura (con fines estadsticos)
                                foreach (Lbl.Comprobantes.DetalleArticulo Det in this.Comprobante.Articulos) {
                                        if (Det.Articulo != null) {
                                                qGen.Update Act = new qGen.Update("comprob_detalle");
                                                Act.Fields.AddWithValue("costo", Det.Articulo.Costo);
                                                Act.WhereClause = new qGen.Where("id_comprob_detalle", Det.Id);
                                                this.Connection.Execute(Act);
                                        }
                                }
                        }

                        ResultadoImprimir = base.Imprimir();

                        // Los movimientos de stock y de dinero los asienta el servidor fiscal en los comprobantes fiscales
                        if (this.Reimpresion == false && ResultadoImprimir.Success == true && this.ImprimiLocal) {
                                //Resto el stock si corresponde
                                this.Comprobante.MoverExistencias(false);

                                // Asentar pagos si corresponde
                                this.Comprobante.AsentarPago(false);
                        }

                        return ResultadoImprimir;
                }
Пример #18
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;
            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                Comando.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);
            Comando.ColumnValues.AddWithValue("estacion", this.Estacion);
            Comando.ColumnValues.AddWithValue("id_impresora", this.Tipo.Id);
            Comando.ColumnValues.AddWithValue("id_tipo", this.Impresora.Id);
            if (this.Sucursal == null)
            {
                Comando.ColumnValues.AddWithValue("id_sucursal", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_sucursal", this.Sucursal.Id);
            }
            if (this.PuntoDeVenta == null)
            {
                Comando.ColumnValues.AddWithValue("id_pv", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_pv", this.PuntoDeVenta.Id);
            }

            this.AgregarTags(Comando);

            Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #19
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;
            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                Comando.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.ColumnValues.AddWithValue(this.CampoNombre, this.Nombre);
            Comando.ColumnValues.AddWithValue("titular", this.Titular);
            if (Banco == null)
            {
                Comando.ColumnValues.AddWithValue("id_banco", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_banco", this.Banco.Id);
            }
            if (this.Moneda == null)
            {
                Comando.ColumnValues.AddWithValue("id_moneda", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_moneda", this.Moneda.Id);
            }
            Comando.ColumnValues.AddWithValue("numero", this.Numero);
            Comando.ColumnValues.AddWithValue("tipo", (int)(this.Tipo));
            Comando.ColumnValues.AddWithValue("cbu", this.ClaveBancaria);
            Comando.ColumnValues.AddWithValue("estado", this.Estado);

            Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #20
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;
                        if (this.Existe == false) {
                                Comando = new qGen.Insert(Connection, "conceptos");
                        } else {
                                Comando = new qGen.Update(Connection, "conceptos");
                                Comando.WhereClause = new qGen.Where("id_concepto", this.Id);
                        }

                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("es", this.Direccion);
                        if (this.Grupo == 0)
                                Comando.Fields.AddWithValue("grupo", null);
                        else
                                Comando.Fields.AddWithValue("grupo", this.Grupo);

                        Connection.Execute(Comando);

                        return base.Guardar();
                }
Пример #21
0
        /// <summary>
        /// Recalcula completamente el saldo de la caja, para corregir errores de transporte. Principalmente de uso interno.
        /// </summary>
        public void Recalcular()
        {
            Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Recalculando", "Se va a recalcular el saldo de la caja " + this.ToString());
            Progreso.Begin();

            System.Data.DataTable Movims = this.Connection.Select("SELECT id_movim, importe FROM cajas_movim WHERE id_caja=" + this.Caja.Id.ToString() + " ORDER BY id_movim");
            decimal Saldo = 0;

            Progreso.Max = Movims.Rows.Count;
            foreach (System.Data.DataRow Movim in Movims.Rows)
            {
                Saldo += System.Convert.ToDecimal(Movim["importe"]);

                qGen.Update Upd = new qGen.Update("cajas_movim");
                Upd.ColumnValues.AddWithValue("saldo", Saldo);
                Upd.WhereClause = new qGen.Where("id_movim", System.Convert.ToInt32(Movim["id_movim"]));
                this.Connection.ExecuteNonQuery(Upd);

                Progreso.Advance(1);
            }
            Progreso.End();
        }
Пример #22
0
        public bool WriteGlobalSetting(string settingName, string stringValue, int branch)
        {
            string CurrentValue = ReadGlobalSetting <string>(settingName, null, null, branch);

            if (CurrentValue == null)
            {
                //Crear el valor
                qGen.Insert InsertCommand = new qGen.Insert("sys_config");
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("id_sucursal", Lazaro.Orm.ColumnTypes.Integer, branch));
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("estacion", Lazaro.Orm.ColumnTypes.VarChar, "*"));
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("nombre", Lazaro.Orm.ColumnTypes.VarChar, settingName));
                InsertCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("valor", Lazaro.Orm.ColumnTypes.VarChar, stringValue));
                Connection.Insert(InsertCommand);
            }
            else
            {
                //Actualizar el valor
                qGen.Update UpdateCommand = new qGen.Update("sys_config");
                UpdateCommand.ColumnValues.Add(new Lazaro.Orm.Data.ColumnValue("valor", Lazaro.Orm.ColumnTypes.VarChar, stringValue));
                UpdateCommand.WhereClause          = new qGen.Where();
                UpdateCommand.WhereClause.Operator = qGen.AndOr.And;
                UpdateCommand.WhereClause.Add(new qGen.ComparisonCondition("nombre", settingName));
                UpdateCommand.WhereClause.Add(new qGen.ComparisonCondition("id_sucursal", branch));
                Connection.Update(UpdateCommand);
            }

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

            if (this.SysConfigCache.ContainsKey(CacheSettingName))
            {
                this.SysConfigCache[CacheSettingName] = stringValue;
            }
            else
            {
                this.SysConfigCache.Add(CacheSettingName, stringValue);
            }

            return(true);
        }
Пример #23
0
        private void EntradaComprobanteId_TextChanged(object sender, System.EventArgs e)
        {
            int ComprobanteId = Lfx.Types.Parsing.ParseInt(EntradaComprobanteId.Text);

            if (ComprobanteId > 0)
            {
                EntradaComprobante.Text = Lbl.Comprobantes.Comprobante.TipoYNumeroCompleto(this.Connection, ComprobanteId);
                // Guardo el comprobante en la tarea (sólo si no tenía uno asociado)
                using (System.Data.IDbTransaction Trans = this.Connection.BeginTransaction()) {
                    qGen.Update Actual = new qGen.Update("tickets");
                    Actual.Fields.Add(new Lfx.Data.Field("id_comprob", ComprobanteId));
                    Actual.WhereClause = new qGen.Where();
                    Actual.WhereClause.AddWithValue("id_comprob", 0);
                    Actual.WhereClause.AddWithValue("id_ticket", this.Elemento.Id);
                    this.Connection.Execute(Actual);
                    Trans.Commit();
                }
            }
            else
            {
                EntradaComprobante.Text = "";
            }
        }
Пример #24
0
        public void End(bool reboot)
        {
            Programador.Stop();

            if (this.PV != 0)
            {
                using (System.Data.IDbTransaction Trans = this.Impresora.Connection.BeginTransaction()) {
                    qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
                    Actualizar.ColumnValues.AddWithValue("lsa", null);
                    this.Impresora.Connection.ExecuteNonQuery(Actualizar);
                    Trans.Commit();
                }
            }

            Impresora.Terminar();
            FormEstado.Close();

            if (reboot)
            {
                Lfx.Environment.Shell.Execute(System.Environment.CommandLine, string.Join(" ", System.Environment.GetCommandLineArgs()), System.Diagnostics.ProcessWindowStyle.Minimized, false);
            }
            System.Windows.Forms.Application.Exit();
        }
Пример #25
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;
                        if (this.Existe == false) {
                                Comando = new qGen.Insert(Connection, "personas_grupos");
                                Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        } else {
                                Comando = new qGen.Update(Connection, "personas_grupos");
                                Comando.WhereClause = new qGen.Where("id_grupo", this.Id);
                        }

                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("descuento", this.Descuento);
                        Comando.Fields.AddWithValue("predet", this.Predeterminado ? 1 : 0);
                        if (this.Parent != null)
                                Comando.Fields.AddWithValue("parent", this.Parent.Id);
                        else
                                Comando.Fields.AddWithValue("parent", null);

                        Connection.Execute(Comando);
                        
                        return base.Guardar();
                }
Пример #26
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("nombre", this.Nombre);
                        if (this.Alicuota == null)
                                Comando.Fields.AddWithValue("id_alicuota", null);
                        else
                                Comando.Fields.AddWithValue("id_alicuota", this.Alicuota.Id);

			this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

			return base.Guardar();
		}
Пример #27
0
        public void Save()
        {
            qGen.TableCommand InsertOrUpdate;
            if (this.Id == 0)
            {
                InsertOrUpdate = new qGen.Insert("sys_tags");
            }
            else
            {
                InsertOrUpdate             = new qGen.Update("sys_tags");
                InsertOrUpdate.WhereClause = new qGen.Where("id_tag", this.Id);
            }

            InsertOrUpdate.Fields.AddWithValue("tablename", this.TableName);
            InsertOrUpdate.Fields.AddWithValue("fieldname", this.FieldName);
            InsertOrUpdate.Fields.AddWithValue("label", this.Label);
            switch (this.FieldType)
            {
            case DbTypes.VarChar:
                InsertOrUpdate.Fields.AddWithValue("fieldtype", "varchar");
                break;

            case DbTypes.Integer:
                InsertOrUpdate.Fields.AddWithValue("fieldtype", "integer");
                break;

            case DbTypes.Text:
                InsertOrUpdate.Fields.AddWithValue("fieldtype", "text");
                break;
            }
            InsertOrUpdate.Fields.AddWithValue("fieldnullable", this.Nullable ? 1 : 0);
            InsertOrUpdate.Fields.AddWithValue("fielddefault", this.DefaultValue);
            InsertOrUpdate.Fields.AddWithValue("internal", this.Internal ? 1 : 0);
            InsertOrUpdate.Fields.AddWithValue("access", this.Access);

            this.DataBase.Execute(InsertOrUpdate);
        }
Пример #28
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;

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

            Comando.ColumnValues.AddWithValue("fecha", this.Fecha);
            Comando.ColumnValues.AddWithValue("auto", this.Auto ? 1 : 0);
            Comando.ColumnValues.AddWithValue("concepto", this.Nombre);
            Comando.ColumnValues.AddWithValue("id_cliente", this.IdCliente);
            Comando.ColumnValues.AddWithValue("importe", this.Importe);
            Comando.ColumnValues.AddWithValue("comprob", this.Comprobantes);
            Comando.ColumnValues.AddWithValue("obs", this.Obs);

            if (this.IdConcepto == 0)
            {
                Comando.ColumnValues.AddWithValue("id_concepto", null);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_concepto", this.IdConcepto);
            }

            this.AgregarTags(Comando);

            this.Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #29
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;

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

            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);

            if (this.Tarjeta != null)
            {
                Comando.ColumnValues.AddWithValue("id_tarjeta", this.Tarjeta.Id);
            }
            else
            {
                Comando.ColumnValues.AddWithValue("id_tarjeta", null);
            }

            Comando.ColumnValues.AddWithValue("cuotas", this.Cuotas);
            Comando.ColumnValues.AddWithValue("interes", this.Interes);
            Comando.ColumnValues.AddWithValue("comision", this.Comision);

            Comando.ColumnValues.AddWithValue("obs", null);
            Comando.ColumnValues.AddWithValue("estado", true);

            this.AgregarTags(Comando);
            this.Connection.ExecuteNonQuery(Comando);
            return(base.Guardar());
        }
Пример #30
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;
            if (this.Existe == false)
            {
                Comando = new qGen.Insert(this.TablaDatos);
                if (this.Id > 0)
                {
                    Comando.ColumnValues.AddWithValue(this.CampoId, this.Id);
                }
                Comando.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
            }
            else
            {
                Comando             = new qGen.Update(this.TablaDatos);
                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
            }

            Comando.ColumnValues.AddWithValue("imagen", this.Imagen);

            Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #31
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", qGen.SqlFunctions.Now);
                        } else {
                                Comando = new qGen.Update(this.Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("porcentaje", this.Porcentaje);
                        Comando.Fields.AddWithValue("predet", this.Predeterminado ? 1 : 0);
                        Comando.Fields.AddWithValue("obs", this.Obs);
                        Comando.Fields.AddWithValue("estado", this.Estado);

                        this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

                        return base.Guardar();
                }
Пример #32
0
        /// <summary>
        /// Numera el comprobante (usando el número especificado), guardando automáticamente los cambios.
        /// </summary>
        /// <param name="numero">El número que se asignó a este comprobante.</param>
        /// <param name="yMarcarComoImpreso">Si es Verdadero, el comprobante se marca como impreso y se actualiza la fecha.</param>
        public void Numerar(int numero, bool yMarcarComoImpreso)
        {
            qGen.Update ActualizarComprob = new qGen.Update(this.Comprobante.TablaDatos);

            // Modifico Registro para no volver a cargar el comprobante desde la BD
            this.Comprobante.Registro["numero"] = numero;
            ActualizarComprob.ColumnValues.AddWithValue("numero", numero);

            string Nombre = this.Comprobante.PV.ToString("0000") + "-" + numero.ToString("00000000");

            this.Comprobante.Registro["nombre"] = Nombre;
            ActualizarComprob.ColumnValues.AddWithValue("nombre", Nombre);

            if (yMarcarComoImpreso)
            {
                this.Comprobante.Registro["estado"] = 1;

                this.Comprobante.Registro["fecha"] = this.Comprobante.Connection.ServerDateTime;

                if (this.Comprobante.TablaDatos == "recibos")
                {
                    ActualizarComprob.ColumnValues.AddWithValue("impreso", 1);
                    this.Comprobante.Registro["impreso"] = 1;
                }
                else
                {
                    ActualizarComprob.ColumnValues.AddWithValue("impresa", 1);
                    this.Comprobante.Registro["impresa"] = 1;
                }
                ActualizarComprob.ColumnValues.AddWithValue("estado", 1);
                ActualizarComprob.ColumnValues.AddWithValue("fecha", new qGen.SqlExpression("NOW()"));
            }
            ActualizarComprob.WhereClause = new qGen.Where(this.Comprobante.CampoId, this.Comprobante.Id);

            this.Comprobante.Connection.ExecuteNonQuery(ActualizarComprob);
        }
Пример #33
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;

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

            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);
            Comando.ColumnValues.AddWithValue("obs", this.Obs);
            Comando.ColumnValues.AddWithValue("estado", this.Estado);

            this.AgregarTags(Comando);

            this.Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #34
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("nombre", this.Nombre);
            Comando.Fields.AddWithValue("porcentaje", this.Porcentaje);
            Comando.Fields.AddWithValue("importe_minimo", this.ImporteMinimo);

            this.AgregarTags(Comando);

            this.Connection.Execute(Comando);

            return(base.Guardar());
        }
Пример #35
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();
                }
Пример #36
0
 private void DepositarPagar_Click(object sender, System.EventArgs e)
 {
         if (this.Emitidos == false) {
                 //Depositar
                 Lbl.ListaIds Codigos = this.CodigosSeleccionados;
                 if (Codigos == null || Codigos.Count == 0) {
                         Lui.Forms.MessageBox.Show("Por favor seleccione uno o más cheques.", "Error");
                 } else {
                         Lui.Forms.YesNoDialog Pregunta = new Lui.Forms.YesNoDialog("Al depositar un cheque en una cuenta bancaria propia, puede marcarlo como depositado para control interno.\nSirve sólamente para depositos en cajas propias. Para depósitos en cajas de terceros utilice la opción 'Efectivizar'.", "¿Desea marcar los cheques seleccionados como depositados?");
                         if (Pregunta.ShowDialog() == DialogResult.OK) {
                                 using (IDbTransaction Trans = this.Connection.BeginTransaction()) {
                                         qGen.Update Depo = new qGen.Update("bancos_cheques");
                                         Depo.Fields.AddWithValue("estado", 5);
                                         Depo.WhereClause = new qGen.Where();
                                         Depo.WhereClause.AddWithValue("estado", 0);
                                         Depo.WhereClause.AddWithValue("id_cheque", qGen.ComparisonOperators.In, Codigos);
                                         this.Connection.Execute(Depo);
                                         Trans.Commit();
                                 }
                                 foreach (System.Windows.Forms.ListViewItem itm in Listado.Items) {
                                         if (itm.Checked)
                                                 itm.Checked = false;
                                 }
                                 this.RefreshList();
                         }
                 }
         } else {
                 Lfx.Types.OperationResult Res = this.Pagar();
                 if (Res.Success == false && Res.Message != null)
                         Lfx.Workspace.Master.RunTime.Toast(Res.Message, "Error");
         }
 }
Пример #37
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;
                        if (this.Existe == false) {
                                Comando = new qGen.Insert(Connection, this.TablaDatos);
                                Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        } else {
                                Comando = new qGen.Update(Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        Comando.Fields.AddWithValue(this.CampoNombre, this.Nombre);
                        Comando.Fields.AddWithValue("titular", this.Titular);
                        if (Banco == null)
                                Comando.Fields.AddWithValue("id_banco", null);
                        else
                                Comando.Fields.AddWithValue("id_banco", this.Banco.Id);
                        if (this.Moneda == null)
                                Comando.Fields.AddWithValue("id_moneda", null);
                        else
                                Comando.Fields.AddWithValue("id_moneda", this.Moneda.Id);
                        Comando.Fields.AddWithValue("numero", this.Numero);
                        Comando.Fields.AddWithValue("tipo", (int)(this.Tipo));
                        Comando.Fields.AddWithValue("cbu", this.ClaveBancaria);
                        Comando.Fields.AddWithValue("estado", this.Estado);

                        Connection.Execute(Comando);

                        return base.Guardar();
                }
Пример #38
0
                /// <summary>
                /// Recalcula completamente el saldo de la caja, para corregir errores de transporte. Principalmente de uso interno.
                /// </summary>
                public void Recalcular()
                {
                        Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Recalculando", "Se va a recalcular el saldo de la caja " + this.ToString());
                        Progreso.Begin();

                        System.Data.DataTable Movims = this.Connection.Select("SELECT id_movim, importe FROM cajas_movim WHERE id_caja=" + this.Id.ToString() + " ORDER BY id_movim");
                        decimal Saldo = 0;
                        Progreso.Max = Movims.Rows.Count;
                        foreach (System.Data.DataRow Movim in Movims.Rows) {
                                Saldo += System.Convert.ToDecimal(Movim["importe"]);

                                qGen.Update Upd = new qGen.Update("cajas_movim");
                                Upd.Fields.AddWithValue("saldo", Saldo);
                                Upd.WhereClause = new qGen.Where("id_movim", System.Convert.ToInt32(Movim["id_movim"]));
                                this.Connection.Execute(Upd);

                                Progreso.Advance(1);
                        }
                        Progreso.End();
                }
Пример #39
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("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("nombresing", this.NombreSingular);
                        Comando.Fields.AddWithValue("stock_minimo", this.PuntoDeReposicion);
                        Comando.Fields.AddWithValue("web", this.PublicacionWeb);
                        Comando.Fields.AddWithValue("requierens", ((int)(this.Seguimiento)));
                        Comando.Fields.AddWithValue("obs", this.Obs);
                        if (this.Rubro == null)
                                Comando.Fields.AddWithValue("id_rubro", null);
                        else
                                Comando.Fields.AddWithValue("id_rubro", this.Rubro.Id);
                        if (this.Alicuota == null)
                                Comando.Fields.AddWithValue("id_alicuota", null);
                        else
                                Comando.Fields.AddWithValue("id_alicuota", this.Alicuota.Id);
                        Comando.Fields.AddWithValue("garantia", this.Garantia);

			this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

			return base.Guardar();
		}
Пример #40
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("nombre", this.Nombre);
                        Comando.Fields.AddWithValue("porcentaje", this.Porcentaje);
                        Comando.Fields.AddWithValue("importe_minimo", this.ImporteMinimo);

                        this.AgregarTags(Comando);

                        this.Connection.Execute(Comando);

                        return base.Guardar();
                }
Пример #41
0
                /// <summary>
                /// Asienta un movimiento en la cuenta corriente, y cancela comprobantes asociados.
                /// </summary>
                /// <param name="auto">Indica si es un movimiento automático (generado por el sistema) o manual (generado por el usuario).</param>
                /// <param name="concepto">El concepto bajo el cual se realiza el movimiento.</param>
                /// <param name="textoConcepto">El texto que describe al concepto.</param>
                /// <param name="importeDebito">El importe a debitar de la cuenta. Un importe negativo indica un crédito.</param>
                /// <param name="obs">Observaciones.</param>
                /// <param name="comprob">El comprobante asociado a este movimiento.</param>
                /// <param name="recibo">El recibo asociado a este movimiento.</param>
                /// <param name="textoComprob">Un texto sobre los comprobantes asociados al sistema.</param>
                /// <param name="extras">Colección de campos adicionales para el registro.</param>
                public void Movimiento(bool auto, 
                        Lbl.Cajas.Concepto concepto,
                        string textoConcepto,
                        decimal importeDebito,
                        string obs,
                        Lbl.Comprobantes.ComprobanteConArticulos comprob,
                        Lbl.Comprobantes.Recibo recibo,
                        string textoComprob,
                        Dictionary<string, object> extras)
                {
                        decimal SaldoActual = this.ObtenerSaldo(true);
                        decimal NuevoSaldo = SaldoActual + importeDebito;

                        qGen.Insert ComandoInsertarMovimiento = new qGen.Insert(this.Connection, this.TablaDatos);
				
                        ComandoInsertarMovimiento.Fields.AddWithValue("auto", auto ? (int)1 : (int)0);
                        if (concepto == null)
                                ComandoInsertarMovimiento.Fields.AddWithValue("id_concepto", null);
                        else
                                ComandoInsertarMovimiento.Fields.AddWithValue("id_concepto", concepto.Id);
                        ComandoInsertarMovimiento.Fields.AddWithValue("concepto", textoConcepto);
                        ComandoInsertarMovimiento.Fields.AddWithValue("id_cliente", this.Persona.Id);
			ComandoInsertarMovimiento.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        ComandoInsertarMovimiento.Fields.AddWithValue("importe", importeDebito);
                        if (comprob == null)
                                ComandoInsertarMovimiento.Fields.AddWithValue("id_comprob", null);
                        else
                                ComandoInsertarMovimiento.Fields.AddWithValue("id_comprob", comprob.Id);
                        if (recibo == null)
                                ComandoInsertarMovimiento.Fields.AddWithValue("id_recibo", null);
                        else
                                ComandoInsertarMovimiento.Fields.AddWithValue("id_recibo", recibo.Id);
                        ComandoInsertarMovimiento.Fields.AddWithValue("comprob", textoComprob);
                        ComandoInsertarMovimiento.Fields.AddWithValue("saldo", NuevoSaldo);
                        ComandoInsertarMovimiento.Fields.AddWithValue("obs", obs);

                        if (extras != null && extras.Count > 0) {
                                foreach (KeyValuePair<string, object> extra in extras) {
                                        ComandoInsertarMovimiento.Fields.AddWithValue(extra.Key, extra.Value);
                                }
                        }
                        this.Connection.Execute(ComandoInsertarMovimiento);

                        qGen.Update ComandoActualizarCliente = new qGen.Update("personas");
                        ComandoActualizarCliente.Fields.AddWithValue("saldo_ctacte", NuevoSaldo);
                        ComandoActualizarCliente.WhereClause = new qGen.Where("id_persona", this.Persona.Id);
                        this.Connection.Execute(ComandoActualizarCliente);
                }
Пример #42
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());
        }
Пример #43
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);
        }
Пример #44
0
 public void Activar(bool activar)
 {
         this.Estado = 0;
         qGen.Update ActCmd = new qGen.Update(this.TablaDatos);
         ActCmd.Fields.AddWithValue("estado", activar ? 1 : 0);
         ActCmd.WhereClause = new qGen.Where(this.CampoId, this.Id);
         this.Connection.Execute(ActCmd);
         Lbl.Sys.Config.ActionLog(this.Connection, Lbl.Sys.Log.Acciones.Delete, this, activar ? "Activar" : "Desactivar");
 }
Пример #45
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();
                }
Пример #46
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;
                }
Пример #47
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;
                }
Пример #48
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        this.Articulos.ElementoPadre = this;

			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);
                        }

                        if (this.Existe == false && this.Numero == 0 && this.Tipo.NumerarAlGuardar) {
                                this.Numerar(false);
                        }

                        if (this.Fecha.Year == 1) {
                                Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        } else {
                                Comando.Fields.AddWithValue("fecha", this.Fecha);
                        }

                        if (this.ComprobanteOriginal == null)
                                Comando.Fields.AddWithValue("id_comprob_orig", null);
                        else
                                Comando.Fields.AddWithValue("id_comprob_orig", this.ComprobanteOriginal.Id);

                        if(this.FormaDePago == null)
                                Comando.Fields.AddWithValue("id_formapago", null);
                        else
                                Comando.Fields.AddWithValue("id_formapago", FormaDePago.Id);

                        if (this.Vendedor == null)
                                Comando.Fields.AddWithValue("id_vendedor", null);
                        else
                                Comando.Fields.AddWithValue("id_vendedor", this.Vendedor.Id);
                        
                        if (this.Sucursal == null)
                                Comando.Fields.AddWithValue("id_sucursal", Lfx.Workspace.Master.CurrentConfig.Empresa.SucursalActual);
                        else
                                Comando.Fields.AddWithValue("id_sucursal", this.Sucursal.Id);

                        if (this.IdRemito == 0)
                                Comando.Fields.AddWithValue("id_remito", null);
                        else
                                Comando.Fields.AddWithValue("id_remito", this.IdRemito);

                        Comando.Fields.AddWithValue("pv", this.PV);
                        Comando.Fields.AddWithValue("numero", this.Numero);
                        Comando.Fields.AddWithValue("nombre", this.PV.ToString("0000") + "-" + this.Numero.ToString("00000000"));
                        Comando.Fields.AddWithValue("id_cliente", Lfx.Data.Connection.ConvertZeroToDBNull(this.Cliente.Id));
                        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);
                        Comando.Fields.AddWithValue("tipo_fac", this.Tipo.Nomenclatura);
                        Comando.Fields.AddWithValue("subtotal", this.SubTotalSinIva);
                        Comando.Fields.AddWithValue("descuento", this.Descuento);
                        Comando.Fields.AddWithValue("interes", this.Recargo);
                        Comando.Fields.AddWithValue("cuotas", this.Cuotas);
                        Comando.Fields.AddWithValue("total", this.Total);
                        Comando.Fields.AddWithValue("iva", this.ImporteIva);
                        Comando.Fields.AddWithValue("totalreal", this.TotalSinRedondeo);
                        Comando.Fields.AddWithValue("gastosenvio", this.GastosDeEnvio);
                        Comando.Fields.AddWithValue("otrosgastos", this.OtrosGastos);
                        Comando.Fields.AddWithValue("obs", this.Obs);
                        // Lo comprobantes de compra se marcan siempre como impresos
                        Comando.Fields.AddWithValue("impresa", this.Compra ? 1 : (this.Impreso ? 1 : 0));
                        Comando.Fields.AddWithValue("compra", this.Compra ? 1 : 0);
                        Comando.Fields.AddWithValue("estado", this.Estado);
                        Comando.Fields.AddWithValue("series", this.Articulos.DatosSeguimiento);
                        if (this.Tipo.EsFacturaOTicket == false && this.Tipo.EsNotaDebito == false) {
                                // Este comprobante no es cancelable
                                this.ImporteCancelado = this.Total;
                                Comando.Fields.AddWithValue("cancelado", this.Total);
                        }

			this.AgregarTags(Comando);

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

                        this.GuardarDetalle();

                        if (this.Compra) {
                                if (this.Tipo.MueveExistencias != 0) {
                                        // Comprobantes de compra mueven stock al guardar
                                        Lfx.Types.OperationResult Res = VerificarSeries();
                                        if (Res.Success == false)
                                                return Res;
                                }

                                if (this.Tipo.EsFacturaNCoND)
                                        this.AsentarPago(false);

                                if (this.Tipo.MueveExistencias != 0) {
                                        // Comprobantes de compra mueven stock al guardar
                                        this.MoverExistencias(false);

                                        Lbl.ListaIds ArticulosAfectados = new Lbl.ListaIds();
                                        foreach (DetalleArticulo Det in m_Articulos) {
                                                if (Det.IdArticulo != 0 && ArticulosAfectados.Contains(Det.IdArticulo) == false)
                                                        ArticulosAfectados.Add(Det.IdArticulo);
                                        }

                                        if (m_ArticulosOriginales != null) {
                                                foreach (DetalleArticulo Det in m_ArticulosOriginales) {
                                                        if (Det.IdArticulo > 0 && ArticulosAfectados.Contains(Det.IdArticulo) == false)
                                                                ArticulosAfectados.Add(Det.IdArticulo);
                                                }
                                        }

                                        if (ArticulosAfectados.Count > 0) {
                                                string ArtCsv = ArticulosAfectados.ToString();
                                                // Actualizo cantidades pedidas y a pedir
                                                Connection.ExecuteSql(@"UPDATE articulos SET apedir=(
							SELECT SUM(cantidad)
							FROM comprob, comprob_detalle
							WHERE comprob.id_comprob=comprob_detalle.id_comprob
							AND comprob.compra=1
							AND tipo_fac='NP' AND estado=50 AND comprob_detalle.id_articulo=articulos.id_articulo)
						WHERE control_stock=1 AND id_articulo IN (" + ArtCsv + " )");
                                                Connection.ExecuteSql(@"UPDATE articulos SET pedido=(
							SELECT SUM(cantidad)
							FROM comprob, comprob_detalle
							WHERE comprob.id_comprob=comprob_detalle.id_comprob
							AND comprob.compra=1
							AND tipo_fac='PD' AND estado=50 AND comprob_detalle.id_articulo=articulos.id_articulo)
						WHERE control_stock=1 AND id_articulo IN (" + ArtCsv + " )");
                                        }
                                }
                        }

                        return base.Guardar();
                }
Пример #49
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        qGen.TableCommand Comando;
                        if (this.Existe == false) {
                                Comando = new qGen.Insert(Connection, this.TablaDatos);
                                Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        } else {
                                Comando = new qGen.Update(Connection, this.TablaDatos);
                                Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        }

                        Comando.Fields.AddWithValue("prefijo", this.Prefijo);
                        Comando.Fields.AddWithValue("numero", this.Numero);
                        Comando.Fields.AddWithValue("nombre", this.Nombre);
                        
                        if (this.Sucursal == null)
                                Comando.Fields.AddWithValue("id_sucursal", null);
                        else
                                Comando.Fields.AddWithValue("id_sucursal", this.Sucursal.Id);
                        
                        if (this.Impresora == null)
                                Comando.Fields.AddWithValue("id_impresora", null);
                        else
                                Comando.Fields.AddWithValue("id_impresora", this.Impresora.Id);
                        Comando.Fields.AddWithValue("tipo", (int)(this.Tipo));
                        Comando.Fields.AddWithValue("tipo_fac", this.TipoFac);
                        Comando.Fields.AddWithValue("detalonario", this.UsaTalonario ? 1 : 0);
                        Comando.Fields.AddWithValue("estacion", this.Estacion);
                        Comando.Fields.AddWithValue("carga", this.CargaManual ? 1 : 0);
                        Comando.Fields.AddWithValue("modelo", (int)(this.ModeloImpresoraFiscal));
                        Comando.Fields.AddWithValue("puerto", this.Puerto);
                        Comando.Fields.AddWithValue("bps", this.Bps);

                        this.AgregarTags(Comando);

                        Connection.Execute(Comando);

                        return base.Guardar();
                }
Пример #50
0
                public void Anular()
                {
                        if (this.Existe && this.Anulado == false) {
                                this.Estado = 90;

                                // Marco el recibo como anulado
                                qGen.Update Act = new qGen.Update(this.TablaDatos);
                                Act.Fields.AddWithValue("estado", this.Estado);
                                Act.WhereClause = new qGen.Where(this.CampoId, this.Id);
                                this.Connection.Execute(Act);

                                Lbl.Sys.Config.ActionLog(this.Connection, Lbl.Sys.Log.Acciones.Delete, this, null);

                                if (this.DePago) {
                                        foreach (Pago Pg in this.Pagos) {
                                                Pg.Anular();
                                        }
                                } else {
                                        foreach (Cobro Cb in this.Cobros) {
                                                Cb.Anular();
                                        }
                                }

                                DescancelarImpagos(this.Cliente, this.Facturas, this, this.DePago ? -this.Total : this.Total);
                                this.Cliente.CuentaCorriente.Movimiento(true, this.Concepto, "Anulación de " + this.ToString(), this.DePago ? -this.Total : this.Total, this.Obs, null, this, null);
                        }
                }
Пример #51
0
                public override Lfx.Types.OperationResult Guardar()
                {
                        try {
				qGen.TableCommand Comando;
                                if (this.Existe) {
					Comando = new qGen.Update(this.Connection, this.TablaDatos);
					Comando.WhereClause = new qGen.Where(this.CampoId, this.Id);
				} else {
					Comando = new qGen.Insert(this.Connection, this.TablaDatos);
                                        Comando.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                                }

                                Comando.Fields.AddWithValue("nombre", this.Registro["nombre"].ToString());
                                Comando.Fields.AddWithValue("cuenta_stock", this.CuentaExistencias ? 1 : 0);
                                Comando.Fields.AddWithValue("deposito", this.Deposito);
                                Comando.Fields.AddWithValue("facturable", this.Facturable ? 1 : 0);
                                Comando.Fields.AddWithValue("estado", this.Estado);
                                Comando.Fields.AddWithValue("obs", this.Obs);
				
				this.AgregarTags(Comando);

	                        this.Connection.Execute(Comando);

				return new Lfx.Types.SuccessOperationResult();
                        }
                        catch (Exception ex) {
                                return new Lfx.Types.FailureOperationResult(ex.ToString());
                        }
                }
Пример #52
0
                public void End(bool reboot)
                {
                        Programador.Stop();

                        if (this.PV != 0) {
                                using (System.Data.IDbTransaction Trans = this.Impresora.DataBase.BeginTransaction()) {
                                        qGen.Update Actualizar = new qGen.Update("pvs", new qGen.Where("id_pv", this.PVenta));
                                        Actualizar.Fields.AddWithValue("lsa", null);
                                        this.Impresora.DataBase.Execute(Actualizar);
                                        Trans.Commit();
                                }
                        }

                        Impresora.Terminar();
                        FormEstado.Close();

                        if (reboot) {
                                string[] ParametrosAPasar = (string[])(this.Arguments);
                                ParametrosAPasar[0] = "";
                                string Params = string.Join(" ", ParametrosAPasar).Trim();

                                Lfx.Environment.Shell.Execute(this.ExecutableName, Params, System.Diagnostics.ProcessWindowStyle.Minimized, false);
                        }
                        System.Windows.Forms.Application.Exit();
                }
Пример #53
0
                /// <summary>
                /// Numera el comprobante (usando el número especificado), guardando automáticamente los cambios.
                /// </summary>
                /// <param name="numero">El número que se asignó a este comprobante.</param>
                /// <param name="yMarcarComoImpreso">Si es Verdadero, el comprobante se marca como impreso y se actualiza la fecha.</param>
                public void Numerar(int numero, bool yMarcarComoImpreso)
                {
                        qGen.Update ActualizarComprob = new qGen.Update(this.TablaDatos);

                        // Modifico Registro para no volver a cargar el comprobante desde la BD
                        Registro["numero"] = numero;
                        ActualizarComprob.Fields.AddWithValue("numero", numero);

                        string Nombre = this.PV.ToString("0000") + "-" + numero.ToString("00000000");
                        Registro["nombre"] = Nombre;
                        ActualizarComprob.Fields.AddWithValue("nombre", Nombre);

                        if (yMarcarComoImpreso) {
                                Registro["estado"] = 1;

                                Registro["fecha"] = this.Connection.ServerDateTime;

                                if (this.TablaDatos == "recibos") {
                                        ActualizarComprob.Fields.AddWithValue("impreso", 1);
                                        Registro["impreso"] = 1;
                                } else {
                                        ActualizarComprob.Fields.AddWithValue("impresa", 1);
                                        Registro["impresa"] = 1;
                                }
                                ActualizarComprob.Fields.AddWithValue("estado", 1);
                                ActualizarComprob.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
                        }
                        ActualizarComprob.WhereClause = new qGen.Where(this.CampoId, this.Id);

                        this.Connection.Execute(ActualizarComprob);
                }
Пример #54
0
                public void AsentarPago(bool anulacion)
                {
                        if (this.FormaDePago == null)
                                return;
                        
                        decimal ImporteMovim;
                        if(anulacion)
                                // Al cancelar, desasiento el importe pagado
                                ImporteMovim = this.ImporteCancelado;
                        else
                                // Al ingresar la factura, asiento el importe impago (que normalmente es el total)
                                ImporteMovim = this.Total;

                        if (this.FormaDePago.Tipo == Pagos.TiposFormasDePago.CuentaCorriente)
                                // Si es cuenta corriente muevo siempre el total (incluso al anular)
                                ImporteMovim = this.Total;

                        if (this.Tipo.DireccionCtaCte < 0)
                                // Este tipo de comprobantes hace créditos en cuenta corriente
                                ImporteMovim = -ImporteMovim;

                        if (this.Compra) {
                                // Es comprobante de compra, invierto la dirección del movimiento
                                ImporteMovim = -ImporteMovim;
                        }

                        if (anulacion == false) {
                                // Asiento el pago (sólo efectivo y cta. cte.)
                                // El resto de los pagos los maneja el formulario desde donde se mandó a imprimir
                                switch (this.FormaDePago.Tipo) {
                                        case Lbl.Pagos.TiposFormasDePago.Efectivo:
                                                if (this.ImporteImpago > 0) {
                                                        Lbl.Cajas.Caja CajaDiaria = new Lbl.Cajas.Caja(this.Connection, Lfx.Workspace.Master.CurrentConfig.Empresa.CajaDiaria);
                                                        CajaDiaria.Movimiento(true,
                                                                Lbl.Cajas.Concepto.IngresosPorFacturacion,
                                                                this.ToString(),
                                                                this.Cliente,
                                                                ImporteMovim,
                                                                null,
                                                                this,
                                                                null,
                                                                null);
                                                        this.CancelarImporte(this.ImporteImpago, null);
                                                }
                                                break;
                                        case Lbl.Pagos.TiposFormasDePago.CuentaCorriente:
                                                this.Cliente.CuentaCorriente.Movimiento(true,
                                                        Lbl.Cajas.Concepto.IngresosPorFacturacion,
                                                        this.ToString(),
                                                        ImporteMovim,
                                                        null,
                                                        this,
                                                        null,
                                                        null);
                                                if (this.Tipo.EsNotaCredito) {
                                                        if (this.ComprobRelacionados == null || this.ComprobRelacionados.Count == 0) {
                                                                // Si no hay comprobantes asociados, pero esta nota de crédito viene de un comprobante anteior
                                                                // asocio el comprobante original a esta nota de crédito
                                                                if (this.ComprobanteOriginal != null && this.ComprobanteOriginal.Tipo.EsFacturaOTicket) {
                                                                        this.ComprobRelacionados = new ColeccionComprobanteImporte();
                                                                        this.ComprobRelacionados.AddWithValue(this.ComprobanteOriginal, 0);
                                                                }
                                                        }
                                                        Lbl.Comprobantes.Recibo.CancelarImpagos(this.Cliente, this.ComprobRelacionados, this, this.Compra ? -this.Total : this.Total);
                                                }

                                                decimal FacturaSaldo = this.ImporteImpago;
                                                if (FacturaSaldo > 0) {
                                                        decimal SaldoCtaCteAntes = -(ImporteMovim - this.Cliente.CuentaCorriente.ObtenerSaldo(true));
                                                        // Busca un saldo en cta cte para cancelar este comprobante
                                                        if ((ImporteMovim > 0 && SaldoCtaCteAntes < 0) || (ImporteMovim < 0 && SaldoCtaCteAntes > 0)) {
                                                                decimal SaldoACancelar = ImporteMovim < 0 ? SaldoCtaCteAntes : -SaldoCtaCteAntes;

                                                                if (SaldoACancelar > FacturaSaldo)
                                                                        SaldoACancelar = FacturaSaldo;

                                                                // Cancelo la factura con un saldo a favor que tenía en cta. cte.
                                                                qGen.Update ActualizarComprob = new qGen.Update("comprob");
                                                                ActualizarComprob.Fields.AddWithValue("cancelado", new qGen.SqlExpression("cancelado+" + Lfx.Types.Formatting.FormatCurrencySql(SaldoACancelar)));
                                                                ActualizarComprob.WhereClause = new qGen.Where("id_comprob", this.Id);
                                                                this.Connection.Execute(ActualizarComprob);
                                                        }
                                                }
                                                break;
                                }
                        } else {
                                // Es una anulación, invierto la dirección del movimiento
                                ImporteMovim = -ImporteMovim;

                                switch (this.FormaDePago.Tipo) {
                                        case Lbl.Pagos.TiposFormasDePago.Efectivo:
                                                // Hago un movimiento en caja diaria
                                                Lbl.Cajas.Caja Caja = new Lbl.Cajas.Caja(Connection, Lfx.Workspace.Master.CurrentConfig.Empresa.CajaDiaria);
                                                Caja.Movimiento(true, 
                                                        Lbl.Cajas.Concepto.IngresosPorFacturacion, 
                                                        "Anulación " + this.ToString(), 
                                                        this.Cliente, 
                                                        ImporteMovim, 
                                                        null, 
                                                        this, 
                                                        null, 
                                                        null);
                                                break;

                                        case Lbl.Pagos.TiposFormasDePago.ChequePropio:
                                        case Pagos.TiposFormasDePago.ChequeTerceros:
                                                Lbl.Bancos.Cheque Cheque = new Lbl.Bancos.Cheque(Connection, this);
                                                if (Cheque != null && Cheque.Existe)
                                                        Cheque.Anular();
                                                break;

                                        case Pagos.TiposFormasDePago.Caja:
                                                throw new NotImplementedException("No implementado: anular comprobante pagado con depósito en caja.");

                                        case Lbl.Pagos.TiposFormasDePago.CuentaCorriente:
                                                // Quito el saldo pagado de la cuenta corriente
                                                this.Cliente.CuentaCorriente.Movimiento(true, Lbl.Cajas.Concepto.IngresosPorFacturacion, "Anulación " + this.ToString(), ImporteMovim, null, this, null, null);
                                                if (this.Tipo.EsNotaCredito)
                                                        Lbl.Comprobantes.Recibo.DescancelarImpagos(this.Cliente, this.ComprobRelacionados, this, this.Compra ? -this.Total : this.Total);
                                                        //this.Cliente.CuentaCorriente.CancelarComprobantesConSaldo(ImporteMovimCtaCte, false);
                                                break;

                                        case Lbl.Pagos.TiposFormasDePago.Tarjeta:
                                        case Pagos.TiposFormasDePago.OtroValor:
                                                Lbl.Pagos.Cupon Cupon = new Lbl.Pagos.Cupon(Connection, this);
                                                if (Cupon != null && Cupon.Existe)
                                                        Cupon.Anular();
                                                break;
                                }
                        }
                }
Пример #55
0
        /// <summary>
        /// Asienta un movimiento en la cuenta corriente, y cancela comprobantes asociados.
        /// </summary>
        /// <param name="auto">Indica si es un movimiento automático (generado por el sistema) o manual (generado por el usuario).</param>
        /// <param name="concepto">El concepto bajo el cual se realiza el movimiento.</param>
        /// <param name="textoConcepto">El texto que describe al concepto.</param>
        /// <param name="importeDebito">El importe a debitar de la cuenta. Un importe negativo indica un crédito.</param>
        /// <param name="obs">Observaciones.</param>
        /// <param name="comprob">El comprobante asociado a este movimiento.</param>
        /// <param name="recibo">El recibo asociado a este movimiento.</param>
        /// <param name="textoComprob">Un texto sobre los comprobantes asociados al sistema.</param>
        /// <param name="extras">Colección de campos adicionales para el registro.</param>
        public void Movimiento(bool auto,
                               Lbl.Cajas.Concepto concepto,
                               string textoConcepto,
                               decimal importeDebito,
                               string obs,
                               Lbl.Comprobantes.ComprobanteConArticulos comprob,
                               Lbl.Comprobantes.Recibo recibo,
                               string textoComprob,
                               Dictionary <string, object> extras)
        {
            decimal SaldoActual = this.ObtenerSaldo(true);
            decimal NuevoSaldo  = SaldoActual + importeDebito;

            qGen.Insert ComandoInsertarMovimiento = new qGen.Insert(this.Connection, this.TablaDatos);

            ComandoInsertarMovimiento.Fields.AddWithValue("auto", auto ? (int)1 : (int)0);
            if (concepto == null)
            {
                ComandoInsertarMovimiento.Fields.AddWithValue("id_concepto", null);
            }
            else
            {
                ComandoInsertarMovimiento.Fields.AddWithValue("id_concepto", concepto.Id);
            }
            ComandoInsertarMovimiento.Fields.AddWithValue("concepto", textoConcepto);
            ComandoInsertarMovimiento.Fields.AddWithValue("id_cliente", this.Persona.Id);
            ComandoInsertarMovimiento.Fields.AddWithValue("fecha", qGen.SqlFunctions.Now);
            ComandoInsertarMovimiento.Fields.AddWithValue("importe", importeDebito);
            if (comprob == null)
            {
                ComandoInsertarMovimiento.Fields.AddWithValue("id_comprob", null);
            }
            else
            {
                ComandoInsertarMovimiento.Fields.AddWithValue("id_comprob", comprob.Id);
            }
            if (recibo == null)
            {
                ComandoInsertarMovimiento.Fields.AddWithValue("id_recibo", null);
            }
            else
            {
                ComandoInsertarMovimiento.Fields.AddWithValue("id_recibo", recibo.Id);
            }
            ComandoInsertarMovimiento.Fields.AddWithValue("comprob", textoComprob);
            ComandoInsertarMovimiento.Fields.AddWithValue("saldo", NuevoSaldo);
            ComandoInsertarMovimiento.Fields.AddWithValue("obs", obs);

            if (extras != null && extras.Count > 0)
            {
                foreach (KeyValuePair <string, object> extra in extras)
                {
                    ComandoInsertarMovimiento.Fields.AddWithValue(extra.Key, extra.Value);
                }
            }
            this.Connection.Execute(ComandoInsertarMovimiento);

            qGen.Update ComandoActualizarCliente = new qGen.Update("personas");
            ComandoActualizarCliente.Fields.AddWithValue("saldo_ctacte", NuevoSaldo);
            ComandoActualizarCliente.WhereClause = new qGen.Where("id_persona", this.Persona.Id);
            this.Connection.Execute(ComandoActualizarCliente);
        }
Пример #56
0
                public Lfx.Types.OperationResult CancelarImporte(decimal importe, Lbl.Comprobantes.Comprobante comprob)
		{
			if(this.ImporteCancelado + importe > this.Total)
                                throw new Lfx.Types.DomainException("ComprobanteConArticulos.CancelarImporte: El importe a cancelar no puede ser mayor que el saldo impago");
			this.ImporteCancelado += importe;
			qGen.Update Actualizar = new qGen.Update("comprob", new qGen.Where("id_comprob", this.Id));
			Actualizar.Fields.AddWithValue("cancelado", this.ImporteCancelado);
			this.Connection.Execute(Actualizar);

                        if (comprob is Lbl.Comprobantes.Recibo) {
                                qGen.Insert AsentarComprobantesDeEsteRecibo = new qGen.Insert("recibos_comprob");
                                AsentarComprobantesDeEsteRecibo.Fields.AddWithValue("id_comprob", this.Id);
                                AsentarComprobantesDeEsteRecibo.Fields.AddWithValue("id_recibo", comprob.Id);
                                AsentarComprobantesDeEsteRecibo.Fields.AddWithValue("importe", importe);
                                this.Connection.Execute(AsentarComprobantesDeEsteRecibo);
                        } else if (comprob is Lbl.Comprobantes.ComprobanteConArticulos) {
                                Lbl.Comprobantes.ComprobanteConArticulos factura = comprob as Lbl.Comprobantes.ComprobanteConArticulos;
                                qGen.Insert AsentarComprobantesDeEsteRecibo = new qGen.Insert("comprob_comprob");
                                AsentarComprobantesDeEsteRecibo.Fields.AddWithValue("id_comprob", factura.Id);
                                AsentarComprobantesDeEsteRecibo.Fields.AddWithValue("id_comprob_rel", this.Id);
                                AsentarComprobantesDeEsteRecibo.Fields.AddWithValue("importe", importe);
                                this.Connection.Execute(AsentarComprobantesDeEsteRecibo);
                        }
			return new Lfx.Types.SuccessOperationResult();
		}
Пример #57
0
        public override Lfx.Types.OperationResult Guardar()
        {
            qGen.IStatement Comando;

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

            if (this.Numero > 0)
            {
                Comando.ColumnValues.AddWithValue("id_sucursal", this.Numero);
                this.m_ItemId = this.Numero;
            }

            Comando.ColumnValues.AddWithValue("nombre", this.Nombre);
            Comando.ColumnValues.AddWithValue("direccion", this.Direccion);
            Comando.ColumnValues.AddWithValue("telefono", this.Telefono);

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

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

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

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

            this.AgregarTags(Comando);

            this.Connection.ExecuteNonQuery(Comando);

            return(base.Guardar());
        }
Пример #58
0
                public Lfx.Types.OperationResult DescancelarImporte(decimal importe, Lbl.Comprobantes.Comprobante comprob)
                {
                        if (importe > this.ImporteCancelado)
                                throw new Lfx.Types.DomainException("ComprobanteConArticulos.CancelarImporte: El importe a cancelar no puede ser mayor que el saldo impago");
                        this.ImporteCancelado -= importe;
                        qGen.Update Actualizar = new qGen.Update("comprob", new qGen.Where("id_comprob", this.Id));
                        Actualizar.Fields.AddWithValue("cancelado", this.ImporteCancelado);
                        this.Connection.Execute(Actualizar);

                        // Debería eliminar la asociación entre este comprobante y el recibo (o NC) que lo canceló orignalmente?
                        return new Lfx.Types.SuccessOperationResult();
                }
Пример #59
0
                public void Anular(bool anularPagos)
                {
                        if (this.Anulado)
                                return;

                        // Marco la factura como anulada
                        qGen.Update Act = new qGen.Update(this.TablaDatos);
                        Act.Fields.AddWithValue("anulada", 1);
                        Act.WhereClause = new qGen.Where(this.CampoId, this.Id);
                        this.Connection.Execute(Act);

                        if (anularPagos)
                                // Anulos los pagos y descancelo los comprobantes
                                this.AsentarPago(true);

                        if (this.Tipo.MueveExistencias != 0)
                                // Vuelvo el stock a su posición original
                                this.MoverExistencias(true);

                        Lbl.Sys.Config.ActionLog(this.Connection, Lbl.Sys.Log.Acciones.DeleteAndRevert, this, null);
                }
Пример #60
0
                /// <summary>
                /// Recalcula completamente el saldo de la cuenta corriente, para corregir errores de transporte. Principalmente de uso interno
                /// durante verificaciones de consistencia o al desduplicar cuentas.
                /// </summary>
                public void Recalcular()
                {
                        Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Recalculando", "Se va a recalcular el saldo de la cuenta corriente de " + this.Persona.ToString());
                        Progreso.Modal = false;
                        Progreso.Begin();

                        System.Data.DataTable Movims = this.Connection.Select("SELECT id_movim, importe FROM ctacte WHERE id_cliente=" + this.Persona.Id.ToString() + " ORDER BY " + this.CampoId);
                        decimal Saldo = 0;
                        Progreso.Max = Movims.Rows.Count;
                        foreach (System.Data.DataRow Movim in Movims.Rows) {
                                Saldo += System.Convert.ToDecimal(Movim["importe"]);
                                
                                qGen.Update ComandoActualizarSaldo = new qGen.Update(this.TablaDatos);
                                ComandoActualizarSaldo.Fields.AddWithValue("saldo", Saldo);
                                ComandoActualizarSaldo.WhereClause = new qGen.Where(this.CampoId, System.Convert.ToInt32(Movim[this.CampoId]));
                                this.Connection.Execute(ComandoActualizarSaldo);

                                Progreso.Advance(1);
                        }

                        qGen.Update ComandoActualizarCliente = new qGen.Update("personas");
                        ComandoActualizarCliente.Fields.AddWithValue("saldo_ctacte", Saldo);
                        ComandoActualizarCliente.WhereClause = new qGen.Where("id_persona", this.Persona.Id);
                        this.Connection.Execute(ComandoActualizarCliente);
                        Progreso.End();
                }