예제 #1
0
        public void FacturaAgregarProductoYConfirmarQueEsteAgregado()
        {
            Factura factura = new Factura();
            Producto producto = new Producto(10);
            factura.AddProducto(producto, 2);

            Assert.IsTrue(factura.Items.Any(i => i.Producto == producto));
        }
예제 #2
0
        public void FacturaConDosProductGetTotal()
        {
            Factura factura = new Factura();
            Producto producto1 = new Producto(10);
            Producto producto2 = new Producto(20);
            factura.AddProducto(producto1, 2);
            factura.AddProducto(producto2, 1);

            Assert.AreEqual(40, factura.GetTotal());
        }
예제 #3
0
        public void RecordOperationInDataBase(String nombreEmpresa,
                              String razonSocial,
                              String sucursal,
                              String direccion,
                              String rubro,
                              String telefono,
                              String departamento,
                              String nit,
                              String facturaNro,
                              String autorizacionNro,
                              String fecha,
                              String clienteNombre,
                              String clienteNit,
                              Factura factura,
                              String literal,
                              String codigoControl,
                              String fechalimite,
                              double montoTotal)
        {
            String datosEmp = formatElem("DatosEmpresa",
                              formatElem("Nombre", nombreEmpresa) +
                              formatElem("RazonSocial", razonSocial) +
                              formatElem("Sucursal", sucursal) +
                              formatElem("Direccion", direccion) +
                              formatElem("Rubro", rubro) +
                              formatElem("Telefono", telefono) +
                              formatElem("Departamento", departamento));

            String datosFacturacion = formatElem("DatosFacturacion",
                                      formatElem("Nit", nit) +
                                      formatElem("FacturaNro", facturaNro) +
                                      formatElem("AutorizacionNro", autorizacionNro) +
                                      formatElem("LimiteEmision", fechalimite));

            String datosFactura = formatElem("DatosFactura",
                formatElem("Fecha", fecha) +
                formatElem("Cliente", clienteNombre) +
                formatElem("ClienteNit", clienteNit) +
                formatElem("FacturaDetalle", factura.toXmlString()) +
                formatElem( "Total" , montoTotal.ToString( ) ) +
                formatElem("TotalLiteral", literal) +
                formatElem("CodigoControl", codigoControl));

            String facturaXml = formatElem("Factura", datosEmp + datosFacturacion + datosFactura);

            String sql = "insert into Factura (FacturaAutorizacion,FacturaNro,FacturaContenido,FacturaCodigoControl,FacturaAnulada,FechaTransaccion,MontoTotal)" +
                " values ('" + autorizacionNro + "','" + facturaNro + "','" + facturaXml + "','" + codigoControl + "','0','" + fecha + "','" + montoTotal + "')";
            CommonUtils.ConexionBD.Actualizar(sql);
            
        }
예제 #4
0
        public ActionResult AddReserva(AddReservaModel model)
        {
            Singleton DB = Singleton.GetInstance();
            if (DB.GetReservaById(model.Reserva.ID) != null)
            {
                return RedirectToAction("List");
            }
            else
            {
                if (model.Reserva.Desde == null || model.Reserva.Desde.Date < DateTime.Now.Date)
                {
                    ModelState.AddModelError(string.Empty, "La fecha de inicio debe ser a lo sumo hoy");
                }
                else
                {
                    if (model.Reserva.Hasta == null || model.Reserva.Hasta.Date < DateTime.Now.Date || model.Reserva.Hasta.Date < model.Reserva.Desde.Date)
                    {
                        ModelState.AddModelError(string.Empty, "La fecha de fin debe ser posterior a la de inicio");
                    }
                    else
                    {
                        if (DB.SalaDisponible(model.Reserva.Sala.ID, model.Reserva.Desde, model.Reserva.Hasta))
                        {
                            Reserva reserva = model.Reserva;
                            reserva.Sala = DB.GetSala(model.Reserva.Sala.ID);
                            reserva.Cliente = (Cliente)Session["user"];
                            reserva.ID = reserva.Cliente.ID + reserva.Sala.ID + reserva.Desde.Day + reserva.Desde.Month + reserva.Desde.Year;
                            DB.NewReserva(reserva);
                            List<Reserva> lstReserva = DB.LoadReserva(reserva.Cliente.ID);

                            Factura factura = new Factura(false)
                            {
                                Cliente = (Cliente)Session["user"],
                                Reserva = reserva,
                                EsPorReserva = true,
                                TotalAPagar = reserva.CalcularTotal(),
                                IVA = reserva.CalcularImpuestos()
                            };
                            return View("MostrarFactura", factura);
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "La sala ya se encuentra reservada para esa fecha");
                        }
                    }
                }
            }
            model.Reserva.Sala = DB.GetSala(model.Reserva.Sala.ID);
            return View("AddReserva", model);
        }
 /// <summary>
 /// Registra una factura en el sistema.
 /// </summary>
 /// <param name="factura">Informacion de la factura.</param>
 /// <returns>Numero de la factura.</returns>
 int IFacturasRepository.Add(Factura factura)
 {
     return ExecuteReaderSingle(StoredProcedureNames.AddFactura,
         values => Convert.ToInt32(values[0]),
         factura.Fecha,
         factura.DniCliente,
         factura.DniEmpleado,
         factura.SucursalId,
         factura.FormaPagoId,
         factura.Cuotas,
         factura.Subtotal,
         factura.Descuento,
         factura.Total);
 }
예제 #6
0
 public void RaiseWhenProductoRepetido()
 {
     try
     {
         Factura factura = new Factura();
         Producto producto = new Producto(10);
         factura.AddProducto(producto, 2);
         factura.AddProducto(producto, 1);
         Assert.Fail();
     }
     catch (Exception ex)
     {
         Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
         Assert.AreEqual("Producto Repetido", ex.Message);
     }
 }
        private void btnAccept_Click(object sender, EventArgs e)
        {
            Try.It(() =>
            {
                if (ucConsultaClientes.Cliente == null)
                    throw new BusinessException(MessageProviderExtensions.EntityRequired(MessageProvider.Cliente));

                if (dgvSelectedProductos.Rows.Count == 0)
                    throw new BusinessException(MessageProvider.FacturaWithoutProductos);

                var factura = new Factura
                {
                    Subtotal = GetSubtotal(),
                    Descuento = (double)numDescuento.Value / 100,
                    Total = GetTotal(),
                    Cuotas = radCuotas.Checked ? (int)numCuotas.Value : 1,
                    DniCliente = ucConsultaClientes.Cliente.Dni,
                    DniEmpleado = ((Main)MdiParent).Usuario.DniEmpleado,
                    SucursalId = (int)cboSucursal.SelectedValue
                };

                var productos = (from row in ((DataTable)dgvSelectedProductos.DataSource).Rows.Cast<DataRow>()
                                 select new FacturaProducto
                                 {
                                     ProductoId = (int)row[0],
                                     Cantidad = (int)row[1],
                                     PrecioUnitario = (double)row[4]
                                 }).ToArray();

                var client = Proxy.It<IFacturaService>();
                int nro = client.Proxy.Add(factura, productos);

                MsgBox.ShowMessage(MessageProviderExtensions.RegisteredFacturaNumber(nro));
                Close();
            });
        }
예제 #8
0
    protected void btnGuardar_Click(object sender, EventArgs e)
    {
        Factura f = new Factura();
        Reparacion r = new Reparacion();

        f.numeroFactura = GestorFacturas.ObtenerNumeroMaximo() + 1;
        f.fechaFactura = DateTime.Now;

        int idReparacion = (int)ViewState["idReparacion"];

        //if (ViewState["reparacion"] != null) r = (Reparacion)ViewState["reparacion"];
        r.idReparacion = idReparacion;
        f.reparacion = r;

        f.total = (decimal)ViewState["totalFactura"];

        List<DetalleFactura> listaDetalles;
        if (ViewState["detallesFactura"] == null) ViewState["detallesFactura"] = new List<DetalleFactura>();
        listaDetalles = (List<DetalleFactura>)ViewState["detallesFactura"];

        GestorFacturas.InsertarFactura(f, listaDetalles);
        alertaExito.Visible = true;
        Inicio();
    }
예제 #9
0
        private void button2_Click(object sender, EventArgs e)
        {
            int amb = comboBox1.SelectedIndex;



            switch (amb)
            {
            case 0:
                ambiente = "https://demointws.thefactoryhka.com.ec/Service.svc";
                break;

            case 1:
                ambiente = "http://testintws.thefactoryhka.com.ec/Service.svc";
                break;
            }



            try
            {
                serviceobj.Service servicio = new serviceobj.Service(); //CREAMOS SERVICIO
                servicio.Url = ambiente;
                PeticionFactura pet      = new PeticionFactura();       //Creamos una peticion
                Factura         fact     = new Factura();
                InfoTributaria  infotrib = new InfoTributaria();

                fact.InfoTributaria = infotrib;
                pet.Documento       = fact;
                fact.InfoTributaria.NombreComercial = "ECUAGOCH";
                fact.InfoTributaria.AgenteRetencion = "SI";
                fact.InfoTributaria.RazonSocial     = "ECUAGOCH";
                fact.InfoTributaria.Ruc             = "1700000000001";
                fact.InfoTributaria.CodigoNumerico  = "01";
                fact.InfoTributaria.Estab           = "001";
                fact.InfoTributaria.PtoEmi          = "001";
                fact.InfoTributaria.Secuencial      = "000000222";
                fact.InfoTributaria.DirMatriz       = "En un lugar de la mancha...";

                InfoFactura infoFactura = new InfoFactura();
                fact.InfoFactura                  = infoFactura;
                infoFactura.FechaEmision          = "01/01/2000";
                infoFactura.DirEstablecimiento    = "dirEstablecimiento0";
                infoFactura.ContribuyenteEspecial = "Contribuyente especial";
                infoFactura.ObligadoContabilidad  = "SI";


//************************CREAMOS OTROS RUBREOS TERCEROS*****************************
                Rubro rubro = new Rubro();   // se deben instanciar
                fact.OtrosRubrosTerceros = new List <Rubro>().ToArray();
                rubro.Total = "total1";

                for (int i = 0; i < 3; i++)
                {
                    rubro.Concepto = "concepto" + i.ToString();
                    fact.OtrosRubrosTerceros.ToList().Add(rubro);
                }


                InfoCompRetencion        inforet = new InfoCompRetencion();
                ImpuestoDetalleRetencion imp     = new ImpuestoDetalleRetencion();

                //**********************************INFOADICIONAL**************************************

                infoAdicional info1 = new infoAdicional();
                infoAdicional info2 = new infoAdicional();
                info1.Nombre = "Inofrmacion";
                info1.Valor  = "1234567";
                info2        = info1;

                fact.CampoAdicional = new List <infoAdicional>().ToArray();
                fact.CampoAdicional.ToList().Add(info1);
                fact.CampoAdicional.ToList().Add(info2);


                //*****************************DETALLES***********************************************

                Detalle detalle1 = new Detalle();
                Detalle detalle2 = new Detalle();
                detalle1.CodigoPrincipal        = "Detalle detalle1 = new Detalle()";
                detalle1.CodigoAuxiliar         = "codigo auxiliar";
                detalle1.Descripcion            = "descriplkugyjf";
                detalle1.UnidadMedida           = "UND";
                detalle1.Cantidad               = "1";
                detalle1.PrecioUnitario         = "10.00";
                detalle1.PrecioSinSubsidio      = "0.00";
                detalle1.Descuento              = "0.00";
                detalle1.PrecioTotalSinImpuesto = "10.00";
                detalle2 = detalle1;
                detalle1.DetAdicional = new List <DetAdicional>().ToArray();
                var detAd1 = new DetAdicional();
                var detAd2 = new DetAdicional();
                fact.Detalles = new List <Detalle>().ToArray();
                fact.Detalles.ToList().Add(detalle1);
                fact.Detalles.ToList().Add(detalle2);


//***********************************PAGOS*********************************
                Pago pago = new Pago();
                pago.FormaPago    = "01";
                pago.Total        = "50.00";
                pago.Plazo        = "3";
                pago.UnidadTiempo = "Dias";

                fact.InfoFactura.Pagos = new List <Pago>().ToArray();
                fact.InfoFactura.Pagos.ToList().Add(pago);
                fact.InfoFactura.Pagos.ToList().Add(pago);



//*****************************TOTAL CON IMPUESTOS**********************


                TotalConImpuesto totalConImpuesto = new TotalConImpuesto();
                totalConImpuesto.BaseImponible      = "100.00";
                totalConImpuesto.Codigo             = "01";
                totalConImpuesto.CodigoPorcentaje   = "02";
                totalConImpuesto.DescuentoAdicional = "0.00";
                totalConImpuesto.Tarifa             = "0.00";
                totalConImpuesto.Valor = "100.00";

                fact.InfoFactura.TotalConImpuestos = new List <TotalConImpuesto>().ToArray();
                fact.InfoFactura.TotalConImpuestos.ToList().Add(totalConImpuesto);



                //**********************************MAQUINAL FSICAL*******************
                maquinaFiscal maquina = new maquinaFiscal();

                maquina.marca  = "marcaaaaaa";
                maquina.modelo = "modelazo";
                maquina.serie  = "ASDFGHJ1234";

                fact.Maquinafiscal = new maquinaFiscal();
                fact.Maquinafiscal = maquina;



//**********************************ENVIO PETICION***************************
                pet.Clave   = "12345";
                pet.RUC     = "17999888222";
                pet.Usuario = "usuario1";
                var resp = servicio.EnviarFactura(pet);


                MessageBox.Show(resp.Mensaje + "--" + resp.Codigo + "--" + "\r\n" + resp.Archivo);
            }


            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
예제 #10
0
 public int save(Factura factura)
 {
     return(_facturaRepository.save(factura));
 }
예제 #11
0
 private void btnGuardar_Click(object sender, EventArgs e)
 {
     if (validarStock() == true)
     {
         if (txtNitCliente.Text != "" && txtNombreCliente.Text != "" && tblDetalleVenta.RowCount > 0)
         {
             string nroFact = getNroFactura().ToString();
             int    idCliente;
             if (objCliente == null)
             {
                 int idPersona = PersonaBLL.InsertDatosPersona(txtNitCliente.Text, txtNombreCliente.Text, "", "", "", "", 1);
                 idCliente = ClienteBLL.InsertDatosCliente(idPersona, 1);
             }
             else
             {
                 idCliente = objCliente.pkCliente;
             }
             int idFactura = 0;
             if (llave != null && llave.txtLlave != "")
             {
                 idFactura = FacturaBLL.InsertarFactura(0, idCliente, 2, Convert.ToInt32(boxDescuentos.SelectedValue), 1, nroFact, llave.txtNroAutorizacion, llave.txtLlave, Convert.ToDecimal(sumarTotalVenta()), 1);
             }
             else
             {
                 MessageBox.Show("USTED NO HA INGRESADO LA LLAVE NI EL CODIGO DE AUTORIZACIÓN DE LA FACTURA");
                 return;
             }
             foreach (DataGridViewRow fila in tblDetalleVenta.Rows)
             {
                 if (Convert.ToInt32(fila.Cells["txtCantidad"].Value.ToString()) > 0)
                 {
                     if (fila.Cells["idProducto"] != null)
                     {
                         GananciasDTO ganancias = new GananciasDTO();
                         ganancias.fkProducto  = Convert.ToInt32(fila.Cells["idProducto"].Value.ToString());
                         ganancias.intCantidad = Convert.ToInt32(fila.Cells["txtCantidad"].Value.ToString());
                         Producto pro = ProductoBLL.GetProductById(ganancias.fkProducto);
                         ganancias.decValorVenta  = pro.decValorVenta;
                         ganancias.decValorCompra = pro.decValorCompra;
                         ganancias.decTotal       = Convert.ToDecimal(fila.Cells["txtSubTotal"].Value.ToString());
                         DetalleVentaBLL.InsertarDetalleVenta(0, Convert.ToInt32(fila.Cells["idProducto"].Value.ToString()), idFactura, Convert.ToInt32(fila.Cells["txtCantidad"].Value.ToString()), Convert.ToDecimal(fila.Cells["txtSubTotal"].Value.ToString()));
                         GananciasBLL.InsertObjetoGanancias(ganancias);
                         Producto auxProducto = getProductoOfList(fila.Cells["idProducto"].Value.ToString());
                         auxProducto.intCantidad -= Convert.ToInt32(fila.Cells["txtCantidad"].Value.ToString());
                         ProductoBLL.UpdateProducto(auxProducto);
                         sumaReal       += (double)auxProducto.decValorVenta * Convert.ToInt32(fila.Cells["txtCantidad"].Value.ToString());
                         sumaDescuentos += Convert.ToDouble(fila.Cells["txtSubTotal"].Value.ToString());
                     }
                 }
                 else
                 {
                     MessageBox.Show("Usted a ingresado una cantidad de 0");
                     return;
                 }
             }
             if (lastLibroVenta != null)
             {
                 if (lastLibroVenta.txtMes == DateTime.Now.Month.ToString() && lastLibroVenta.txtAño == DateTime.Now.Year.ToString())
                 {
                     List <DetalleLibroVentas> lista = DetalleLibroVentasBLL.GetDetalleLibroVentasByIdLibro(lastLibroVenta.pkLibro);
                     int lastNro = 0;
                     if (lista.Count != 0)
                     {
                         lastNro = lista[(lista.Count - 1)].intNro;
                     }
                     if (sumaReal == sumaDescuentos)
                     {
                         sumaDescuentos = 0;
                     }
                     double dif = sumaReal - sumaDescuentos;
                     double db  = 0;
                     if (dif == sumaReal)
                     {
                         db = sumaReal * 13 / 100;
                     }
                     else
                     {
                         db = (sumaReal - dif) * 13 / 100;
                     }
                     DetalleLibroVentasBLL.InsertDatosDetalleLibroVentas(lastNro + 1, DateTime.Now, nroFact, llave.txtNroAutorizacion, txtNitCliente.Text, txtNombreCliente.Text, Convert.ToDecimal(sumaReal), 0, 0, 0, Convert.ToDecimal(sumaReal), (dif == sumaReal) ? 0 : Convert.ToDecimal(dif), (dif == sumaReal) ? Convert.ToDecimal(sumaReal) : Convert.ToDecimal(sumaReal - dif), Convert.ToDecimal(db), getCodigoControl(), lastLibroVenta.pkLibro, 1);
                 }
                 else
                 {
                     int pkLibro = LibroVentasBLL.InsertDatosLibroVentas(DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString());
                     int lastNro = 0;
                     if (sumaReal == sumaDescuentos)
                     {
                         sumaDescuentos = 0;
                     }
                     double dif = sumaReal - sumaDescuentos;
                     double db  = 0;
                     if (dif == sumaReal)
                     {
                         db = sumaReal * 13 / 100;
                     }
                     else
                     {
                         db = (sumaReal - dif) * 13 / 100;
                     }
                     DetalleLibroVentasBLL.InsertDatosDetalleLibroVentas(lastNro + 1, DateTime.Now, nroFact, llave.txtNroAutorizacion, txtNitCliente.Text, txtNombreCliente.Text, Convert.ToDecimal(sumaReal), 0, 0, 0, Convert.ToDecimal(sumaReal), (dif == sumaReal) ? 0 : Convert.ToDecimal(dif), (dif == sumaReal) ? Convert.ToDecimal(sumaReal) : Convert.ToDecimal(sumaReal - dif), Convert.ToDecimal(db), getCodigoControl(), pkLibro, 1);
                 }
             }
             else
             {
                 int pkLibro = LibroVentasBLL.InsertDatosLibroVentas(DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString());
                 int lastNro = 0;
                 if (sumaReal == sumaDescuentos)
                 {
                     sumaDescuentos = 0;
                 }
                 double dif = sumaReal - sumaDescuentos;
                 double db  = 0;
                 if (dif == sumaReal)
                 {
                     db = sumaReal * 13 / 100;
                 }
                 else
                 {
                     db = (sumaReal - dif) * 13 / 100;
                 }
                 DetalleLibroVentasBLL.InsertDatosDetalleLibroVentas(lastNro + 1, DateTime.Now, nroFact, llave.txtNroAutorizacion, txtNitCliente.Text, txtNombreCliente.Text, Convert.ToDecimal(sumaReal), 0, 0, 0, Convert.ToDecimal(sumaReal), (dif == sumaReal) ? 0 : Convert.ToDecimal(dif), (dif == sumaReal) ? Convert.ToDecimal(sumaReal) : Convert.ToDecimal(sumaReal - dif), Convert.ToDecimal(db), getCodigoControl(), pkLibro, 1);
             }
             if (original == " COPIA")
             {
                 original = "ORIGINAL";
             }
             imprimirFactura();
             original = " COPIA";
             imprimirFactura();
             tblDetalleVenta.RowCount = 0;
             txtNitCliente.Text       = "";
             txtNombreCliente.Text    = "";
             sumaReal       = 0;
             sumaDescuentos = 0;
             lastFactura    = FacturaBLL.GetLastFactura();
             llave          = LlaveFacturaBLL.GetLastLlaveFactura();
             lastFactura    = FacturaBLL.GetLastFactura();
             lastLibroVenta = LibroVentasBLL.GetLastLibroVentas();
             listaProductos = new List <Producto>();
         }
         else
         {
             MessageBox.Show("Debe ingresar el nit, el nombre del cliente y al menos un producto");
         }
     }
 }
    protected void GenerarXMLFile_Button_Click(object sender, EventArgs e)
    {
        if (PeriodoSeleccion_TextBox.Text == "")
        {
            ErrMessage_Span.InnerHtml = "Ud. debe indicar un período de selección válido. <br /><br />" +
                                        "El período de selección que Ud. indique debe tener la forma 'aaaamm'; por ejemplo: 200901.";
            ErrMessage_Span.Style["display"] = "block";

            return;
        }

        if (PeriodoSeleccion_TextBox.Text.ToString().Length != 6)
        {
            ErrMessage_Span.InnerHtml = "Ud. debe indicar un período de selección válido. <br /><br />" +
                                        "El período de selección que Ud. indique debe tener la forma 'aaaamm'; por ejemplo: 200901.";
            ErrMessage_Span.Style["display"] = "block";

            return;
        }

        int nPeriodoSeleccion = 0;

        if (!int.TryParse(PeriodoSeleccion_TextBox.Text, out nPeriodoSeleccion))
        {
            ErrMessage_Span.InnerHtml = "Ud. debe indicar un período de selección válido. <br /><br />" +
                                        "El período de selección que Ud. indique debe tener la forma 'aaaamm'; por ejemplo: 200901.";
            ErrMessage_Span.Style["display"] = "block";

            return;
        }

        // si el combo no tiene registro seleccionado es porque no hay registros en la tabla
        if (CiaContab_DropDownList.SelectedIndex == -1)
        {
            ErrMessage_Span.InnerHtml = "No existe información para construir el archivo que Ud. ha requerido. <br /><br />" +
                                        "Probablemente Ud. no ha aplicado un filtro y seleccionado información aún.";
            ErrMessage_Span.Style["display"] = "block";

            return;
        }

        BancosEntities dbBancos = new BancosEntities();

        int ciaContab = Convert.ToInt32(CiaContab_DropDownList.SelectedValue);

        var Facturas = (from f in dbBancos.tTempWebReport_ConsultaFacturas
                        join c in dbBancos.Companias
                        on f.CiaContab equals c.Numero
                        where f.NombreUsuario == User.Identity.Name &&
                        f.CiaContab == ciaContab
                        select new
        {
            RifAgente = c.Rif,
            NombreCiaContab = c.NombreCorto,
            c.Abreviatura
        }).ToList();

        if (Facturas.Count == 0)
        {
            ErrMessage_Span.InnerHtml = "No existe información para construir el archivo que Ud. ha requerido. <br /><br /> " +
                                        "Probablemente Ud. no ha aplicado un filtro y seleccionado información aún.";
            ErrMessage_Span.Style["display"] = "block";

            dbBancos = null;
            return;
        }

        string sNombreCiaContab = Facturas[0].Abreviatura;
        string sRifCiaContab    = Facturas[0].RifAgente.ToString().Replace("-", "");

        int cantidadFacturas    = 0;
        int cantidadRetenciones = 0;

        Facturas = null;

        // nótese como seleccionamos solo los registros que corresponden a la cia contab seleccinada;
        // además, solo los que corresponden al usuario
        XDocument xmldoc = new XDocument(
            new XElement("RelacionRetencionesISLR",
                         new XAttribute("RifAgente", sRifCiaContab),
                         new XAttribute("Periodo", nPeriodoSeleccion.ToString())));

        xmldoc.Declaration = new XDeclaration("1.0", "ISO-8859-1", "true");



        var facturasQuery = from f in dbBancos.tTempWebReport_ConsultaFacturas
                            where f.NombreUsuario == User.Identity.Name &&
                            f.CiaContab == ciaContab
                            select f;

        foreach (var f in facturasQuery)
        {
            // nótese lo que hacemos aquí: si el Iva comienza con J (persona jurídica) grabamos el
            // monto sujeto a retención al archivo; si el rif comienza con otra letra (persona NO juridica)
            // grabamos el monto total de la factura (ie: imponible más no imponible)

            // dejamos de aplicar el criterio que sigue pues ahora los empleados vienen siempre desde la
            // nómina con el sueldo que registre el usuario como monto sujeto a retención para el xml file

            if (f.RifCompania == null)
            {
                ErrMessage_Span.InnerHtml = "Aparentemente, la compañía " + f.NombreCompania +
                                            " no tiene un número de rif definido en la Maestra de Proveedores. <br /><br />" +
                                            "Por favor revise esta situación; asigne un número de Rif a esta compañía y regrese a ejecutar nuevamente este proceso.";
                ErrMessage_Span.Style["display"] = "block";

                dbBancos = null;
                return;
            }

            // ----------------------------------------------------------------------------------------------------------------------------------------------
            // ahora los impuestos y las retenciones se registran en forma separada en la tabla Facturas_Impuestos; el objetivo principal de este cambio fue,
            // simplemente, poder registrar *más de una* retención de impuestos para una factura. Aunque no es un caso frecuente, existen proveedores que
            // hacen facturas en las cuales especifican dos retenciones (islr) diferentes ... ellos ya las indican, para que el cliente sepa que debe hacerlo
            // así ... por esa razón, ahora buscamos, para cada factura, la retención islr en la tabla Facturas_Impuestos; como dijimos antes, aunque no es
            // frecuente, puede haber más de una retención islr para una misma factura ...

            Factura factura = dbBancos.Facturas.Include("Facturas_Impuestos").
                              Include("Facturas_Impuestos.ImpuestosRetencionesDefinicion").
                              Where(x => x.ClaveUnica == f.ClaveUnicaFactura).
                              FirstOrDefault();

            if (factura == null)
            {
                continue;
            }

            foreach (Facturas_Impuestos retencion in factura.Facturas_Impuestos.Where(r => r.ImpuestosRetencionesDefinicion.Predefinido == 3))
            {
                // la factura debe tener un código de retención en el registro de ImpuestosRetenciones ...
                string codigoConceptoRetencion_islr = retencion.Codigo;

                if (string.IsNullOrEmpty(codigoConceptoRetencion_islr))
                {
                    ErrMessage_Span.InnerHtml = "Aparentemente, la compañía " + f.NombreCompania + " no tiene un 'código de concepto de retención de Islr' " +
                                                "en una (o varias) de sus facturas asociadas (ej: " + factura.NumeroFactura + "). " +
                                                "<br /><br /> Por favor revise esta situación; asigne un " +
                                                "'código de concepto de retención de Islr' a cada una de las facturas asociadas a esta compañía; " +
                                                "luego regrese y ejecute nuevamente este proceso.";
                    ErrMessage_Span.Style["display"] = "block";

                    dbBancos = null;
                    return;
                }

                // ------------------------------------------------------------------------------------------
                // número control - intentamos quitar caracteres especiales y dejar solo números ...
                string sNumeroControlDefinitivo = factura.NumeroControl;

                if (string.IsNullOrEmpty(sNumeroControlDefinitivo))
                {
                    sNumeroControlDefinitivo = "0";
                }

                Int64 numeroControl = 0;

                if (this.retencionISLR_NumeroControl_ConvertirNumeros_CheckBox.Checked)
                {
                    if (!Int64.TryParse(sNumeroControlDefinitivo, out numeroControl))
                    {
                        // excelente como quitamos letras y caracteres especiales del string (tomado de algún lado en la Web) ...
                        sNumeroControlDefinitivo = new String(sNumeroControlDefinitivo.Where(c => char.IsDigit(c)).ToArray());
                    }
                    else
                    {
                        sNumeroControlDefinitivo = factura.NumeroControl;
                    }
                }
                ;
                // ------------------------------------------------------------------------------------------

                decimal montoOperacion = retencion.MontoBase != null ? retencion.MontoBase.Value : 0;
                decimal porcentaje     = retencion.Porcentaje != null ? retencion.Porcentaje.Value : 0;

                montoOperacion = decimal.Round(montoOperacion, 2, MidpointRounding.AwayFromZero);
                porcentaje     = decimal.Round(porcentaje, 2, MidpointRounding.AwayFromZero);

                XElement x = new XElement("DetalleRetencion",
                                          new XElement("RifRetenido", f.RifCompania.ToString().Replace("-", "")),
                                          new XElement("NumeroFactura", factura.NumeroFactura),
                                          new XElement("NumeroControl", sNumeroControlDefinitivo),
                                          new XElement("FechaOperacion", factura.FechaRecepcion.ToString("dd/MM/yyyy").Replace("-", "/")),
                                          new XElement("CodigoConcepto", codigoConceptoRetencion_islr),
                                          // siempre nos aseguramos que el signo decimal en los montos sea '.' y no ','
                                          new XElement("MontoOperacion", montoOperacion.ToString().Replace(",", ".")),
                                          new XElement("PorcentajeRetencion", porcentaje.ToString().Replace(",", "."))
                                          );

                xmldoc.Element("RelacionRetencionesISLR").Add(x);

                cantidadRetenciones++;
            }

            cantidadFacturas++;
        }

        String fileName = @"ISLR_retenido_" + sNombreCiaContab + ".xml";
        String filePath = HttpContext.Current.Server.MapPath("~/Temp/" + fileName);

        // --------------------------------------------------------------------------------------------------
        // si el usuario así lo indica, leemos retenciones desde la nómina de pago
        if (!LeerNomina_CheckBox.Checked)
        {
            // Saving to a file, you can also save to streams
            xmldoc.Save(filePath);

            GeneralMessage_Span.InnerHtml = "<br />" +
                                            "Ok, el archivo xml ha sido generado en forma satisfactoria. <br />" +
                                            "Se han leído " + cantidadFacturas.ToString() + " facturas, en base al criterio de selección que Ud. indicó. <br />" +
                                            "Se han agregado " + cantidadRetenciones.ToString() + " retenciones (registros) al archivo de retenciones. <br />" +
                                            "El nombre del archivo es: " + filePath + ".<br /><br />";

            GeneralMessage_Span.Style["display"] = "block";

            DownloadFile_LinkButton.Visible = true;
            FileName_HiddenField.Value      = filePath;

            return;
        }

        // -----------------------------------------------------------------------------------------------
        // lo primero que hacemos es intentar generar fechas de inicio y fin usando el período indicado
        int ano = Convert.ToInt32(PeriodoSeleccion_TextBox.Text.ToString().Substring(0, 4));
        int mes = Convert.ToInt32(PeriodoSeleccion_TextBox.Text.ToString().Substring(4, 2));

        if (ano <= 1990 || ano >= 2050)
        {
            ErrMessage_Span.InnerHtml = "El período indicado no está correctamente formado. <br /><br />" +
                                        "Recuerde que el período debe formarse de la siguiente manera: aaaamm; ejemplo: 201006.";
            ErrMessage_Span.Style["display"] = "block";

            dbBancos = null;
            return;
        }

        if (mes <= 0 || mes >= 13)
        {
            ErrMessage_Span.InnerHtml = "El período indicado no está correctamente formado. <br /><br />" +
                                        "Recuerde que el período debe formarse de la siguiente manera: aaaamm; ejemplo: 201006.";
            ErrMessage_Span.Style["display"] = "block";

            dbBancos = null;
            return;
        }

        // intentamos leer el código de retención para empleados de nómina

        // declaramos el EF context ...
        NominaEntities nominaCtx = new NominaEntities();

        ContabSysNet_Web.ModelosDatos_EF.Nomina.ParametrosNomina parametrosNomina = (from c in nominaCtx.ParametrosNominas
                                                                                     where c.Cia == ciaContab
                                                                                     select c).FirstOrDefault();

        if (parametrosNomina == null || string.IsNullOrEmpty(parametrosNomina.CodigoConceptoRetencionISLREmpleados))
        {
            ErrMessage_Span.InnerHtml = "Aparentemente, no se ha definido un código de retención ISLR para empleados en la tabla Parámetros Nómina. <br /><br /> " +
                                        "Por favor abra la tabla mencionada y registre el código usado como concepto de retención para retención ISLR de empleados.";
            ErrMessage_Span.Style["display"] = "block";

            dbBancos = null;
            return;
        }

        // rubro que corresponde al ISLR
        var rubroIslr = nominaCtx.tMaestraRubros.Select(r => new { r.Rubro, r.TipoRubro }).Where(r => r.TipoRubro == 8).FirstOrDefault();

        if (rubroIslr == null)
        {
            ErrMessage_Span.InnerHtml = "No se ha definido el rubro ISLR en la maestra de rubros " +
                                        "(Catálogos --> Maestra de Rubros). <br /><br />" +
                                        "Ud. debe definir el rubro ISLR en la Maestra de Rubros.";
            ErrMessage_Span.Style["display"] = "block";

            nominaCtx = null;
            return;
        }

        // leemos la nómina de pago del mes y seleccionamos los rubros que corresponden a la retención de ISLR
        // recuérdese que arriba validamos que existan rubros marcados como ISLR en la maestra; sin embargo,
        // puede no haber de éstos en la nómina de pago ...

        // además, leemos solo los empleados cuya propiedad EscribirArchivoXMLRetencionesISLR es true ...
        var queryNominaPago = from n in nominaCtx.tNominas
                              where
                              n.tNominaHeader.FechaNomina.Month == mes &&
                              n.tNominaHeader.FechaNomina.Year == ano &&
                              (n.tEmpleado.EscribirArchivoXMLRetencionesISLR != null &&
                               n.tEmpleado.EscribirArchivoXMLRetencionesISLR == true) &&
                              n.tNominaHeader.tGruposEmpleado.Cia == ciaContab &&
                              n.Rubro == rubroIslr.Rubro                                              // maestraRubro.Rubro
                              group n by n.Empleado into g
                              select new
        {
            empleado    = g.Key,
            fechaNomina = g.Max(m => m.tNominaHeader.FechaNomina),
            montoISLR   = g.Sum(m => m.Monto),
            montoBase   = g.Sum(m => m.MontoBase)
        };

        int empleadosAgregadosISLRFile = 0;

        RegistroRetencionISLR        registroRetencionISLR;
        List <RegistroRetencionISLR> registroRetencionISLR_List = new List <RegistroRetencionISLR>();

        foreach (var n in queryNominaPago)
        {
            // leemos empleado

            ContabSysNet_Web.ModelosDatos_EF.Nomina.tEmpleado empleado = (from emp in nominaCtx.tEmpleados
                                                                          where emp.Empleado == n.empleado
                                                                          select emp).FirstOrDefault();

            if (String.IsNullOrEmpty(empleado.Rif))
            {
                ErrMessage_Span.InnerHtml = "Aunque se ha retenido ISLR al empleado " + empleado.Nombre +
                                            " en la nómina de pago, no se ha registrado su número de rif en la Maestra de Empleados. <br /><br />" +
                                            "Por favor abra la tabla mencionada y registre un número de rif para cada empleado que tenga retención de ISLR en la nómina de pago.";
                ErrMessage_Span.Style["display"] = "block";

                dbBancos = null;
                return;
            }

            decimal islrPorc  = 0;
            decimal montoBase = 0;
            decimal montoISLR = n.montoISLR;

            if (n.montoBase != null)
            {
                montoBase = n.montoBase.Value;
            }

            if (montoBase < 0)
            {
                // cómo la retención de islr en la nómina es una deducción, este monto viene negativo ...
                montoBase *= -1;
            }

            if (montoISLR < 0)
            {
                montoISLR *= -1;
            }

            if (montoBase != 0)
            {
                islrPorc = montoISLR * 100 / montoBase;
            }

            registroRetencionISLR = new RegistroRetencionISLR();

            registroRetencionISLR.RifRetenido    = empleado.Rif;
            registroRetencionISLR.NumeroFactura  = "0";
            registroRetencionISLR.NumeroControl  = "NA";
            registroRetencionISLR.FechaOperacion = n.fechaNomina;
            registroRetencionISLR.CodigoConcepto = parametrosNomina.CodigoConceptoRetencionISLREmpleados;

            // nos aseguramos que el monto tenga siempre 2 decimales
            decimal montoOperacion = decimal.Round(montoBase, 2, MidpointRounding.AwayFromZero);
            decimal porcentaje     = decimal.Round(islrPorc, 2, MidpointRounding.AwayFromZero);

            // al convertir el monto a string siempre queda así: 1500.35
            registroRetencionISLR.MontoOperacion      = montoOperacion.ToString();
            registroRetencionISLR.PorcentajeRetencion = porcentaje.ToString();

            registroRetencionISLR_List.Add(registroRetencionISLR);

            empleadosAgregadosISLRFile++;
        }

        // finalmente, agregamos cada item en la lista como un nodo al xml file
        foreach (RegistroRetencionISLR r in registroRetencionISLR_List)
        {
            XElement x = new XElement("DetalleRetencion",
                                      new XElement("RifRetenido", r.RifRetenido.ToString().Replace("-", "")),
                                      new XElement("NumeroFactura", r.NumeroFactura),
                                      new XElement("NumeroControl", r.NumeroControl),
                                      new XElement("FechaOperacion", r.FechaOperacion.ToString("dd/MM/yyyy")),
                                      new XElement("CodigoConcepto", r.CodigoConcepto),
                                      new XElement("MontoOperacion", r.MontoOperacion),
                                      new XElement("PorcentajeRetencion", r.PorcentajeRetencion)
                                      );

            xmldoc.Element("RelacionRetencionesISLR").Add(x);
        }

        // Saving to a file, you can also save to streams
        xmldoc.Save(filePath);

        GeneralMessage_Span.InnerHtml = "<br />" +
                                        "Ok, el archivo xml ha sido generado en forma satisfactoria. <br />" +
                                        "Se han leído " + cantidadFacturas.ToString() + " facturas, en base al criterio de selección que Ud. indicó. <br />" +
                                        "Se han agregado " + cantidadRetenciones.ToString() + " retenciones (registros) al archivo de retenciones. <br />" +
                                        "El nombre del archivo es: " + filePath + "<br /><br />" +
                                        "Además, se han agregado " + empleadosAgregadosISLRFile.ToString() + " retenciones (registros) desde la nómina de pago del mes.";
        GeneralMessage_Span.Style["display"] = "block";

        DownloadFile_LinkButton.Visible = true;
        FileName_HiddenField.Value      = filePath;
    }
        private void CrearFactura(string CondicionVenta, string MedioPago)
        {
            try
            {
                DateTime       FechaEmicionDocumento = DateTime.Now;
                int            casaMatriz            = 1;
                int            PuntoVenta            = 1;
                Tipo_documento tipoDocumento         = Tipo_documento.Factura_electrónica;
                if (tb_TipoFactura.IsChecked.Value)
                {
                    tipoDocumento = Tipo_documento.Tiquete_Electrónico;
                }

                #region HeaderFactura
                Factura fac = new Factura()
                {
                    Codigo_Moneda                = "CRC",
                    CondicionVenta               = CondicionVenta,
                    Email_Enviado                = false,
                    CasaMatriz                   = casaMatriz,
                    PuntoVenta                   = PuntoVenta,
                    Emisor_CorreoElectronico     = RecursosSistema.Contribuyente.CorreoElectronico,
                    Emisor_Identificacion_Numero = RecursosSistema.Contribuyente.Identificacion_Numero,
                    Emisor_Identificacion_Tipo   = RecursosSistema.Contribuyente.Identificacion_Tipo,
                    Emisor_Nombre                = RecursosSistema.Contribuyente.Nombre,
                    Emisor_NombreComercial       = RecursosSistema.Contribuyente.NombreComercial,
                    Emisor_Telefono_Codigo       = RecursosSistema.Contribuyente.Telefono_Codigo,
                    Emisor_Telefono_Numero       = RecursosSistema.Contribuyente.Telefono_Numero,
                    Emisor_Ubicacion_Barrio      = RecursosSistema.Contribuyente.Barrio,
                    Emisor_Ubicacion_Canton      = RecursosSistema.Contribuyente.Canton,
                    Emisor_Ubicacion_Distrito    = RecursosSistema.Contribuyente.Distrito,
                    Emisor_Ubicacion_Provincia   = RecursosSistema.Contribuyente.Provincia,
                    Emisor_Ubicacion_OtrasSenas  = RecursosSistema.Contribuyente.OtrasSenas,
                    Fecha_Emision_Documento      = FechaEmicionDocumento,
                    Estado           = (int)EstadoComprobante.Enviado,
                    Id_Contribuyente = RecursosSistema.Contribuyente.Id_Contribuyente,
                    Id_TipoDocumento = (int)tipoDocumento,
                    MedioPago        = MedioPago,
                };
                #endregion

                #region Totales
                if (ResumenProductoExento != 0)
                {
                    fac.TotalMercanciasExentas = ResumenProductoExento;
                }

                if (ResumenProductoGravado != 0)
                {
                    fac.TotalMercanciasGravadas = ResumenProductoGravado;
                }

                if (ResumenServicioExento != 0)
                {
                    fac.TotalServExentos = ResumenServicioExento;
                }

                if (ResumenServicioGravado != 0)
                {
                    fac.TotalServGravados = ResumenServicioGravado;
                }

                if (ResumenImpuesto != 0)
                {
                    fac.TotalImpuesto = ResumenImpuesto;
                }

                if (ResumenDescuentos != 0)
                {
                    fac.TotalDescuentos = ResumenDescuentos;
                }

                fac.TotalGravado = (fac.TotalMercanciasGravadas ?? 0) + (fac.TotalServGravados ?? 0);
                fac.TotalExento  = (fac.TotalMercanciasExentas ?? 0) + (fac.TotalServExentos ?? 0);
                fac.TotalVenta   = (fac.TotalGravado ?? 0) + (fac.TotalExento ?? 0);

                fac.TotalVentaNeta   = fac.TotalVenta - (fac.TotalDescuentos ?? 0);
                fac.TotalComprobante = fac.TotalVentaNeta + (fac.TotalImpuesto ?? 0);

                #endregion



                if (tipoDocumento == Tipo_documento.Factura_electrónica)
                {
                    Cliente ClienteSeleccionado = cb_Clientes.SelectedItem as Cliente;
                    if (ClienteSeleccionado == null)
                    {
                        loadingDisplayer.Visibility = Visibility.Collapsed;
                        MessageBox.Show("Error al obtener datos del cliente seleccionado", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }

                    fac.Receptor_CorreoElectronico     = ClienteSeleccionado.CorreoElectronico;
                    fac.Receptor_Identificacion_Numero = ClienteSeleccionado.Identificacion_Numero;
                    fac.Receptor_Identificacion_Tipo   = ClienteSeleccionado.Identificacion_Tipo;
                    fac.Receptor_Nombre               = ClienteSeleccionado.Nombre;
                    fac.Receptor_NombreComercial      = ClienteSeleccionado.NombreComercial;
                    fac.Receptor_Telefono_Codigo      = ClienteSeleccionado.Telefono_Codigo;
                    fac.Receptor_Telefono_Numero      = ClienteSeleccionado.Telefono_Numero;
                    fac.Receptor_Ubicacion_Barrio     = ClienteSeleccionado.Barrio;
                    fac.Receptor_Ubicacion_Canton     = ClienteSeleccionado.Canton;
                    fac.Receptor_Ubicacion_Distrito   = ClienteSeleccionado.Distrito;
                    fac.Receptor_Ubicacion_OtrasSenas = ClienteSeleccionado.OtrasSenas;
                    fac.Receptor_Ubicacion_Provincia  = ClienteSeleccionado.Provincia;
                }

                if (tipoDocumento == Tipo_documento.Tiquete_Electrónico)
                {
                    string clienteTiquete;
                    if (string.IsNullOrEmpty(txt_Cliente_Tiquete.Text))
                    {
                        clienteTiquete = "Cliente Contado";
                    }
                    else
                    {
                        clienteTiquete = txt_Cliente_Tiquete.Text;
                    }

                    fac.Receptor_Nombre = clienteTiquete;
                }

                fac.Factura_Detalle = new List <Factura_Detalle>(FacturaDetalle);


                Contribuyente_Consecutivos Consecutivo;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    Consecutivo           = db.Contribuyente_Consecutivos.First(q => q.Id_Contribuyente == RecursosSistema.Contribuyente.Id_Contribuyente);
                    fac.NumeroConsecutivo = Consecutivo.Consecutivo_Facturas;

                    string ClaveHacienda = new GeneradorDeClavesHacienda(new GeneradorDeClavesHacienda()
                    {
                        ConsecutivoHacienda = new ConsecutivoHacienda(new ConsecutivoHacienda()
                        {
                            TipoDocumento         = Tipo_documento.Factura_electrónica,
                            NumeracionConsecutiva = Consecutivo.Consecutivo_Facturas,
                            CasaMatriz            = casaMatriz,
                            PuntoVenta            = PuntoVenta
                        }),
                        FechaEmicion = FechaEmicionDocumento,
                        Identificacion_Contribuyente = Convert.ToInt64(RecursosSistema.Contribuyente.Identificacion_Numero),
                    }).ToString();

                    fac.Clave = ClaveHacienda;
                    db.Factura.Add(fac);
                    Consecutivo.Consecutivo_Facturas++;

                    try
                    {
                        if (tipoDocumento == Tipo_documento.Factura_electrónica)
                        {
                            FacturaDB_ToFacturaElectronica Hacienda = new FacturaDB_ToFacturaElectronica(RecursosSistema.Contribuyente);
                            Hacienda.Convertir(fac).CrearXml(tipoDocumento).Enviar();
                            fac.XML_Enviado = Hacienda.XML.InnerXml;
                            new FacturaPDF.FacturaElectronicaPDF().CrearFactura(fac);
                        }
                        else
                        {
                        }
                        db.SaveChanges();
                        LimpiarVista();
                        RecursosSistema.WindosNotification("Factura", "La factura Clave [" + fac.Clave + "] se envío para su valoración");
                        RecursosSistema.Servicio_AgregarFactura(fac.Clave);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    loadingDisplayer.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                loadingDisplayer.Visibility = Visibility.Collapsed;
                this.LogError(ex);
                MessageBox.Show("Ocurrio un error al crear la factura en la base de datos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
예제 #14
0
 public AgregarFactura(Factura factura)
 {
     InitializeComponent();
     this._factura     = factura;
     this.DialogResult = DialogResult.Cancel;
 }
예제 #15
0
 public FrmVenta()
 {
     InitializeComponent();
     LabelCurso.Enabled = false;
     Factura            = new Factura();
 }
예제 #16
0
        public void FacturaVaciaTotalEnCero()
        {
            Factura factura = new Factura();

            Assert.AreEqual(0, factura.GetTotal());
        }
예제 #17
0
 public int ModificarFactura(Factura factura, int idFactura)
 {
     return(this.Modificar(idFactura, factura));
 }
        /// <summary>
        /// Crea una row para ser mostrada en la grilla de facturas
        /// </summary>
        /// <param name="table">DataTable con la estructura del DataRow.</param>
        /// <param name="factura">Factura a mostrar.</param>
        /// <returns>DataRow con los datos a mostrar.</returns>
        private DataRow CreateDataRow(DataTable table, Factura factura)
        {
            var row = table.NewRow();
            row[0] = factura.Nro;
            row[1] = factura.Fecha.ToShortDateString();
            row[2] = factura.Total.ToString("N");
            row[3] = factura.Cuotas;
            row[4] = factura.CuotasRestantes;
            row[5] = Math.Round(factura.Total / factura.Cuotas, 2);

            return row;
        }
예제 #19
0
 public void AdaugaFactura(Factura factura)
 {
     _context.Facturi.Add(factura);
 }
 /// <summary>
 /// Registra una factura en el sistema.
 /// </summary>
 /// <param name="factura">Factura a registrar.</param>
 /// <param name="productos">Productos a comprar con la factura.</param>
 /// <returns>Numero de la factura.</returns>
 int IFacturaService.Add(Factura factura, FacturaProducto[] productos)
 {
     factura.Save(productos);
     return factura.Nro;
 }
 /// <summary>
 /// Retorna el valor total a pagar.
 /// </summary>
 /// <param name="factura">factura que el cliente desea pagar.</param>
 /// <returns>Valor a pagar.</returns>
 private double GetTotalPago(Factura factura)
 {
     return factura.Total / factura.Cuotas * (double)numCuotas.Value;
 }
        private bool ExisteEnLaBaseDatos()
        {
            Factura factura = FacturaBLL.Buscar((int)Convert.ToInt32(idTextBox.Text));

            return(factura != null);
        }
		/// <summary>
		/// Copia los valorres almacenados en el objeto COnfiguracion a al objeto Factura
		/// </summary>
		/// <param name="f">Factura a la cual se le asignarán los valores del objeto Configuracion</param>
		public void CargarConfiguracion(Factura f)
		{
			Empresa emisor;
			Domicilio domicilioFiscalEmisor;

			f.Version = Version;
			f.Serie = Serie;
			//f.NoAprobacion = NoAprobacion;
			//f.AnoAprobacion = AnoAprobacion;
			f.FormaDePago = FormaDePago;
			f.NoCertificado = NoCertificado;
			f.Certificado = Certificado;
			f.CondicionesDePago = CondicionesDePago;
			f.MetodoDePago = MetodoDePago;
			f.LugarExpedicion = LugarExpedicion;

			f.Xmlns = Xmlns;
			f.Xmlns_Xsi = Xmlns_Xsi;
			f.Xsi_SchemaLocation = Xsi_SchemaLocation;

			emisor = new Empresa();
			emisor.Nombre = Emisor.Nombre;
			emisor.RFC = Emisor.RFC;
			emisor.RegimenFiscal = Emisor.RegimenFiscal;
			f.Emisor = emisor;

			domicilioFiscalEmisor = new Domicilio();
			domicilioFiscalEmisor.Calle = DomicilioFiscalEmisor.Calle;
			domicilioFiscalEmisor.NoExterior = DomicilioFiscalEmisor.NoExterior;
			domicilioFiscalEmisor.NoInterior = DomicilioFiscalEmisor.NoInterior;
			domicilioFiscalEmisor.Colonia = DomicilioFiscalEmisor.Colonia;
			domicilioFiscalEmisor.Localidad = DomicilioFiscalEmisor.Localidad;
			domicilioFiscalEmisor.Referencia = DomicilioFiscalEmisor.Referencia;
			domicilioFiscalEmisor.Municipio = DomicilioFiscalEmisor.Municipio;
			domicilioFiscalEmisor.Estado = DomicilioFiscalEmisor.Estado;
			domicilioFiscalEmisor.Pais = DomicilioFiscalEmisor.Pais;
			domicilioFiscalEmisor.CodigoPostal = DomicilioFiscalEmisor.CodigoPostal;
			f.DomicilioFiscalEmisor = domicilioFiscalEmisor;
		}
예제 #24
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.accion.Equals(6))
            {
                /*eliman el produc y actualiza la factu*/
                this.subTotal = this.subTotal - this.totalProd;
                this.Iva      = this.subTotal * 0.13;
                this.Total    = this.subTotal + this.Iva;
                /*llama del metodo*/
                modelo.CambioCliente devp = new modelo.CambioCliente();
                devp.Idfactura  = this.IdFact;
                devp.Idproducto = this.producId;
                devp.Sub1       = this.subTotal;
                devp.Iva        = this.Iva;
                devp.Total      = this.Total;
                devp.devProduct();
                if (devp.Msg.Equals("Producto eliminado"))
                {
                    MessageBox.Show(devp.Msg);
                    this.Hide();
                    ActuFactu dev = new ActuFactu();
                    dev.Id     = this.id;
                    dev.Nombre = this.nombre;
                    dev.Rol    = this.rol;
                    dev.IdFact = this.IdFact;
                    dev.Accion = this.accion;
                    dev.Show();
                }
                else
                {
                    MessageBox.Show(devp.Msg);
                    this.Hide();
                    ActuFactu dev = new ActuFactu();
                    dev.Id     = this.id;
                    dev.Nombre = this.nombre;
                    dev.Rol    = this.rol;
                    dev.IdFact = this.IdFact;
                    dev.Accion = this.accion;
                    dev.Show();
                }
            }
            else
            {
                this.Hide();
                Factura fac = new Factura();

                fac.Id            = this.id;
                fac.Rol           = this.Rol;
                fac.Nombre        = this.nombre;
                fac.IdCliente     = this.idCliente;
                fac.NombreCliente = this.nombreCliente;
                fac.Documento     = this.documento;
                fac.Direccion1    = this.Direccion;
                fac.Telefono1     = this.Telefono;
                fac.Tipo          = this.tipo;
                /*el detalle*/
                fac.NumeroFact = this.numeroFact;
                /*---*/
                fac.SubTotal = this.subTotal;
                fac.Iva1     = this.Iva;
                fac.Total1   = this.Total;
                /*----------------*/
                fac.Idproducto     = this.idproducto;
                fac.Codigo1        = this.Codigo;
                fac.NombreProducto = this.nombreProducto;
                fac.Cantidad       = this.cantidad;
                fac.Descuento      = this.descuento;
                fac.Totalproducto  = this.totalproducto;
                fac.PrecioVenta    = this.precioVenta;
                fac.Show();
            }
        }
        /// <summary>
        /// Setea el DataSource de la grilla.
        /// </summary>
        /// <param name="Facturas">Coleccion de facturas a mostrar.</param>
        private void SetDataSource(Factura[] Facturas)
        {
            var table = CreateDataTable();
            Facturas.ForEach(factura => table.Rows.Add(CreateDataRow(table, factura)));

            dgvFacturas.DataSource = table;
        }
예제 #26
0
        public static bool GeneratePDF(Factura factura, bool notadeCredito)
        {
            log.Info($"Generando el PDF");

            var cliente = factura.cliente[0];

            string formatedId        = formatIndentificacion(cliente);
            string humanizedTotal    = humanizeTotal(factura);
            string formatedDireccion = XmlHelper.formatedDireccion(cliente);

            string consecutivoFactura = notadeCredito
                         ? factura.claveNumericaFactura.Substring(21, 20)
                         : "";

            try
            {
                string cssPath = Path.Combine(Directory.GetCurrentDirectory(), "dist/template.css");

                var sb = new StringBuilder();
                sb.AppendFormat(@"
                           <html>
                             <head>
                             </head>
                             <body>
                                <div class='header row'>
                                    <h1>{0}</h1>
                                    <h1>Clave Numérica {1}</h1>
                                    {10}
                                    <h3 class='date'><strong>Fecha de emisión:</strong> {2}</h3>
                                </div>
                                <div class='header row'>
                                    <div class='col-50'>
                                        <h1><strong>Comercial Pozos de Santa Ana S.A</strong></h1>
                                        <h2><strong>Comercial Pozos de Santa Ana S.A</strong></h2>
                                        <h2><strong>Cédula Jurídica: </strong> 3-101-159911</h2>
                                    </div>
                                    <div class='col-50'>
                                       <h2><strong>Tel.: </strong>2282-6030 / 2282-4516 / 2282-1420 / 2282-1889 / 2282-4571 </h2> 
                                       <h2><strong>Correo: </strong>[email protected]</h2>
                                       <h2><strong>Direccion: </strong>San José, Santa Ana, Pozos. 100 metros sur de la iglesia de pozos.</h2>  
                                    </div>
                                </div>
                                
                                 <div class='header row'>
                                    <div class='col-50'>
                                       <h2><strong>Receptor: </strong>{3}</h2> 
                                       <h2>{4}</h2>
                                       <h2>{5}</h2>
                                       <h2>{6}</h2>
                                       <h2>{7}</h2>
                                    </div>
                                    <div class='col-50'>
                                       <h2><strong>Número de referencia: </strong>{8}</h2> 
                                       <h2><strong>Condición de venta: </strong>{9}</h2>  
                                    </div>
                                </div>

                                <div class='row'>
                                    <h1 align='center'> Lineas de Detalle</h1>
                                </div>

                                <table align='center'>
                                    <tr class='table-header'>
                                        <th>Código</th>
                                        <th>Cantidad</th>
                                        <th>Unidad Medida</th>
                                        <th>Descipción del Producto</th>
                                        <th>Consumidor</th>
                                        <th>Precio Unitario</th>
                                        <th>Descuento</th>
                                        <th>SubTotal</th>
                                    </tr>",
                                $"{(notadeCredito ? "Nota de Crédito" : "Factura")} No {factura.numConsecutivo}",
                                factura.claveNumerica, factura.fecha,
                                factura.clienteTributa ? cliente.nombre : "Cliente Contado",
                                factura.clienteTributa ? $"<strong>Identificación: </strong>{formatedId}" :"",
                                factura.clienteTributa ? $"<strong>Teléfono: </strong>{cliente.telefono}" : "",
                                factura.clienteTributa ? $"<strong>Correo: </strong>{cliente.email }" : "",
                                factura.clienteTributa ? $"<strong>Dirección: </strong>{formatedDireccion}" : "",
                                factura.id_documento,
                                $"{(factura.plazo == 0 ? "Contado" : $"Crédito a {factura.plazo} dias plazo")}",
                                notadeCredito ? $"<h1>Factura de Referencia: {consecutivoFactura}" : "");

                foreach (factura_Detalle detalle in factura.factura_Detalle)
                {
                    sb.AppendFormat(@"<tr class='table-row' align='center'>
                                    <td>{0}</td>
                                    <td>{1}</td>
                                    <td>{2}</td>
                                    <td align='left'>{3}</td>
                                    <td>₡{4}</td>
                                    <td>₡{5}</td>   
                                    <td>{6}</td>
                                    <td>₡{7}</td>
                                  </tr>", detalle.Id_Producto,
                                    detalle.cantidad,
                                    detalle.unidadString,
                                    detalle.producto[0].nombre,
                                    detalle.consumidor.ToString("N2"),
                                    detalle.precio.ToString("N2"),
                                    $"{Convert.ToInt32(detalle.descuento)}%",
                                    $"{detalle.montoTotal.ToString("n2")}{((!detalle.IV) ? "*" : "")}");
                }

                sb.AppendFormat(@"
                                </table>
                                <div>
                                    <h3>{6}</d3>
                                </div>
                                <div class='totales'>
                                       <table class='tabla-totales' cellpadding='10'>
                                            <tr class='row-totales'>
                                                <td class='toti'><strong>Gravado:</strong></td>
                                                <td> ₡</td>
                                                <td class='toti'>{0}</td>
                                            </tr>
                                            <tr class='row-totales'>
                                                <td class='toti'><strong>Exento:</strong></td>
                                                <td> ₡</td>
                                                <td class='toti'>{1}</td>
                                            </tr>
                                            <tr class='row-totales'>
                                                <td class ='toti'><strong>Descuento:</strong></td>
                                                <td> ₡</td>
                                                <td class='toti'>{2}</td>
                                            </tr>
                                            <tr class='row-totales'>
                                                <td class ='toti'><strong>Impuestos:</strong></td>
                                                <td> ₡</td>
                                                <td class='toti'>{3}</td>
                                            </tr>
                                            <tr class='row-totales'>
                                                <td class ='toti'><strong>Total {7}:</strong></td>
                                                <td> ₡</td>
                                                <td class='toti'>{4}</td>
                                            </tr>                                       
                                       </table>  
                                       <p>{5}</p>
                                </div>                              
                                <div class='header foota'>
                                    <h1>Emitida confirme lo establecido en la resolución de Facturación Electrónica, No DGT-R-48-2016 siete de octubre
                                        de dos mil dieciseis de la Direccion General de Tributación</h1>                     
                                </div>
                            </body>
                        </html>", factura.totalGravado.ToString("N2"),
                                factura.totalExento.ToString("N2"),
                                factura.totalDescuentos.ToString("N2"),
                                factura.totalImpuestos.ToString("N2"),
                                factura.totalComprobante.ToString("N2"),
                                humanizedTotal,
                                (factura.totalDescuentos > 0) ? "<strong>Motivo del descuento: </strong>Pronto Pago" : "",
                                notadeCredito ? "Nota de Crédito" : "Factura"
                                );

                var      fileName = $"C://DSign//Temp//{factura.claveNumerica}.pdf";
                FileInfo file     = new FileInfo(fileName);
                file.Directory.Create();

                var converter = new BasicConverter(new PdfTools());
                var doc       = new HtmlToPdfDocument()
                {
                    GlobalSettings =
                    {
                        ColorMode   = ColorMode.Color,
                        Orientation = Orientation.Portrait,
                        PaperSize   = PaperKind.Letter,
                        Out         = fileName
                    },
                    Objects =
                    {
                        new ObjectSettings()
                        {
                            PagesCount     = true,
                            HtmlContent    = sb.ToString(),
                            WebSettings    = { DefaultEncoding     = "utf-8", UserStyleSheet = cssPath },
                            FooterSettings =
                            {
                                FontSize =                           9,
                                Right    = "Pagina [page] de [toPage]",
                                Line     = true,
                                Spacing  = 2.812
                            }
                        }
                    }
                };

                converter.Convert(doc);
            }
예제 #27
0
 public ActionResult MostrarFactura(Factura factura)
 {
     return View(factura);
 }
예제 #28
0
 public Tuple <bool, int> InsertarFactura(Factura factura)
 {
     return(facturasDatos.InsertarFactura(factura));
 }
예제 #29
0
 public ActionResult Register(Cliente user, string confirmarContra, string idGrupoTrabajo, Membresia Membresia)
 {
     if (ModelState.IsValid)
     {
         var ok = true;
         if (!user.Contraseña.Equals(confirmarContra))
         {
             ModelState.AddModelError("confirmarContra", "Las contraseñas no coinciden");
             ok = false;
         }
         if (Singleton.GetInstance().YaExisteIDCliente(user.ID))
         {
             ModelState.AddModelError("ID", "El identificador ya existe");
             ok = false;
         }
         if (Membresia.Desde >= Membresia.Hasta)
         {
             ModelState.AddModelError("Membresia.Hasta", "La fecha hasta debe ser mayor a la fecha desde");
             ok = false;
         }
         if (ok)
         {
             if (idGrupoTrabajo != null)
             {
                 user.GrupoTrabajo = Singleton.GetInstance().GetGrupoTrabajo(idGrupoTrabajo);
             }
             user.Membresias.Add(Membresia);
             Singleton.GetInstance().Clientes.Add(user);
             Factura factura = new Factura(false)
             {
                 Cliente = user,
                 Membresia = Membresia,
                 TotalAPagar = Membresia.CalcularTotal(),
                 IVA = Membresia.CalcularImpuestos()
             };
             return View("MostrarFactura", factura);
         }
     }
     if (user.ID == null)
         user.ID = Singleton.GetInstance().GetClienteID();
     CargarViewBags();
     return View(user);
 }
예제 #30
0
        public static Error validarFacturas(Factura factura)
        {
            if (factura.clienteTributa)
            {
                var cliente = factura.cliente[0];
                try
                {
                    //validate email
                    log.Info($"Correo del cliente: {cliente.email}");
                    MailAddress mail = new MailAddress(cliente.email);

                    Regex regex = new Regex(@"^[0-9]{8}$");

                    log.Info($"Telefono del cliente: {cliente.telefono}");
                    //validate phone
                    if (regex.Match(cliente.telefono.Trim().Replace("-", "")) == Match.Empty)
                    {
                        return(new Error(factura.id_documento, "Error:002", "Formato del numero incorrecto"));
                    }

                    log.Info($"Identificacion del cliente: {cliente.identificacion} del tipo: {cliente.tipoIdentificacion}");
                    regex = new Regex(@"^[0-9]{12}$");
                    //validate identificacion
                    if (cliente.tipoIdentificacion == 3 &&
                        regex.Match(cliente.identificacion.Trim().Replace("-", "")) == Match.Empty)
                    {
                        return(new Error(factura.id_documento, "Error:003", "El formato de la cedula no corresponde al tipo de identificacion"));
                    }

                    regex = new Regex(@"^[0-9]{10}$");
                    //validate identificacion
                    if (cliente.tipoIdentificacion == 2 &&
                        regex.Match(cliente.identificacion.Trim().Replace("-", "")) == Match.Empty)
                    {
                        return(new Error(factura.id_documento, "Error:003", "El formato de la cedula no corresponde al tipo de identificacion"));
                    }

                    regex = new Regex(@"^[0-9]{9}$");
                    //validate identificacion
                    if (cliente.tipoIdentificacion == 1 &&
                        regex.Match(cliente.identificacion.Trim().Replace("-", "")) == Match.Empty)
                    {
                        return(new Error(factura.id_documento, "Error:003", "El formato de la cedula no corresponde al tipo de identificacion"));
                    }


                    return(null);
                }
                catch (FormatException ex)
                {
                    log.Error(ex.Message);
                    return(new Error(factura.id_documento, "Error:001", "Formato del correo incorrecto"));
                }
                catch (NullReferenceException ex)
                {
                    log.Error(ex.Message);
                    return(new Error(factura.id_documento, "Error:004", "Unhaldled exception"));
                }
            }

            log.Info("La factura esta marcada sin receptor, no necesita validacion");
            return(null);
        }
예제 #31
0
 private ActionResult ContinuarEdicionCuenta(Cliente cliente, string confirmarContra, string idGrupoTrabajo, Membresia Membresia, bool membresiaOn)
 {
     if (idGrupoTrabajo != null)
     {
         cliente.GrupoTrabajo = Singleton.GetInstance().GetGrupoTrabajo(idGrupoTrabajo);
     }
     if (membresiaOn)
     {
         cliente.Membresias.Add(Membresia);
         Factura factura = new Factura(false)
         {
             Cliente = cliente,
             Membresia = Membresia,
             TotalAPagar = Membresia.CalcularTotal(),
             IVA = Membresia.CalcularImpuestos()
         };
         ModificarCliente(cliente);
         ViewBag.ReturnUrl = "Home";
         return View("MostrarFactura", factura);
     }
     ModificarCliente(cliente);
     return RedirectToAction("Index", "Home");
 }
예제 #32
0
 public static String comprar(Factura F, List<DtoProductoVenta> lista)
 {
     return DaoFactura.comprar(F,lista);
 }
예제 #33
0
        public void fillFacturaItems(ref StreamWriter streamToFill, Int16 maxTextWidth, Factura factura, String literal, double descuento)
        {
            List<string> items;
            int idx;
            streamToFill.WriteLine(strFormat.fillString('-', maxTextWidth));
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.formatString("CANT", Align.Left, 4) +
                                   strFormat.formatString("CONCEPTO", Align.Center, 16) +
                                   strFormat.formatString("PRECIO", Align.Right, 8) +
                                   strFormat.formatString("TOTAL", Align.Right, 8));
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.fillString('-', maxTextWidth));

            foreach (ItemFactura item in factura.Items)
            {
                streamToFill.WriteLine();
                items = TextWrapper( item.ItemNombre , 17 );
                idx = 0;

                // If we wrapped the text and it contains more than one line, we need to procees one by one.
                if ( items.Count > 1 )
                {
                    foreach ( var itemNames in items )
                    {
                        if ( idx == 0 )
                        {
                            streamToFill.WriteLine( strFormat.formatString( item.ItemCantidad.ToString( ) , Align.Center , 4 ) +
                                    strFormat.formatString( itemNames , Align.Left , 17 ) +
                                    strFormat.formatString( item.ItemPrecioUnitario.ToString( ) , Align.Right , 8 ) +
                                    strFormat.formatString( item.ItemImporte.ToString( ) , Align.Right , 8 ) );
                        }
                        else
                        {
                            streamToFill.WriteLine( );
                            streamToFill.WriteLine( strFormat.formatString( " " , Align.Center , 4 ) + strFormat.formatString( itemNames , Align.Left , 17 ) );
                        }

                        idx++;
                    }
                }
                else
                {
                    streamToFill.WriteLine( strFormat.formatString( item.ItemCantidad.ToString( ) , Align.Center , 4 ) +
                                      strFormat.formatString( item.ItemNombre , Align.Left , 17 ) +
                                      strFormat.formatString( item.ItemPrecioUnitario.ToString( ) , Align.Right , 8 ) +
                                      strFormat.formatString( item.ItemImporte.ToString( ) , Align.Right , 8 ) );
                }

            }
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.fillString('-', maxTextWidth));
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.formatString("MONTO PARCIAL BS.:" +
                                                          strFormat.formatString(factura.TotalFactura.ToString(), Align.Right, 9) + " "
                                                          , Align.Right, maxTextWidth));
            streamToFill.WriteLine( );
            streamToFill.WriteLine(strFormat.formatString("DESCUENTO BS.:" +
                                                         strFormat.formatString(descuento.ToString(), Align.Right, 9) + " "
                                                         , Align.Right, maxTextWidth));
            streamToFill.WriteLine( );
            streamToFill.WriteLine(strFormat.formatString("TOTAL Bs.:" +
                                                          strFormat.formatString((factura.TotalFactura-descuento).ToString(), Align.Right, 9) + " "
                                                          , Align.Right, maxTextWidth));
            streamToFill.WriteLine( );

            items = TextWrapper( literal , 35 );
            idx = 0;

            // If we wrapped the literal text and it contains more than one line, we need to procees it one by one.
            if ( items.Count > 1 )
            {
                foreach ( var itemNames in items )
                {
                    if ( idx == 0 )
                        streamToFill.WriteLine( "SON: " + itemNames );
                    else
                    {
                        streamToFill.WriteLine( );
                        streamToFill.WriteLine( strFormat.formatString( " " , Align.Center , 4 ) + itemNames );
                    }

                    idx++;
                }
            }
            else
            {
                streamToFill.WriteLine( "SON: " + literal );
            }

            streamToFill.WriteLine( );
        }
예제 #34
0
 public bool Update(Factura entity)
 {
     return(facturaRepository.Update(entity));
 }
        public ActionResult Create(FacturaView fvv)
        {
            decimal c  = 0;
            var     ff = Session["FacturaI"] as FacturaView;

            fvv.factList = ff.factList;
            foreach (var item in ff.factList)
            {
                c += decimal.Parse(item.precio.ToString());
            }
            Factura insF     = fvv.factEncab;
            var     clientes = db.Clientes.ToList();

            foreach (var item in clientes)
            {
                if (item.nit.Equals(insF.nitFactura))
                {
                    insF.cliente       = item.id;
                    insF.nombreFactura = item.nombrePersona + " " + item.apellidoPersona;
                    break;
                }
            }
            insF.estadoFactura = db.estadoFacturas.ToList().First().id;
            insF.vendedor      = int.Parse(Session["UserID"].ToString());
            insF.totalFactura  = c;
            insF.fechaFactura  = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            db.Factura.Add(insF);
            db.SaveChanges();
            insF = db.Factura.ToList().Last();
            foreach (var item in fvv.factList)
            {
                DetalleFactura df = new DetalleFactura();
                df.codigoFactura    = insF.id;
                df.codigoInventario = item.codigoInventario;
                df.precio           = item.precio;
                db.DetalleFactura.Add(df);
                db.SaveChanges();
            }
            InOut io = new InOut();

            io.descripcion   = "Salida por factura generada";
            io.fechaInOut    = insF.fechaFactura;
            io.tipoInOut     = 2;
            io.cantidadInOut = fvv.factList.Count;
            int eje = int.Parse(Session["UserID"].ToString());
            int ub  = int.Parse((from q in db.EmployeeBodega
                                 where q.idUsuario == eje
                                 select q).ToList().First().idBodega.ToString());

            io.ubicacionInOut = ub;
            db.InOut.Add(io);
            db.SaveChanges();
            io = db.InOut.ToList().Last();
            List <DetalleInOutP> dip = new List <DetalleInOutP>();

            foreach (var item in fvv.factList)
            {
                bool creador = true;
                int  proc    = int.Parse((from q in db.Inventario
                                          where q.id == item.codigoInventario
                                          select q).ToList().First().codigoProducto.ToString());
                foreach (var item1 in dip)
                {
                    if (item1.codigoProducto == proc)
                    {
                        item1.cantidadP++;
                        creador = false;
                    }
                }
                if (creador)
                {
                    DetalleInOutP dop = new DetalleInOutP();
                    dop.inoutType      = false;
                    dop.codigoProducto = proc;
                    dop.cantidadP      = 1;
                    dop.coidgoInOut    = io.id;
                    dip.Add(dop);
                }
            }
            foreach (var item in dip)
            {
                db.DetalleInOutP.Add(item);
                db.SaveChanges();
                var ite = db.DetalleInOutP.ToList().Last();
                foreach (var item1 in fvv.factList)
                {
                    int proc = int.Parse((from q in db.Inventario
                                          where q.id == item1.codigoInventario
                                          select q).ToList().First().codigoProducto.ToString());
                    if (proc == ite.codigoProducto)
                    {
                        DetalleInOut dit = new DetalleInOut();
                        dit.coidgoInOut    = ite.id;
                        dit.codigoProducto = item1.codigoInventario;
                        dit.cantidad       = 1;
                        db.DetalleInOut.Add(dit);
                        db.SaveChanges();
                    }
                }
            }
            foreach (var item in fvv.factList)
            {
                db.inveVendido(item.codigoInventario);
            }
            ViewBag.cliente       = new SelectList(db.Clientes, "id", "nombrePersona");
            ViewBag.estadoFactura = new SelectList(db.estadoFacturas, "id", "nombreEstado");
            ViewBag.vendedor      = new SelectList(db.Usuarios, "id", "nombrePersona");
            ViewBag.fechaI        = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
            ViewBag.totalI        = 0;
            FacturaView fv = new FacturaView();

            fv.factEncab        = new Factura();
            fv.Titulos          = new FacturaDetalle();
            fv.factList         = new List <FacturaDetalle>();
            Session["FacturaI"] = fv;
            Session["ProductI"] = new List <Inventario>();
            return(RedirectToAction("Create"));
        }
예제 #36
0
        static void Main_(string[] args)
        {
            string datilApiFacturaUrl = "https://link.datil.co/invoices/";

            // Credenciales del requerimiento
            string myApiKey   = "xxxx";
            string myPassword = "******";

            // Crear requerimiento
            var requestOptions = new RequestOptions();

            requestOptions.ApiKey   = myApiKey;
            requestOptions.Password = myPassword;
            requestOptions.Url      = datilApiFacturaUrl + "issue";

            // Información del comprador (Obligatorio)
            Comprador comprador = new Comprador("Juan Pérez", "0989898921001", "04", "*****@*****.**", "Calle única Numero 987", "046029400");

            // Información del establecimiento (Obligatorio)
            Establecimiento establecimiento = new Establecimiento("001", "002", "Av. Primera 234 y calle 5ta");

            // Información del emisor. Necesita de un Establecimiento. (Obligatorio)
            Emisor emisor = new Emisor("0910000000001", "GUGA S.A. ", "XYZ Corp", "Av.Primera 234 y calle 5ta", "12345", true, establecimiento);

            // Detalle de la factura y sus impuestos. (Obligatorio)
            var  items = new List <Item>();
            Item item  = new Item("ZNC", "050", "Zanahoria granel 50 Kg.", 622.0, 7.01, 4360.22, 0.0);

            item.PrecioSinSubsidio = 600.0;
            var detallesAdicionales = new Dictionary <string, string>();

            detallesAdicionales.Add("Peso", "5000"); //  agregar más detalles al item de ser necesario
            item.DetallesAdicionales = detallesAdicionales;
            var impuestos = new List <ImpuestoItem>();

            impuestos.Add(new ImpuestoItem("2", "2", 4359.54, 523.14, 12.0)); // agregar más impuestos al item de ser necesario
            item.Impuestos = impuestos;
            items.Add(item);                                                  //agregar más items a la lista de ser necesario

            // Total de la factura con sus impuestos. (Obligatorio)
            var totales = new TotalesFactura(4359.54, 4882.68, 0.0, 0.0);

            totales.TotalSubsidio = 22.00;
            var impuestosDeTotal = new List <Impuesto>();

            impuestosDeTotal.Add(new Impuesto("2", "0", 0.0, 0.0));
            impuestosDeTotal.Add(new Impuesto("2", "2", 4359.54, 523.14)); // agregar más impuestos a la lista de ser necesario.
            totales.Impuestos = impuestosDeTotal;

            // Retenciones en la factura

            /*      Caso específico de Retenciones en la Comercializadores / Distribuidores
             *      de derivados del Petróleo y Retención presuntiva de IVA a los Editores,
             *      Distribuidores y Voceadores que participan en la comercialización
             *      de periódicos y/ o revistas.
             */
            var retenciones            = new List <RetencionFactura>();
            RetencionFactura retencion = new RetencionFactura("4", "327", 0.20, 0.13);

            retenciones.Add(retencion);
            RetencionFactura retencion2 = new RetencionFactura("4", "327", 0.20, 0.13);

            retenciones.Add(retencion2);

            // Creación del objeto factura
            Factura factura = new Factura();

            // Cabecera de la factura
            factura.Secuencial  = "1613";
            factura.Moneda      = "USD";
            factura.Ambiente    = 1;
            factura.TipoEmision = 1;

            DateTime today  = DateTime.Today;
            var      offset = TimeZoneInfo.Local.GetUtcOffset(today);

            factura.FechaEmision = new DateTimeOffset(today, offset);
            //factura.Version =
            //factura.ClaveAcceso =
            //factura.GuiaRemision =

            // Completar informaciòn de la factura
            factura.Emisor      = emisor;
            factura.Comprador   = comprador;
            factura.Totales     = totales;
            factura.Items       = items;
            factura.Retenciones = retenciones;

            // Valores de retención de IVA y de Renta (Opcionales)
            factura.ValorRetIva   = 2.0;
            factura.ValorRetRenta = 0.10;

            //Métodos de pago  (Obligatorio)
            // Ejemplo de pagos sin propiedades adicionales
            factura.Pagos.Add(new MetodoPago("efectivo", 12.0));
            factura.Pagos.Add(new MetodoPago("transferencia_otro_banco", 8.0));
            // Ejemplo de pago con propiedades adicionales
            var pagoConDetalle = new MetodoPago("tarjeta_credito_nacional", 60.0);

            pagoConDetalle.Propiedades = new Dictionary <string, string>();
            pagoConDetalle.Propiedades.Add("Tipo tarjeta", "Visa");
            pagoConDetalle.Propiedades.Add("Diferido", "3 meses");
            factura.Pagos.Add(pagoConDetalle);

            // Credito otorgado al cliente (Opcional)
            var montoCredito = 10.50;
            // Crédito a 30 días a partir de la fecha de emisión. Formato 'yyyy-mm-dd'
            var fechaVencimientoCredito = factura.FechaEmision.Date.AddDays(30).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

            factura.Credito = new CreditoFactura(montoCredito, fechaVencimientoCredito);

            // Informaciòn adicional de la factura (Opcional)
            var infoAdicionalFactura = new Dictionary <string, string>();

            infoAdicionalFactura.Add("Tiempo de entrega", "5 días");
            factura.InformacionAdicional = infoAdicionalFactura;

            Console.WriteLine(factura.toJson());

            // Enviar factura
            var respuesta = factura.Enviar(requestOptions);

            Console.WriteLine("RESPUESTA:" + respuesta);

            // Obtener el id externo, para luego consultar el estado
            JObject json      = JObject.Parse(respuesta);
            string  idExterno = (string)json["id"];

            Console.WriteLine("ID EXTERNO: " + idExterno); //5832e2c370414663a1bea71938a65bf0

            // Consultar estado de la factura
            var requestOptions2 = new RequestOptions();

            requestOptions2.ApiKey   = myApiKey;
            requestOptions2.Password = myPassword;
            requestOptions2.Url      = datilApiFacturaUrl + idExterno;
            respuesta = Factura.Consultar(requestOptions2);
            json      = JObject.Parse(respuesta);
            string estado = (string)json["estado"];

            Console.WriteLine("ESTADO: " + estado); // RECIBIDO
        }
예제 #37
0
        static void Main(string[] args)
        {
            List <string> listacodigo      = new List <string>();
            List <string> listadescripcion = new List <string>();
            List <float>  listaprecio      = new List <float>();
            List <float>  listacantidad    = new List <float>();


            Cliente          cliente          = new Cliente();
            Factura          factura          = new Factura();
            Producto         producto         = new Producto();
            Factura_Producto factura_Producto = new Factura_Producto();
            float            subtotall        = 0;
            float            subtotall2       = 0;
            float            totalsiniva      = 0;
            float            iva   = 0;
            float            total = 0;


            Console.WriteLine("Ingrese el codigo de la factura");
            factura.CodigoFactura = Console.ReadLine();
            Console.WriteLine("Ingrese su identificacion");
            cliente.Identificacion = Console.ReadLine();
            Console.WriteLine("Ingrese su nombre");
            cliente.Nombre = Console.ReadLine();
            Console.WriteLine("Ingrese su dirección");
            cliente.Direccion = Console.ReadLine();
            Console.WriteLine("Ingrese su telefono");
            cliente.Telefono = int.Parse(Console.ReadLine());
            byte decicion = 1;

            while (decicion == 1)
            {
                Console.WriteLine("Ingrese codigo del producto");
                producto.Codigo = Console.ReadLine();
                listacodigo.Add(producto.Codigo);
                Console.WriteLine("Ingrese la descripcion del producto");
                producto.Descripcion = Console.ReadLine();
                listadescripcion.Add(producto.Descripcion);
                Console.WriteLine("Ingrese el precio del producto");
                producto.Precio = float.Parse(Console.ReadLine());
                listaprecio.Add(producto.Precio);
                Console.WriteLine("Ingrese la cantidad del producto");
                producto.Cantidad = int.Parse(Console.ReadLine());
                listacantidad.Add(producto.Cantidad);

                subtotall  = new Factura_Producto().CalcularSubtotal(producto.Precio, producto.Cantidad);
                subtotall2 = subtotall2 + subtotall;
                Console.WriteLine("¿Ingresara más productos?");
                Console.WriteLine("1. SI");
                Console.WriteLine("2. NO");
                decicion = byte.Parse(Console.ReadLine());
            }



            Console.WriteLine("Ingrese el descuento");
            factura.Descuento = float.Parse(Console.ReadLine());
            Console.WriteLine("________________________________________________________________________________");
            Console.WriteLine("Cliente: " + cliente.Nombre + "      Identificación: " + cliente.Identificacion);
            Console.WriteLine("Dirección: " + cliente.Direccion + "                  Telefono: " + cliente.Telefono);
            Console.WriteLine("________________________________________________________________________________");
            totalsiniva = new Factura_Producto().CalcularTotalsinIVA(subtotall2, factura.Descuento);
            iva         = new Factura_Producto().CalcularIVA(subtotall2);
            total       = new Factura_Producto().CalcularTotal(totalsiniva, iva);



            foreach (var item in listacodigo)
            {
                Console.WriteLine("Cod: " + item);
            }
            foreach (var item in listadescripcion)
            {
                Console.WriteLine("Descripción: " + item);
            }
            foreach (var item in listaprecio)
            {
                Console.WriteLine("Precio: " + item);
            }
            foreach (var item in listacantidad)
            {
                Console.WriteLine("Cantidad: " + item);
            }

            Console.WriteLine("subtotal: " + subtotall2);
            Console.WriteLine("Descuento: " + factura.Descuento);


            Console.WriteLine("Subtotal-Descuento: " + totalsiniva);

            Console.WriteLine("IVA: " + iva);

            Console.WriteLine("Total: " + total);
        }
예제 #38
0
 public void Add(Factura facturaToAdd)
 {
     Facturas.Add(facturaToAdd);
     Count++;
 }
예제 #39
0
 public void AgregarFactura(Factura factura)
 {
     ElContextoDeBaseDeDatos.Factura.Add(factura);
     ElContextoDeBaseDeDatos.SaveChanges();
 }
예제 #40
0
        private void botonDetalles_Click(object sender, EventArgs e)
        {
            Factura factura = dataGrid.SelectedRows[0].DataBoundItem as Factura;

            new FacturaDetallesForm(factura).Show();
        }
예제 #41
0
 private void ActualizarLista()
 {
     lstFactura.DataSource = null;
     lstFactura.DataSource = Factura.ObtenerFactura();
 }
예제 #42
0
        //Método para agregar una factura a  una tienda - Kevin

        /*public string AgregarFactura(Factura nuevaFactura)
         * {
         *  var result = db.Facturas.Add(nuevaFactura);
         *  db.SaveChanges();
         *  return "Factura agregada  " + result.Entity.IdFactura;
         * }
         */
        public string AgregarFactura(Factura nuevaFactura)
        {
            db.Tiendas.Find(nuevaFactura.TiendaID).Facturas.Add(nuevaFactura);
            db.SaveChanges();
            return("Factura agregada ");
        }
        public ActionResult GuardarVenta(string Fecha, string modoPago, string IdCliente, string Total, string usuario, List <DetalleVenta> ListadoDetalle)
        {
            string mensaje       = "";
            double iva           = 18;
            string idVendedor    = "321";
            int    codigoPago    = 0;
            long   codigoCliente = 0;
            double total         = 0;


            if (Fecha == "" || modoPago == "" || IdCliente == "" || Total == "")
            {
                if (Fecha == "")
                {
                    mensaje = "ERROR EN EL CAMPO FECHA";
                }
                if (modoPago == "")
                {
                    mensaje = "SELECCIONE UN MODO DE PAGO";
                }
                if (IdCliente == "")
                {
                    mensaje = "ERROR CON EL CODIGO DEL CLIENTE";
                }
                if (Total == "")
                {
                    mensaje = "ERROR EN EL CAMPO TOTAL";
                }
            }
            else
            {
                codigoPago    = Convert.ToInt32(modoPago);
                codigoCliente = Convert.ToInt64(IdCliente);
                total         = Convert.ToDouble(Total);

                //REGISTRO DE VENTA
                Venta  objVenta    = new Venta(total, codigoCliente, idVendedor, Fecha, iva);
                string codigoVenta = objVentaNeg.create(objVenta);
                if (codigoVenta == "" || codigoVenta == null)
                {
                    mensaje = "ERROR AL REGISTRAR LA VENTA";
                }
                else
                {
                    Session["idVenta"] = codigoVenta;
                    //REGISTRO DE FACTURA
                    Factura objFactura    = new Factura(Fecha, iva, total, codigoPago, usuario);
                    string  codigoFactura = objFacturaNeg.create(objFactura);
                    if (codigoFactura == "" || codigoFactura == null)
                    {
                        mensaje = "ERROR AL REGISTRAR LA FACTURA";
                    }
                    else
                    {
                        foreach (var data in ListadoDetalle)
                        {
                            string idProducto = data.IdProducto.ToString();
                            int    cantidad   = Convert.ToInt32(data.Cantidad.ToString());

                            if (objProductoNeg.ReduceInventario(int.Parse(data.IdProducto), cantidad))
                            {
                                double       descuento       = Convert.ToDouble(data.Descuento.ToString());
                                double       subtotal        = Convert.ToDouble(data.SubTotal.ToString());
                                DetalleVenta objDetalleVenta = new DetalleVenta(Convert.ToInt64(codigoFactura), Convert.ToInt64(codigoVenta), idProducto, subtotal, descuento, cantidad);
                                objDetalleVentaNeg.create(objDetalleVenta);
                            }
                            else
                            {
                                mensaje = "ERROR AL REGISTRAR LA FACTURA | REBAJAR PRODUCTO";
                                return(Json(mensaje));
                            }
                        }
                        mensaje = "VENTA GUARDADA CON EXITO...";
                    }
                }
            }

            return(Json(mensaje));
        }
        public ActionResult Factura(string Mesa, string Nombre)
        {
            //Recibir nombre del cliente y el ID de la Mesa
            int idMesa = Int32.Parse(Mesa);

            RegisterVM Cliente = new RegisterVM();

            Cliente.Password       = "******" + idMesa;
            Cliente.Nombre_Usuario = Nombre;

            //Se crea nuevo cliente
            Register(Cliente);

            Factura  nuevaFactura = new Factura();
            DateTime time         = DateTime.Now;


            //Encontrar el ultimo valor ingresado en el cliente (usaremos como demo el 6)
            //Encontrar el ultimo del usuario actual (usaremos como demo el 1)-- Mesero que utiliza el programa UsuarioLogueado.IdUsuario
            //Usar el ID de la mesa.

            /*Datos del vendedor*/
            var     usuario  = Session["Data"];
            Usuario logueado = (Usuario)usuario;

            Usuario cliente = new Usuario();


            /*Datos del cliente recien creado*/
            using (var context = new ContextDB())
            {
                cliente = context.Usuario.OrderByDescending(x => x.idUsuario).FirstOrDefault();
            }


            nuevaFactura.idMesa     = idMesa;
            nuevaFactura.Fecha      = time;
            nuevaFactura.idCliente  = cliente.idUsuario;
            nuevaFactura.idVendedor = logueado.idUsuario;

            using (var context = new ContextDB())
            {
                //Tomar valores de la mesa a actualizar
                var mesaUpdate = context.Mesas.SingleOrDefault(b => b.idMesa == idMesa);

                //Establecer nuevo estao de la mesa
                mesaUpdate.Disponible = 1;

                //Agregar nueva factura
                context.Factura.Add(nuevaFactura);
                context.SaveChanges();
            }


            Factura factura = new Factura();

            /*Datos de la Factura recien creado*/
            using (var context = new ContextDB())
            {
                factura = context.Factura.OrderByDescending(x => x.idFactura).FirstOrDefault();
            }


            return(RedirectToAction("MenuPage", "Receptionist", factura));
        }
예제 #45
0
        public void fillStreamWithData(ref StreamWriter streamToFill,
                                      Int16 maxTextWidth,
                                      String nombreEmpresa,
                                      String razonSocial,
                                      String sucursal,
                                      String direccion,
                                      String rubro,
                                      String telefono,
                                      String departamento,
                                      String nit,
                                      String facturaNro,
                                      String autorizacionNro,
                                      String fecha,
                                      String clienteNombre,
                                      String clienteNit,
                                      Factura factura,
                                      String literal,
                                      String codigoControl,
                                      String fechalimite,
                                        double descuento)
        {
            //streamToFill.WriteLine(strFormat.formatString(strFormat.fillString('X', 90), Align.Left, 90));             

            #region datos A Empresa
            fillDatosAEmpresa(ref streamToFill, maxTextWidth, nombreEmpresa, razonSocial, sucursal, direccion, telefono, departamento);
            #endregion

            #region Texto Estatico
            streamToFill.WriteLine(strFormat.formatString("FACTURA ORIGINAL", Align.Center, maxTextWidth));
            streamToFill.WriteLine(strFormat.formatString(strFormat.fillString('-', 34), Align.Center, maxTextWidth));
            #endregion

            #region datos A Facturacion
            fillDatosAFacturacion(ref streamToFill, maxTextWidth, nit, facturaNro, autorizacionNro);
            streamToFill.WriteLine(strFormat.formatString(strFormat.fillString('-', 34), Align.Center, maxTextWidth));
            #endregion

            #region datos A Cliente
            if (!String.IsNullOrEmpty(rubro))
            {
                fillRubroEmpresa(ref streamToFill, rubro, maxTextWidth);
                streamToFill.WriteLine();
            }
            fillDatosACliente(ref streamToFill, maxTextWidth, fecha, clienteNombre, clienteNit);
            #endregion

            #region factura Items
            fillFacturaItems(ref streamToFill, maxTextWidth, factura, literal,descuento);
            #endregion

            #region codigo Control
            streamToFill.WriteLine( );
            streamToFill.WriteLine("CODIGO DE CONTROL: " + codigoControl);
            #endregion

            #region fecha limite emision
            streamToFill.WriteLine( );
            streamToFill.WriteLine("FECHA LIMITE DE EMISION:" + fechalimite);
            #endregion

            #region pie de pagina
            streamToFill.WriteLine();

            streamToFill.WriteLine(strFormat.formatString("\"ESTA FACTURA CONTRIBUYE AL DESARROLLO", Align.Left, maxTextWidth));
           // streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.formatString("DEL PAIS.EL USO ILICITO DE ESTA SERA", Align.Left, maxTextWidth));
           // streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.formatString("SANCIONADO DE ACUERDO A LEY\"", Align.Left, maxTextWidth));
           // streamToFill.WriteLine();
            fillPiePaginaLeyenda(ref streamToFill, "Ley No. 453: Los productos deben suministrarse en condiciones de inocuidad, calidad y seguridad.", maxTextWidth);
            /*
            streamToFill.WriteLine(strFormat.formatString("\"LA ALTERACIÓN, FALSIFICACIÓN O", Align.Left, maxTextWidth));
            streamToFill.WriteLine(strFormat.formatString("COMERCIALIZACIÓN ILEGAL DE ESTE", Align.Left, maxTextWidth));
            streamToFill.WriteLine(strFormat.formatString("DOCUMENTO, TIENE CÁRCEL\"", Align.Left, maxTextWidth));
            */
 /*
            streamToFill.WriteLine(strFormat.formatString("\"La reproduccion total o parcial y/o el", Align.Center, maxTextWidth));
            streamToFill.WriteLine(strFormat.formatString("uso no autorizado de esta Nota Fiscal", Align.Center, maxTextWidth));
            streamToFill.WriteLine(strFormat.formatString("constituye un delito a ser sancionado", Align.Center, maxTextWidth));
            streamToFill.WriteLine(strFormat.formatString("conforme a la Ley\"", Align.Center, maxTextWidth));
  */
            streamToFill.WriteLine(strFormat.fillString('-', maxTextWidth));
            streamToFill.WriteLine( );
            streamToFill.WriteLine(strFormat.formatString("GRACIAS POR SU PREFERENCIA", Align.Center, maxTextWidth));
      
            #endregion
        }
예제 #46
0
        public JsonResult ProcesarFactura(int IdCliente, int? IdCotizacion, decimal MontoPagar, decimal Montototal)
        {
            var respuesta = "Factura Registrada!";
            try
            {
                if (TempData["ListaProductosFact"] != null)
                {
                    ListaProductos = (List<ProductoCotizacion>)TempData["ListaProductosFact"];
                }

                if (ListaProductos.Count()>0)
                {
                    Factura Fact = new Factura();
                    Fact.IdCliente = IdCliente;
                    if (IdCotizacion != null)
                    {
                        Fact.IdCotizacion = IdCotizacion;
                        Cotizacion Cotiz = db.Cotizacion.Find(IdCotizacion);
                        Cotiz.Estado = "F";
                        Cotiz.FechaActualizacion = DateTime.Now;
                        db.Entry(Cotiz).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        Fact.IdCotizacion = null;
                    }

                    Fact.FechaHora = DateTime.Now;
                    Fact.Usuario = Session["UsuarioActual"].ToString();
                    Fact.Estado=1;
                    Fact.MontoTotal = Montototal;
                    Fact.MontoPagar = MontoPagar;
                    db.Factura.Add(Fact);
                    db.SaveChanges();
                    TempData["Fecha"] = Fact.FechaHora;
                    TempData["Cliente"] =db.Cliente.Find(Fact.IdCliente).Nombre;
                    foreach (var item in ListaProductos)
                    {
                        DetalleFactura D1 = new DetalleFactura();
                        D1.IdFactura = Fact.IdFactura;
                        D1.IdProducto = item.IdProducto;
                        D1.IdColor = item.IdColor;
                        D1.MontoParcial = item.Subtotal;
                        D1.Cantidad = item.CantMat;
                        db.DetalleFactura.Add(D1);
                    }
                    db.SaveChanges();
                    TempData["IdFactura"] = Fact.IdFactura;
                }
                else
                {
                    respuesta = "Debe Agregar Productos a la Factura!";
                }
            }
            catch (Exception e)
            {
                respuesta = "Un error inesperado a ocurrido, contacte al administrador del sistema\n\n" + e;
                return Json(respuesta,
              JsonRequestBehavior.AllowGet);
            }
            TempData["ListaProductosFact"] = ListaProductos;
            return Json(respuesta,
             JsonRequestBehavior.AllowGet);
        }
예제 #47
0
        public void GuardarFactura(Factura fact)
        {
            var datosFactura = new Dfactura();

            datosFactura.PostInsertFactura(fact);
        }
예제 #48
0
    // Funcion para realizar la factura
    public void facturacion()
    {
        Console.Clear();
        Console.WriteLine("BIENVENIDO (A) AL SISTEMA");
        Console.WriteLine("-------------------------");
        Console.WriteLine("");

        Console.WriteLine("Ingrese el codigo del Cafe Tender: ");
        string nuevoCodigoCafeTender = Console.ReadLine();

        CafeTender cafeTender = ListadeCafeTender.Find(c => c.CodigoCafeTender.ToString() == nuevoCodigoCafeTender);

        if (cafeTender == null)
        {
            Console.WriteLine("Cafe Tender no encontrado: ");
            Console.ReadLine();
            //return;
        }
        else
        {
            Console.WriteLine("Nombre Completo: " + cafeTender.Nombre + " | " + cafeTender.Apellido + " Codigo: " + cafeTender.CodigoCafeTender);
            Console.ReadLine();
            Console.WriteLine("");
        }

        int nuevoCodigo = ListadeFacturas.Count + 1;

        Factura factura = new Factura(nuevoCodigo, DateTime.Now, "Express", cafeTender);

        ListadeFacturas.Add(factura);

        //Ciclo while (true) este nos dira si deseamos realizar pedidos

        while (true)
        {
            Console.WriteLine("Ingrese el numero de orden de su pedido: ");
            string nuevoPedido = Console.ReadLine();

            InventarioCafe inventarioCafe = ListadeInventario.Find(ci => ci.NoOrden.ToString() == nuevoPedido);

            if (inventarioCafe == null)
            {
                Console.WriteLine("Pedido no encontrado: ");
                Console.ReadLine();
                //return;
            }
            else
            {
                Console.WriteLine("Descripcion: " + inventarioCafe.Nombre + " Precio: " + inventarioCafe.Precio + " Tipo: " + inventarioCafe.Tipo);
                factura.agregarPedido(inventarioCafe);         //Invocar funcion agregarPedido
                Console.WriteLine("");
            }

            Console.WriteLine("");
            Console.WriteLine("Realizar otro pedido? Presione s/n");
            string realizarPedido = Console.ReadLine();
            if (realizarPedido.ToLower() == "n")
            {
                break;
            }
        }

        Console.WriteLine("");
        Console.WriteLine("Subtotal: " + factura.Subtotal);
        Console.WriteLine("ISV - Impuesto: " + factura.Isv);
        Console.WriteLine("Total: " + factura.Total);
        Console.WriteLine("GRACIAS POR PREFERIRNOS, BRINDANDO CALIDAD A SU PALADAR");
        Console.ReadLine();

        /*Console.WriteLine("Ingrese efectivo pagado: "); PENDIENTE
         * factura.ValorPago = Console.ReadLine();
         * Console.WriteLine("Cambio: " + factura.Cambio);
         * Console.ReadLine();*/
    }
예제 #49
0
        //Cierra el pedido
        private void CrearPedido_Click(object sender, EventArgs e)
        {
            string nombre = textoNombre.Text;
            string direccion;

            if (checkBox2.Checked)
            {
                direccion = textDireccion.Text;
            }
            else
            {
                direccion = "Retira en persona";
            }
            string estado = comboEstado.Text;
            string pagado = "no";

            if (checkBox1.Checked)
            {
                pagado = "si";
            }

            if (ValidarPedido(nombre, direccion, estado))
            {
                //Cuenta la cantidad de productos sumados al pedido para recorrer la lista de productos
                int productosContador = pedido.Rows.Count;
                //Toma un producto y lo pone en un texto (después de mostrará por pantalla)
                string productosTexto = " ";
                //Cuenta todo para el precio final
                int productosPrecioFinal = 0;

                for (int i = 0; i < productosContador; i++)
                {
                    string cant   = pedido.Rows[i]["Cantidad"].ToString();
                    string precio = pedido.Rows[i]["Precio"].ToString();
                    productosPrecioFinal = productosPrecioFinal + (Int32.Parse(precio) * Int32.Parse(cant));


                    productosTexto = String.Concat(pedido.Rows[i]["Producto"].ToString() + " ");
                }


                MessageBox.Show("PEDIDO CREADO \n"
                                + "Nombre: "
                                + nombre
                                + "\n"
                                + "Entrega: "
                                + direccion
                                + "\n"
                                + "Pagado: "
                                + pagado
                                + "\n"
                                + "Estado: "
                                + estado
                                + "\n"
                                //+ "PEDIDOS: \n"
                                //+ listBox1.Text.ToString()
                                + "TOTAL: "
                                + productosPrecioFinal

                                );
                // Agrego los datos del pedido a la facturaciòn
                Factura  f              = new Factura();
                DateTime fecha          = DateTime.Today;
                string   fechaParametro = fecha.ToString();

                //agrego un int cualquiera al codigo pedido
                int codPedido = productosPrecioFinal + 1000;

                if (f.AgregarFactura(codPedido, productosPrecioFinal, fechaParametro) == true)
                {
                    MessageBox.Show("Factura creada con exito");
                }
                else
                {
                    MessageBox.Show("Error al generar la factura");
                }
            }
        }
예제 #50
0
        private void cmbFactura_SelectedIndexChanged(object sender, EventArgs e)
        {
            int aux = cmbFactura.SelectedIndex;

            if (aux != -1)
            {
                string numFactura = facturasTransito.Rows[aux]["numFacturaTransito"].ToString();
                equiposFacturaTransito = facturaDA.CargarEquiposFacturaConCodigo(numFactura);

                facturas = new BindingList <Factura>();
                int rec = 0;
                while (rec < equiposFacturaTransito.Rows.Count)
                {
                    Factura fact = new Factura();
                    fact.IdFacturaTransito = Convert.ToInt32(equiposFacturaTransito.Rows[rec]["idFacturaTransito"].ToString());

                    fact.CodigoLC        = equiposFacturaTransito.Rows[rec]["codigoEquipo"].ToString();
                    fact.FechaPago       = Convert.ToDateTime(equiposFacturaTransito.Rows[rec]["fecEmisiom"].ToString());
                    fact.FechaIniPago    = (equiposFacturaTransito.Rows[rec]["fecIniPago"] is DBNull) ? Convert.ToDateTime("1/01/1900 00:00:00") : Convert.ToDateTime(equiposFacturaTransito.Rows[rec]["fecIniPago"].ToString());
                    fact.FechaFinPago    = (equiposFacturaTransito.Rows[rec]["fecFinPago"] is DBNull) ? Convert.ToDateTime("1/01/1900 00:00:00") : Convert.ToDateTime(equiposFacturaTransito.Rows[rec]["fecFinPago"].ToString());
                    fact.RucDni          = equiposFacturaTransito.Rows[rec]["ruc"].ToString();
                    fact.RazonSocial     = equiposFacturaTransito.Rows[rec]["razonSocial"].ToString();
                    fact.NumeroOC        = equiposFacturaTransito.Rows[rec]["numeroOC"].ToString();
                    fact.NumeroDocRef    = equiposFacturaTransito.Rows[rec]["guiaSalida"].ToString();
                    fact.NumeroFactura   = equiposFacturaTransito.Rows[rec]["numFacturaTransito"].ToString();
                    fact.TotalSoles      = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["totalSoles"].ToString());
                    fact.TotalDolares    = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["totalDolares"].ToString());
                    fact.CostoSoles      = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["costoSoles"].ToString());
                    fact.CostoDolares    = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["costoDolares"].ToString());
                    fact.CantidadEquipos = Convert.ToInt32(equiposFacturaTransito.Rows[rec]["cantidadEquipos"].ToString());
                    fact.TipoCambio      = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["tipoCambio"].ToString());

                    fact.TotalSolesAntiguo   = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["totalSoles"].ToString());
                    fact.TotalDolaresAntiguo = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["totalDolares"].ToString());
                    fact.CostoSolesAntiguo   = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["costoSoles"].ToString());
                    fact.CostoDolaresAntiguo = Convert.ToDouble(equiposFacturaTransito.Rows[rec]["costoDolares"].ToString());

                    fact.TipoFacturaTransito = 1;

                    rec++;
                    facturas.Add(fact);
                }

                equiposFacturaTransito = facturaDA.CargarEquiposFacturaConCodigoGenerico(numFactura);

                if (equiposFacturaTransito.Rows.Count > 0)
                {
                    int auxCantidad = Convert.ToInt32(equiposFacturaTransito.Rows[0]["cantidadEquipos"].ToString());
                    rec = 0;
                    while (rec < auxCantidad)
                    {
                        Factura fact = new Factura();
                        fact.IdFacturaTransito = Convert.ToInt32(equiposFacturaTransito.Rows[0]["idFacturaTransito"].ToString());

                        fact.CodigoLC        = "";
                        fact.FechaPago       = Convert.ToDateTime(equiposFacturaTransito.Rows[0]["fecEmisiom"].ToString());
                        fact.FechaIniPago    = (equiposFacturaTransito.Rows[0]["fecIniPago"] is DBNull) ? Convert.ToDateTime("1/01/1900 00:00:00") : Convert.ToDateTime(equiposFacturaTransito.Rows[0]["fecIniPago"].ToString());
                        fact.FechaFinPago    = (equiposFacturaTransito.Rows[0]["fecFinPago"] is DBNull) ? Convert.ToDateTime("1/01/1900 00:00:00") : Convert.ToDateTime(equiposFacturaTransito.Rows[0]["fecFinPago"].ToString());
                        fact.RucDni          = equiposFacturaTransito.Rows[0]["ruc"].ToString();
                        fact.RazonSocial     = equiposFacturaTransito.Rows[0]["razonSocial"].ToString();
                        fact.NumeroOC        = equiposFacturaTransito.Rows[0]["numeroOC"].ToString();
                        fact.NumeroDocRef    = equiposFacturaTransito.Rows[0]["guiaSalida"].ToString();
                        fact.NumeroFactura   = equiposFacturaTransito.Rows[0]["numFacturaTransito"].ToString();
                        fact.TotalSoles      = Convert.ToDouble(equiposFacturaTransito.Rows[0]["totalSoles"].ToString()) / auxCantidad;
                        fact.TotalDolares    = Convert.ToDouble(equiposFacturaTransito.Rows[0]["totalDolares"].ToString()) / auxCantidad;
                        fact.CostoSoles      = Convert.ToDouble(equiposFacturaTransito.Rows[0]["costoSoles"].ToString()) / auxCantidad;
                        fact.CostoDolares    = Convert.ToDouble(equiposFacturaTransito.Rows[0]["costoDolares"].ToString()) / auxCantidad;
                        fact.TipoCambio      = Convert.ToDouble(equiposFacturaTransito.Rows[0]["tipoCambio"].ToString());
                        fact.CantidadEquipos = 1;

                        fact.TipoFacturaTransito = 1;//Esto es para cuando se use la funcion de InsertarFactura se ejecute solo en esta parte

                        rec++;
                        facturas.Add(fact);
                    }
                }

                dgvEquiposCodigos.DataSource = facturas;
                vistaCodigo.OptionsBehavior.AutoPopulateColumns = false;
                vistaCodigo.OptionsSelection.MultiSelect        = true;
                vistaCodigo.RefreshData();
            }
            else
            {
                dgvEquiposCodigos.DataSource = null;
                facturas = new BindingList <Factura>();
            }
        }
예제 #51
0
 public bool Save(Factura entity)
 {
     return(facturaRepository.Save(entity));
 }
예제 #52
0
        public void insertarNodo(Factura factura)
        {
            documento = new XmlDocument();
            if (!File.Exists(fichero))
            {

                XmlDeclaration declaracion = documento.CreateXmlDeclaration("1.0", "UTF-8", null);
                documento.AppendChild(declaracion);
                raiz = documento.CreateElement("Facturas");
                documento.AppendChild(raiz);
            }
            else
            {
                documento.Load(fichero);
                raiz = documento.DocumentElement;
            }

            raiz.AppendChild(crearNodo(factura));

            documento.Save(fichero);
        }
예제 #53
0
        public static String comprar(Factura F, List<DtoProductoVenta> lista)
        {
            SqlConnection cn = new SqlConnection();
            SqlTransaction tran = null;
            String resultado;
            try
            {
                cn.ConnectionString = cadenaConex;
                cn.Open();
                tran = cn.BeginTransaction();
                string consulta = "INSERT INTO Facturas(numero,tipo,fecha,idDeportista,montoTotal) VALUES(@numero,@tipo,@fecha,@idDeportista,@montoTotal)";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = consulta;
                cmd.Connection = cn;
                cmd.Transaction = tran;
                cmd.Parameters.AddWithValue("@numero", F.numero);
                cmd.Parameters.AddWithValue("@tipo", F.tipo);
                cmd.Parameters.AddWithValue("@fecha", F.fecha);
                cmd.Parameters.AddWithValue("@idDeportista", F.deportista.IdDeportista);
                cmd.Parameters.AddWithValue("@montoTotal", F.montoTotal);
                cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();
                string consulta4 ="SELECT TOP 1 idFactura FROM Facturas ORDER BY idFactura DESC";
                cmd.CommandText = consulta4;
                cmd.Connection = cn;
                int idFactura = (int)cmd.ExecuteScalar();

                foreach (DtoProductoVenta dto in lista)
                {
                    cmd.Parameters.Clear();
                    string consulta2 = "SELECT idProducto FROM Productos WHERE codigoBarra = @codigoBarra";
                    cmd.CommandText = consulta2;
                    cmd.Connection = cn;
                    cmd.Parameters.AddWithValue("@codigoBarra", dto.codigoBarra);
                    int idProducto = (int)cmd.ExecuteScalar();

                    cmd.Parameters.Clear();
                    string consulta3 = "INSERT INTO DetallesFactura(cantidad,precio,idFactura,idProducto) VALUES(@cantidad,@precio,@idFactura,@idProducto)";
                    cmd.CommandText = consulta3;
                    cmd.Connection = cn;
                    cmd.Transaction = tran;
                    cmd.Parameters.AddWithValue("@cantidad", dto.cantidad);
                    cmd.Parameters.AddWithValue("@precio", dto.precio);
                    cmd.Parameters.AddWithValue("@idFactura", idFactura );
                    cmd.Parameters.AddWithValue("@idProducto", idProducto);
                    cmd.ExecuteNonQuery();

                    cmd.Parameters.Clear();
                    string consulta5 = "UPDATE Productos SET stock= stock - @cantidad WHERE idProducto=@idProducto";
                    cmd.CommandText = consulta5;
                    cmd.Connection = cn;
                    cmd.Transaction = tran;
                    cmd.Parameters.AddWithValue("@cantidad", dto.cantidad);
                    cmd.Parameters.AddWithValue("@idProducto", idProducto);
                    cmd.ExecuteNonQuery();

                }
                tran.Commit();
                resultado = "Transaccion exitosa!";

            }
            catch (SqlException E)
            {
                throw new ApplicationException("Error sql al guardar la transaccion." + E.ToString());

                if (cn.State == ConnectionState.Open)
                    resultado = "Transaccion erronea!";
                    tran.Rollback();
            }
            finally
            {
                if (cn.State == ConnectionState.Open)
                    cn.Close();

            }
            return resultado;
        }
예제 #54
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (txtTotal.Text == string.Empty)
            {
                errorProvider1.SetError(txtTotal, "Debe existir una totalidad");
            }
            else
            {
                using (Entidades context = new Entidades())
                {

                    Llenar_lista_con_otra();

                    Factura oFactura = new Factura()
                    {

                        CodFactura = Convert.ToInt32(dgFactura.CurrentRow.Cells[0].Value.ToString()),
                        Fecha = dtFecha.Value,
                        Ciudad = cbCiudad.Text,
                        ValorTotal = Convert.ToDecimal(txtTotal.Text),
                        DetalleFactura = Productos
                    };
                    context.Factura.Add(oFactura);
                    context.SaveChanges();
                    MessageBox.Show("Factura registrada correctamente");
                    dgFactura.Rows.Clear();
                    dgFactura.Refresh();
                    txtTotal.Text = "";
                    cbProducto.SelectedIndex = 0;
                    cbCiudad.SelectedIndex = 0;
                    dtFecha.Value = DateTime.Now;
                }
            }
        }
예제 #55
0
        private void buildFacturaOBject()
        {
            factura = new Factura();
            
            List<DataRow> listaPedidos = dataTable.AsEnumerable().ToList();
            ItemFactura itemFactura;
            foreach (DataRow item in listaPedidos)
            {
    //            "(PedidoId,ProductoId,Cantidad,Total,CostoReceta,PrecioProducto,Descripcion) values('" + pedidoId + "','" + item["Id"] + "','" + item["Cantidad"] + "','" + item["Subtotal"] + "','" + costoReceta + "','" + item["Precio"] + "','" + item["Descripcion"] + "')";
 //('" + pedidoId + "','" + item["Id"] + "','" + item["Cantidad"] + "','" + item["Subtotal"] + "','" + "','" + item["Precio"] + "','" "')";
                double importeTotal=0.0;
                double precio = 0.0;
                int cantidadPedido = 0;
                short idItem = 0;
                double.TryParse(item["Subtotal"].ToString(),out importeTotal );
                double.TryParse(item["Precio"].ToString(), out precio);
                int.TryParse(item["Cantidad"].ToString(), out cantidadPedido);
                short.TryParse(item["Id"].ToString(), out idItem);
                itemFactura = new ItemFactura(idItem, item["Articulo"].ToString(), precio, cantidadPedido, importeTotal);
                factura.addItem(itemFactura);
            }
 
        }
예제 #56
0
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            ProyectoFinal.BD.ProyectoFinal db = new BD.ProyectoFinal();
            Factura fac = new Factura();

            fac.ServicioServicioId = (int)cbser.SelectedValue;
            fac.Fecha = DateTime.Now;
            fac.AsistenteAsistenteId = (int)cbasis.SelectedValue;
            fac.ProveedorIdProveedor = (int)cbpro.SelectedValue;

            //actualizaGrid();
            db.Factura.Add(fac);
            db.SaveChanges();
            MessageBox.Show("Se Guardaron los datos");
            CleanUp();
        }
예제 #57
-1
        public void fillDetalle(ref StreamWriter streamToFill, Int16 maxTextWidth, Factura factura, string numeroPedido)
        {
            streamToFill.WriteLine(strFormat.formatString("Nro Pedido: "+numeroPedido,Align.Left,maxTextWidth));
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.fillString('-', maxTextWidth));
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.formatString("CANT", Align.Left, 4) +
                                   strFormat.formatString("CONCEPTO", Align.Center, 16) +
                                   strFormat.formatString("PRECIO", Align.Right, 8)                                   
                                   );
            streamToFill.WriteLine();
            streamToFill.WriteLine(strFormat.fillString('-', maxTextWidth));

            foreach (ItemFactura item in factura.Items)
            {
                streamToFill.WriteLine();
                streamToFill.WriteLine(strFormat.formatString(item.ItemCantidad.ToString(), Align.Center, 4) +
                                   strFormat.formatString(item.ItemNombre, Align.Left, 16) +
                                   strFormat.formatString(item.ItemPrecioUnitario.ToString(), Align.Right, 8));
            }

            streamToFill.WriteLine( );
            streamToFill.WriteLine( strFormat.formatString( "-" , Align.Center , maxTextWidth ) );
            streamToFill.WriteLine( );
        }
예제 #58
-1
        private void btn_registrar_Click(object sender, EventArgs e)
        {
            int count_dgv = dgv_factura.Rows.Count - 1;
                for (int x = 0; x <= count_dgv; x++)
                {

                    int id,cant;
                    string nompro;
                    decimal pre;
                    id = int.Parse(dgv_factura.Rows[x].Cells[5].Value.ToString());

                    nompro = dgv_factura.Rows[x].Cells[1].Value.ToString();

                    pre = decimal.Parse( dgv_factura.Rows[x].Cells[2].Value.ToString());
                    cant = int.Parse(dgv_factura.Rows[x].Cells[3].Value.ToString());
                    //Insertar

                    var fac = new Factura();

                    if (fac.add(id,nompro,pre,cant))
                    {

                    }

                }
        }
예제 #59
-1
        public void FacturaConUnProductGetTotal()
        {
            Factura factura = new Factura();
            Producto producto = new Producto(10);
            factura.AddProducto(producto, 2);

            Assert.AreEqual(20, factura.GetTotal());
        }