public void ConcederEmprestimo(Participante participante, decimal valor, DateTime data)
        {
            Adesao adesaoAtiva = AdesaoService.ObterAdesaoAtiva(participante);

            if (adesaoAtiva != null)
            {
                Emprestimo emprestimo = new Emprestimo
                {
                    Id              = Guid.NewGuid(),
                    Adesao          = adesaoAtiva,
                    DataBase        = data,
                    DataVencimento  = data.AddMonths(1),
                    ValorBase       = valor,
                    ValorDevido     = valor * (1 + (Parametrizacao.PercentualJurosEmprestimo / 100)),
                    ValorJuros      = valor * Parametrizacao.PercentualJurosEmprestimo / 100,
                    PercentualJuros = Parametrizacao.PercentualJurosEmprestimo
                };
                repositorio.Incluir(emprestimo);
                repositorio.Commit();
            }
        }
        public void DeleteEmprestimo(Emprestimo qualEmprestimo)
        {
            try
            {
                String sql = "Delete from BibEmprestimo where idEmprestimo=@id";
                conexao = new SqlConnection(_conexaoSQLServer);
                SqlCommand cmd = new SqlCommand(sql, conexao);

                cmd.Parameters.AddWithValue("@id", qualEmprestimo.IdEmprestimo);
                conexao.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conexao.Close();
            }
        }
        public void AnalisarProposta(Proposta proposta)
        {
            Thread.Sleep(3000); //simula a analise da proposta

            Emprestimo emprestimo = proposta.Emprestimo;
            Cliente    cliente    = proposta.Cliente;

            if ((emprestimo.Valor * emprestimo.TaxaDeJuros) / emprestimo.QuantidadeDeParcelas > (cliente.Salario * 0.3M))
            {
                proposta.Status = Status.Rejeitada;
            }
            else
            {
                proposta.Status = Status.Aprovada;
            }

            IGestorDeCreditoCallback callback =
                OperationContext.Current.GetCallbackChannel <IGestorDeCreditoCallback>();

            callback.PropostaAnalisada(proposta);
        }
Пример #4
0
        //Quando o usuario clica em pagar em uma parcela de emprestimo que e do tipo de pagamento por debito em conta corrente
        //Será efetuado o pagamento da parcela e atualizado a gridview respectiva
        protected void gdvParcelasDebitoEmConta_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            ContaCorrente conta      = Session["ContaCorrente"] as ContaCorrente;                                                   //Chama conta para usar as funções dela pra trabalhar
            Emprestimo    emp        = Session["emprestimo"] as Emprestimo;                                                         //Chama o emprestimo selecionado quando clicou no botão visualizar na função gdvEmprestimos_RowCommand
            Parcela       p          = new Parcela();                                                                               //Instancia uma parcela que será utilizada para receber a parcela que sera paga
            int           numParcela = 0;                                                                                           //irá receber o numero da parcela filtrado a ser paga recebida como parametro da gridview no botão de pagar parcela antecipada
            string        numero     = e.CommandArgument.ToString();                                                                //Recebe o numero da parcela como argumento da gridview sem filtro ex: 3/15 (terceira de quinze parcelas)

            lblAviso.Text = "";                                                                                                     //Limpa o aviso caso tenha aviso como saldo insuficiente de outra parcela de outro emprestimo

            if (conta.Saldo >= emp.Parcelas[0].Valor)                                                                               //verifica se o saldo da conta e maior que o valor da parcela para pagar
            {
                numParcela = numero.Length > 4 ? Convert.ToInt32(numero.Substring(0, 2)) : Convert.ToInt32(numero.Substring(0, 1)); //Filtra o numero da parcela

                int count = 1;
                emp.Parcelas.ForEach(item => { if (count == numParcela)
                                               {
                                                   p = item;
                                               }
                                               count++; });                                   //Busca a parcela do emprestimo a qual o numero se refere e armazena na instância de parcela

                //Session["parcela"] = p;

                emp.PagarParcela(p);              //Usa o metodo do emprestimo no caso para pagar a parcela

                Session["ContaCorrente"] = conta; //Devolve a conta a Session atualizada

                PopulateGridParcelas(emp.Id);     //Atualiza a grid de Parcelas nesse caso passa o id do emprestimo de parametro
                if (!emp.Pendente)                //Verifica se o emprestimo ainda tem parcelas pendentes, se não tiver mais sua gridview de parcela desaparcel
                {
                    gdvParcelasDebitoEmConta.DataSource = null;
                    gdvParcelasDebitoEmConta.DataBind();
                }
                PopulateGridEmprestimos();
            }
            else  //Se não tem saldo na conta, informa o usuario de saldo insuficiente
            {
                lblAviso.Text = "Saldo insuficiente.";
            }
        }
        public string RegistrarEmprestimo(int id, Amigo amigo, Revista revista, DateTime dataDevolucaoRevista)
        {
            Emprestimo emprestimo = null;

            int posicao;

            if (id == 0)
            {
                emprestimo = new Emprestimo();
                posicao    = ObterPosicaoVaga();
            }
            else
            {
                posicao    = ObterPosicaoOcupada(new Emprestimo(id));
                emprestimo = (Emprestimo)registros[posicao];
            }

            if (!amigo.StatusEmprestimo || !revista.StatusEmprestimo)
            {
                return("Amigo Ou Revista Já Possui Emprestimo Em Andamento!");
            }


            emprestimo.Amigo         = amigo;
            emprestimo.Revista       = revista;
            emprestimo.DataDevolucao = dataDevolucaoRevista;
            emprestimo.DataAbertura  = System.DateTime.Now;

            string resultadoValidacao = emprestimo.ValidarEmprestimo();



            if (resultadoValidacao == "EMPRESTIMO_VALIDO")
            {
                amigo.AlocarHistoricoEmprestimos(emprestimo);
                revista.StatusEmprestimo = false;
                registros[posicao]       = emprestimo;
            }
            return(resultadoValidacao);
        }
        public HttpResponseMessage AddEmprestimo()
        {
            Emprestimo emprestimo = new Emprestimo();

            List <Livro> livros = null;

            Usuario usuario = null;

            emprestimo.DiaDevolucao  = DateTime.Now.AddDays(5);
            emprestimo.DiaEmprestimo = DateTime.Now;

            using (var repository = new LivroRepository())
            {
                livros = repository.ListAll();
            }



            emprestimo.Livros = livros;

            emprestimo.Multa      = 0;
            emprestimo.Quantidade = livros.Count();

            using (var repository = new UsuarioRepository())
            {
                usuario = repository.GetById(2);
            }


            emprestimo.Usuario = usuario;

            using (var repository = new EmprestimoRepository())
            {
                repository.MarkStates(System.Data.Entity.EntityState.Unchanged, emprestimo);
                repository.Add(emprestimo);
            }


            return(Request.CreateResponse(HttpStatusCode.OK, "Adicionou"));
        }
        public async Task <EmprestimoResponse> Inserir(EmprestimoRequest request)
        {
            var amigo = await _context.Amigo.Include(x => x.Emprestimos).ThenInclude(y => y.Jogo)
                        .FirstOrDefaultAsync(x => x.Id == request.AmigoId);

            if (amigo == null)
            {
                _notification.AddNotification("Amigo", "Amigo não foi encontrado");
                return(null);
            }

            var jogo = await _context.Jogo.FirstOrDefaultAsync(x => x.Id == request.JogoId);

            if (jogo == null)
            {
                _notification.AddNotification("Jogo", "Jogo não foi encontrado");
                return(null);
            }

            if (jogo.Situacao == SituacaoJogo.Indisponivel)
            {
                _notification.AddNotification("Jogo", "Já existe um emprestimo para esse jogo");
                return(null);
            }

            var emprestimo = new Emprestimo(amigo, jogo);

            amigo.AddEmprestimo(emprestimo);

            _entityValidator.Validate(new Entity[] { emprestimo, amigo });

            if (_notification.HasNotifications)
            {
                return(null);
            }

            await _context.SaveChangesAsync();

            return(_mapper.Map <EmprestimoResponse>(emprestimo));
        }
Пример #8
0
        public void EmprestimosEditTests()
        {
            // Arrange
            var mockRepository = new Mock <IEmprestimoRepository>();

            var emprestimo = new Emprestimo()
            {
                Id = 1, LivroId = 1, Titulo = "Teste", DataEmprestimo = DateTime.Now, DataDevolucao = DateTime.Now
            };
            var controller = new EmprestimosController(mockRepository.Object);

            // Act
            var resultado = controller.Edit(emprestimo);

            // Assert
            Assert.IsInstanceOfType(resultado, typeof(RedirectToRouteResult));

            var resultadoDaView = resultado as RedirectToRouteResult;
            var modelo          = resultadoDaView.RouteValues.Values.First();

            Assert.IsTrue(modelo.Equals("Index"));
        }
Пример #9
0
        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            Emprestimo emprestimo = new Emprestimo()
            {
                Descricao = txtDescricao.Text,
                Valor     = Convert.ToDecimal(txtValor.Text),
                DataEmp   = DateTime.Now,
                Percjuros = Convert.ToDecimal(txtJuros.Text),
                QtdParc   = Convert.ToInt32(txtParcelas.Text),
            };

            if (new EmprestimoDB().Insert(emprestimo))
            {
                Decimal  ValorParcela = Convert.ToInt32(txtValor.Text) * 0.02m;
                int      QtdParcelas  = Convert.ToInt32(txtParcelas.Text);
                DateTime DataVenc     = emprestimo.DataEmp.AddDays(30);

                for (int i = 0; i <= QtdParcelas; i++)
                {
                    EmpGerado empgerado = new EmpGerado()
                    {
                        Emprestimo.Equals,
                        Parcela     = ValorParcela / QtdParcelas,
                        VencParcela = DataVenc.AddDays(30)
                    };
                }
            }

            if (new EmprestimoDB().Insert(emprestimo))
            {
                lblMsg.Text      = "Registro Inserido com Sucesso!";
                lblMsg.ForeColor = Color.Blue;
            }
            else
            {
                lblMsg.Text      = "Erro ao Inserir Registro!";
                lblMsg.ForeColor = Color.Red;
            }
        }
Пример #10
0
        public ActionResult Edit(Emprestimo emprestimo)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    emprestimoRepository.Atualizar(emprestimo);
                    emprestimoRepository.Salvar();

                    return(RedirectToAction("Listar"));
                }

                ViewBag.LivrosEditar   = retornaSelectListItemRepository.LivrosDisponiveis();
                ViewBag.ClientesEditar = retornaSelectListItemRepository.Clientes();

                return(View(emprestimo));
            }
            catch
            {
                return(View());
            }
        }
Пример #11
0
        public ActionResult CadastrarEmprestimo([FromForm] Emprestimo emprestimo)
        {
            var id = new { id = emprestimo.Id + 1 };

            var idLivro = emprestimo.LivroID;

            var livro = aluguelContexto.Livros.FirstOrDefault(x => x.Id == idLivro);

            livro.Status = StatusLivro.Indisponivel;

            emprestimo.DataEmprestimo = DateTime.Now;

            var data = DateTime.Now;

            emprestimo.PreviaDevolucao = data.AddDays(30);

            aluguelContexto.Add(emprestimo);

            aluguelContexto.SaveChanges();

            return(RedirectToAction(nameof(Emprestimo)));
        }
Пример #12
0
        public void EmprestimoService_Adiciona_NomeNuloOuVazio_DeveRetornarExcecao()
        {
            //Cenário
            Livro livro = new Livro();

            livro.Id = 1;
            Emprestimo emprestimo = ObjectMother.ObterEmprestimoInvalido_NomeClienteNuloOuVazio();

            emprestimo.Id    = 0;
            emprestimo.Livro = livro;

            _mockEmprestimoRepositorio.Setup(rp => rp.Adicionar(emprestimo)).Returns(new Emprestimo {
                Id = 1, NomeCliente = "nome", DataDevolucao = DateTime.Now.AddDays(2), Livro = livro
            });

            //Ação
            Action acaoRetorno = () => _emprestimoService.Adiciona(emprestimo);

            //Verificar
            acaoRetorno.Should().Throw <NomeNuloOuVazioException>();
            _mockEmprestimoRepositorio.VerifyNoOtherCalls();
        }
Пример #13
0
        public ActionResult Create([Bind(Include = "id,livro,valor,cep,endereco")] Emprestimo emprestimo, long matricula, string nome, DateTime dataPrazo)
        {
            string    url    = "https://viacep.com.br/ws/" + emprestimo.cep + "/json/";
            WebClient client = new WebClient();

            try
            {
                Emprestimo aux       = new Emprestimo();
                string     resultado = client.DownloadString(@url);
                //Converter para UTF8
                byte[] bytes = Encoding.Default.GetBytes(resultado);
                resultado = Encoding.UTF8.GetString(bytes);
                //Converter os dados da string em objeto
                aux = JsonConvert.DeserializeObject <Emprestimo>(resultado);
                emprestimo.endereco   = aux.Logradouro + emprestimo.endereco;
                emprestimo.Bairro     = aux.Bairro;
                emprestimo.Localidade = aux.Localidade;
                emprestimo.Uf         = aux.Uf;
                emprestimo.Logradouro = aux.Logradouro;
            }
            catch
            {
                emprestimo.cep = "Cep Inválido";
            }

            emprestimo.status        = 0;
            emprestimo.nome          = nome;
            emprestimo.bibliotecario = BibliotecarioDAO.BuscarBibliotecarioPorMatricula(matricula);
            if (ModelState.IsValid)
            {
                emprestimo.livro.ano     = DateTime.Now;
                emprestimo.dataDevolucao = "26/04/2000 00:00:00";
                emprestimo.dataPrazo     = Convert.ToString(dataPrazo);
                EmprestimoDAO.CadastrarEmprestimo(emprestimo);
                return(RedirectToAction("Index"));
            }

            return(View(emprestimo));
        }
Пример #14
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                Emprestimo emprestimo   = new Emprestimo();
                int        idLivro      = int.Parse(ddLivros.SelectedValue);
                int        idUtilizador = int.Parse(ddUtilizadores.SelectedValue);
                DateTime   dataDevolve  = DateTime.Parse(tbData.Text);
                emprestimo.adicionarEmprestimo(idLivro, idUtilizador, dataDevolve);

                atualizarDDLivros();
                atualizarDDUtilizadores();
                lbErro.Text = "Empréstimo registado com sucesso.";
            }catch (Exception erro)
            {
                lbErro.Text     = "Ocorreu o seguinte erro: " + erro.Message;
                lbErro.CssClass = "alert alert-danger";
            }
            finally {
                atualizarGrid();
            }
        }
        public ActionResult EmprestimoCliente(int?page, int ID)
        {
            IClienteProcesso processoCliente = ClienteProcesso.Instance;
            Cliente          cliente         = new Cliente();

            cliente.id = ID;
            cliente    = processoCliente.Consultar(cliente, SiteMVCTelerik.ModuloBasico.Enums.TipoPesquisa.E)[0];

            Session["ClienteSelecionado"] = cliente;
            IEmprestimoProcesso processo   = EmprestimoProcesso.Instance;
            Emprestimo          emprestimo = new Emprestimo();

            emprestimo.cliente_id = ID;
            var resultado = processo.Consultar(emprestimo, TipoPesquisa.E);



            List <Emprestimo> emprestimos = resultado;
            int currentPageIndex          = page.HasValue ? page.Value - 1 : 0;

            return(View(resultado.ToPagedList(currentPageIndex, defaultPageSize)));
        }
        public Emprestimo[] SelecionarEmprestimosMensais(int mes)
        {
            object[] arrayAux = SelecionarTodosRegistros();

            Emprestimo[] emprestimos = new Emprestimo[arrayAux.Length];

            Array.Copy(arrayAux, emprestimos, arrayAux.Length);

            Emprestimo[] emprestimosMensais = new Emprestimo[emprestimos.Length];

            int i = 0;

            foreach (Emprestimo emp in emprestimos)
            {
                if (emp != null && emp.data.Month == mes)
                {
                    emprestimosMensais[i++] = emp;
                }
            }

            return(emprestimosMensais);
        }
        public Emprestimo[] SelecionarEmprestimosEmAberto()
        {
            object[] arrayAux = SelecionarTodosRegistros();

            Emprestimo[] emprestimos = new Emprestimo[arrayAux.Length];

            Array.Copy(arrayAux, emprestimos, arrayAux.Length);

            Emprestimo[] emprestimosAbertos = new Emprestimo[emprestimos.Length];

            int i = 0;

            foreach (Emprestimo emp in emprestimos)
            {
                if (emp != null && emp.emprestimoAberto == true)
                {
                    emprestimosAbertos[i++] = emp;
                }
            }

            return(emprestimosAbertos);
        }
        public EmprestarJogoResponse Handle(EmprestarJogoRequest request)
        {
            var amigo = _context.Amigos
                        .Where(a => a.Id == request.AmigoId)
                        .FirstOrDefault();

            var jogo = _context.Jogos
                       .Where(j => j.Id == request.JogoId)
                       .FirstOrDefault();

            var emprestimo = new Emprestimo(amigo, jogo);

            _context.Emprestimos.Add(emprestimo);
            _context.SaveChanges();

            return(new EmprestarJogoResponse
            {
                Id = emprestimo.Id,
                Amigo = amigo,
                Jogo = jogo
            });
        }
Пример #19
0
        public void EmprestimoIntegracaoSistema_Obter_DeveSerValido()
        {
            //Cenário
            Livro livro = new Livro();

            livro.Id = 1;
            livro.Disponibilidade = true;

            Emprestimo emprestimo = ObjectMother.ObterEmprestimoValido();

            emprestimo.Id    = 0;
            emprestimo.Livro = livro;

            emprestimo = _emprestimoService.Adiciona(emprestimo);

            //Ação
            emprestimo = _emprestimoService.Obtem(emprestimo.Id);

            //Verificar
            emprestimo.Id.Should().Be(emprestimo.Id);
            emprestimo.Should().NotBeNull();
        }
Пример #20
0
        private void btnMulta_Click(object sender, EventArgs e)
        {
            _emprestimo = listEmprestimo.SelectedItem as Emprestimo;

            if (_emprestimo != null)
            {
                if (_emprestimo.CalculaMulta <= 0)
                {
                    var message = MessageBox.Show("O Emprestimo não possui multas. ", "Atenção",
                                                  MessageBoxButtons.OK);
                }
                else
                {
                    var message = MessageBox.Show("Multa: R$" + _emprestimo.CalculaMulta, "Atenção",
                                                  MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show("Selecione um emprestimo para calcular a multa!");
            }
        }
 private void IncluirJogosParaEmprestimo(Emprestimo emprestimo, ICollection <Jogo> jogos)
 {
     try
     {
         foreach (var jogo in jogos)
         {
             var emprestimoJogo = new EmprestimoJogo {
                 Ativo        = true,
                 Jogo         = jogo,
                 JogoId       = jogo.Id,
                 EmprestimoId = emprestimo.Id,
                 Emprestimo   = emprestimo
             };
             db.Entry(emprestimoJogo).State = EntityState.Added;
             emprestimo.EmprestimosJogos.Add(emprestimoJogo);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public ActionResult Create([Bind(Include = "EmprestimoId,Emprestado,PessoaEmprestimo,DataEmprestimo,DataDevolucao,LivroId,UsuarioId")] Emprestimo emprestimo)
        {
            using (LibraryContext ctx = new LibraryContext())
            {
                if (ModelState.IsValid)
                {
                    Usuario u = Session["usuario"] as Usuario;
                    emprestimo.UsuarioId = u.UsuarioId;

                    db.Emprestimo.Add(emprestimo);
                    db.SaveChanges();

                    ViewBag.LivroId = new SelectList(ctx.Usuario.Where(c => c.UsuarioId == u.UsuarioId));

                    return(RedirectToAction("Index"));
                }

                //ViewBag.LivroId = new SelectList(db.Livro, "LivroId", "Titulo", emprestimo.LivroId);

                return(View(emprestimo));
            }
        }
Пример #23
0
        public ActionResult Create([Bind(Include = "Id,DataEmprestimo,DataDevolucao,IdLivro,IdAluno")] Emprestimo emprestimo)
        {
            if (ModelState.IsValid)
            {
                Livro livro = new Livro();
                livro = db.Livroes.Find(emprestimo.IdLivro);
                if (livro.emprestado)
                {
                    return(RedirectToAction("LivroEmprestado"));
                }
                else
                {
                    livro.emprestado = true;
                    emprestimo.Livro = livro;
                    db.Emprestimoes.Add(emprestimo);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            return(View(emprestimo));
        }
Пример #24
0
        public ActionResult Emprestimo(Emprestimo emprestimo)
        {
            var retorno = _jogoService.Emprestar(emprestimo);

            if (retorno != null)
            {
                return(Redirect("\\Jogos\\Jogos"));
            }
            else
            {
                var jogo = _jogoService.Get(emprestimo.JogoId);
                emprestimo.Jogo = jogo;
                var model = new ModelEmprestimo()
                {
                    Emprestimo = emprestimo,
                };
                model.Amigos = (_amigoService.Get() as IQueryable <Amigo>).ToList();

                ViewBag.Message = EscopoBase._notificacoes;
                return(View(model));
            }
        }
Пример #25
0
        //feito
        public IEnumerable <Emprestimo> GetAllEmprestimos()
        {
            using (var connection = new SqlConnection(connectionString))
            {
                var commandText = "SELECT * FROM Emprestimos INNER JOIN Livro ON Emprestimos.LivroID=Livro.Id";

                var selectCommand = new SqlCommand(commandText, connection);

                Emprestimo emprestimo  = null;
                var        emprestimos = new List <Emprestimo>();

                try
                {
                    connection.Open();

                    using (var reader = selectCommand.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (reader.Read())
                        {
                            emprestimo                = new Emprestimo();
                            emprestimo.Id             = (int)reader["Id"];
                            emprestimo.LivroId        = (int)reader["LivroId"];
                            emprestimo.Titulo         = reader["Titulo"].ToString();
                            emprestimo.DataEmprestimo = Convert.ToDateTime(reader["DataEmprestimo"]);
                            emprestimo.DataDevolucao  = Convert.ToDateTime(reader["DataDevolucao"]);

                            emprestimos.Add(emprestimo);
                        }
                    }
                }
                finally
                {
                    connection.Close();
                }

                return(emprestimos);
            }
        }
Пример #26
0
        public bool RegistrarEmprestimo(int id, int idAmigoEmprestimo, int idRevistaEmprestimo, DateTime dataDevolucao)
        {
            bool       conseguiuRegistrar = false;
            Emprestimo emprestimo;
            int        posicao = 0;

            if (id == 0)
            {
                emprestimo = new Emprestimo();
                posicao    = ObterPosicaoVazia();
            }
            else
            {
                posicao    = ObterPosicaoOcupada(new Emprestimo(id));
                emprestimo = (Emprestimo)registros[posicao];
            }

            emprestimo.amigo   = controladorAmigo.SelecionarAmigoPorId(idAmigoEmprestimo);
            emprestimo.revista = controladorRevista.SelecionarRevistaPorId(idRevistaEmprestimo);

            if (emprestimo.amigo.pegouRevista == false && emprestimo.revista.emprestado == false)
            {
                emprestimo.dataDevolucao      = dataDevolucao;
                emprestimo.dataEmprestimo     = DateTime.Now;
                emprestimo.revista.emprestado = true;
                emprestimo.amigo.pegouRevista = true;
                emprestimo.emprestimoFechado  = false;
                conseguiuRegistrar            = true;

                registros[posicao] = emprestimo;
            }
            else
            {
                conseguiuRegistrar = false;
            }

            return(conseguiuRegistrar);
        }
Пример #27
0
        public async Task <IActionResult> EmprestarLivros()
        {
            // Verificamos se o usuário está logado
            if (User.Identity.IsAuthenticated)
            {
                // Pegar ID do Usuário
                var userID = _userManager.GetUserId(HttpContext.User);

                // Criar empréstimo
                Emprestimo emprestimo = new Emprestimo()
                {
                    ApplicationUserId = userID,
                    DataInicio        = DateTime.Now.ToString("dd/MM/yyyy"),
                    DataFim           = DateTime.Now.AddDays(7).ToString("dd/MM/yyyy"),
                    UsuarioID         = 1, // Fixo p/ não dar erro
                    LivroEmprestimo   = new List <LivroEmprestimo>()
                };

                // Resgatar lista de livros no carrinho
                List <Livro> listaLivros = GetCarrinho();

                // Inserir a lista de livros na tabela LivroEmprestimo
                foreach (var item in listaLivros)
                {
                    LivroEmprestimo livroEmprestimo = new LivroEmprestimo();
                    livroEmprestimo.LivroID    = item.LivroID;
                    livroEmprestimo.Emprestimo = emprestimo;

                    emprestimo.LivroEmprestimo.Add(livroEmprestimo);
                }

                // Inserir o novo empréstimo na tabela
                _context.Add(emprestimo);
                await _context.SaveChangesAsync();
            }

            return(View("Index", GetCarrinho()));
        }
Пример #28
0
 public ActionResult Create(DateTime dataEmprestimo, List <string> artigosEmprestimo)
 {
     try
     {
         if (User.IsInRole("Utilizador") && ModelState.IsValid && artigosEmprestimo.Count() > 0 && DateTime.Compare(dataEmprestimo, DateTime.Today) >= 0)
         {
             List <ArtigosEmprestimo> artEmpFiltered = new List <ArtigosEmprestimo>();
             foreach (string idArt in artigosEmprestimo)
             {
                 if (idArt != "false")
                 {
                     int idArtInt = Convert.ToInt32(idArt);
                     if (IdArtigoExiste(GetArtigosDisponiveis(), idArtInt) && !IdArtigoExiste(artEmpFiltered, idArtInt))
                     {
                         artEmpFiltered.Add(new ArtigosEmprestimo()
                         {
                             IdArtigo = idArtInt
                         });
                     }
                 }
             }
             Emprestimo emprestimo = new Emprestimo()
             {
                 DataEmprestimo     = dataEmprestimo,
                 IdEstado           = 1, //-> Pendente
                 IdUtilizador       = User.Identity.GetUserId(),
                 ArtigosEmprestimos = artEmpFiltered
             };
             db.Emprestimos.Add(emprestimo);
             db.SaveChanges();
         }
     }
     catch (Exception ex)
     {
         return(RedirectToAction("Index"));
     }
     return(RedirectToAction("Index"));
 }
Пример #29
0
        public IServiceResult Devolver(TipoMidia tipoMidia, int midiaId)
        {
            if (tipoMidia == 0 || midiaId == 0)
            {
                return(ServiceResult.CriarFormularioInvalido(new List <string> {
                    "Midia não informada"
                }));
            }

            var possuinte = new Possuinte()
            {
                Nome = string.Empty, FormaDeContato = string.Empty
            };

            var emprestimo = new Emprestimo(possuinte)
            {
                EstaEmprestado = false
            };

            switch (tipoMidia)
            {
            case TipoMidia.Livro:
                esClientProvider.Client.Update <Livro, object>(midiaId, u => u.Doc(new { emprestimo = emprestimo }).RetryOnConflict(1));
                break;

            case TipoMidia.Cd:
                esClientProvider.Client.Update <Cd, object>(midiaId, u => u.Doc(new { emprestimo = emprestimo }).RetryOnConflict(1));
                break;

            case TipoMidia.Dvd:
                esClientProvider.Client.Update <Dvd, object>(midiaId, u => u.Doc(new { emprestimo = emprestimo }).RetryOnConflict(1));
                break;

            default: throw new Exception();
            }

            return(ServiceResult.CreateResultOk());
        }
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Emprestimo emprestimo = db.Emprestimo.Find(id);

            if (emprestimo == null)
            {
                return(HttpNotFound());
            }

            using (LibraryContext ctx = new LibraryContext())
            {
                Usuario u = (Usuario)Session["usuario"];
                ViewBag.LivroId = new SelectList(db.Livro.Where(c => c.UsuarioId == u.UsuarioId), "LivroId", "Titulo");
                return(View(emprestimo));
            }
            //ViewBag.LivroId = new SelectList(db.Livro, "LivroId", "Titulo", emprestimo.LivroId);
            //ViewBag.UsuarioId = new SelectList(db.Usuario, "UsuarioId", "Nome", emprestimo.UsuarioId);
            //return View(emprestimo);
        }