public void TesteReserva() { //Arrange DateTime dataAluguel = DateTime.Now; DateTime dataDevolucao = DateTime.MaxValue; int idCarro = 1; string userID = "*****@*****.**"; Aluguel teste = new Aluguel() { AluguelID=1, DataAluguel = dataAluguel, DataDevolucao = dataDevolucao, CarroID = 1, UserId = userID,Finalizado = false }; Carro carro = new Carro() { CarroID = 1, Quilometragem = 6291 }; var mockCtx = new Mock<IContext>(); mockCtx.Setup(x => x.Alugueis).Returns(new FakeSET<Aluguel> { teste }); var mockdaoAluguel = new Mock<IAluguelDAO>(); var mockdaoCarro = new Mock<ICarroDAO>(); mockdaoCarro.Setup(x => x.FindById(1)).Returns(carro); mockdaoAluguel.Setup(x => x.Add(teste)).Callback(() => mockdaoAluguel.Setup(x => x.Exists(1)).Returns(true)); var service = new AluguelService(mockdaoAluguel.Object, mockdaoCarro.Object); //ACT service.Reservar(dataAluguel, dataDevolucao, idCarro, userID); bool result = mockdaoAluguel.Object.Exists(1); //ASSERT Assert.AreEqual(false, result); }
public void Incluir(Aluguel aluguel) { //conexao SqlConnection cn = new SqlConnection(); try { cn.ConnectionString = Dados.StringDeConexao; //command SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandText = "insert into TbAluguel(TbUsuario_idUsuario, TbTema_idTema,enderecoUsuario,dataFesta,horaInicio, horaFim, numeroPessoas, valorAluguel)" + " values (@idUsuario, @idTema, @enderecoUsuario, @dataFesta, @horaInicio, @horaFim, @numeroPessoas, @valorAlguel); select @@IDENTITY;"; cmd.Parameters.AddWithValue("@idUsuario", aluguel.IdUsuario); cmd.Parameters.AddWithValue("@idTema", aluguel.IdTema); cmd.Parameters.AddWithValue("@enderecoUsuario", aluguel.EnderecoUsuario); cmd.Parameters.AddWithValue("@dataFesta", aluguel.DataFesta); cmd.Parameters.AddWithValue("@horaInicio", aluguel.HoraInicio); cmd.Parameters.AddWithValue("@horaFim", aluguel.HoraFim); cmd.Parameters.AddWithValue("@numeroPessoas", aluguel.NumeroPessoas); cmd.Parameters.AddWithValue("@valorAlguel", aluguel.ValorAluguel); cn.Open(); aluguel.IdAluguel = Convert.ToInt32(cmd.ExecuteScalar()); } catch (SqlException ex) { throw new Exception("Servidor SQL Erro:" + ex.Number); } catch (Exception ex) { throw new Exception(ex.Message); } finally { cn.Close(); } }
public void CriarAluguel(Aluguel aluguel) { int confirmado = 0; if (aluguel.confirmado == true) { confirmado = 1; } var strQuery = ""; strQuery += "INSERT INTO aluguel (idAluguel, idCampo,horarioInicio, horarioFim, confirmado, valor)"; strQuery += string.Format("VALUES( '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')", aluguel.idAluguel, aluguel.idCampo, aluguel.horarioInicio, aluguel.horarioFim, confirmado, aluguel.valor); using (contexto = new Contexto()) { contexto.ExecutaComando(strQuery); } }
public void ProcessaNF(Aluguel aluguel) { TimeSpan duracao = aluguel.Fim.Subtract(aluguel.Inicio); double pagtoBasico = 0.0; if (duracao.TotalHours <= 12) { pagtoBasico = PrecoHora * Math.Ceiling(duracao.TotalHours); } else { pagtoBasico = PrecoDia * Math.Ceiling(duracao.TotalDays); } double tax = _servicoTaxa.Taxa(pagtoBasico); aluguel.Invoice = new Invoice(pagtoBasico, tax); }
public List <Aluguel> ObterTodos() { var linhas = File.ReadAllLines(PATH); List <Aluguel> reservas = new List <Aluguel>(); foreach (var linha in linhas) { Aluguel aluguel = new Aluguel(); aluguel.Id = ulong.Parse(ExtrairValorDoCampo("id", linha)); aluguel.Status = uint.Parse(ExtrairValorDoCampo("status_pedido", linha)); aluguel.Cliente.Nome = ExtrairValorDoCampo("cliente_nome", linha); aluguel.Cliente.Email = ExtrairValorDoCampo("cliente_email", linha); aluguel.DataDoAluguel = DateTime.Parse(ExtrairValorDoCampo("data_aluguel", linha)); aluguel.PrecoTotal = double.Parse(ExtrairValorDoCampo("preco_total", linha)); reservas.Add(aluguel); } return(reservas); }
public bool ConfirmarEntregaChave(int idAdm, string senha, int idAluguel) { Administrador = UsuarioDao.Pegar(idAdm); if (Administrador.Senha.Equals(senha)) { Aluguel = AluguelDao.Pegar(idAluguel); Aluguel.AdministradorId = idAdm; Aluguel.ClienteComAChave = true; AluguelDao.Alterar(Aluguel); return(true); } else { return(false); } }
public IActionResult Get(int id) { try { Aluguel aluguel = _aluguelRepositorio.Obter(id); if (aluguel == null) { return(NotFound(Constantes.Mensagens.AluguelNaoEncontrado)); } return(Ok(_mapper.Map <Aluguel, AluguelModel>(aluguel))); } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError, Constantes.Mensagens.ServicoIndisponivel)); } }
public async Task <IActionResult> Edit(int id, [Bind("AluguelId,Valor,MesId,Ano")] Aluguel aluguel) { if (id != aluguel.AluguelId) { return(NotFound()); } if (ModelState.IsValid) { await _aluguelRepositorio.Atualizar(aluguel); TempData["Atualizacao"] = $"Aluguel do mês {aluguel.MesId} ano {aluguel.Ano} atualizado"; return(RedirectToAction(nameof(Index))); } ViewData["MesId"] = new SelectList(await _mesRepositorio.PegarTodos(), "MesId", "Nome"); return(View(aluguel)); }
public JsonResult Incluir(Aluguel item) { try { var msg = new Mensagem(Descricoes.MSG001, Tipo.Sucesso); if (ModelState.IsValid) { aluguelService.Save(item); return(Json(CreateMessageJson(msg))); } msg = new Mensagem(Descricoes.MSG025, Tipo.Alerta); return(Json(CreateMessageJson(msg))); } catch (Exception ex) { return(Json(CreateMessageJson(ex))); } }
private IEnumerable <Entities.Aluguel> GetAll(Aluguel item) { //Filtros var temIdePessoaJuridica = item.IdePessoaJuridica > 0; var temDscVeiculo = !string.IsNullOrEmpty(item.DscVeiculo); var temDthSolicitacaoInicio = item.DthSolicitacaoInicio.HasValue; var temDthSolicitacaoFim = item.DthSolicitacaoFim.HasValue; var items = DbConnection.Aluguel .Where(x => (temIdePessoaJuridica? x.IdePessoaJuridica == item.IdePessoaJuridica: true) && (temDscVeiculo? x.DscVeiculo.Contains(item.DscVeiculo): true) && (temDthSolicitacaoInicio? x.DthSolicitacao >= item.DthSolicitacaoInicio: true) && (temDthSolicitacaoFim? x.DthSolicitacao <= item.DthSolicitacaoFim: true) ) .Include(x => x.PessoaJuridica); return(items); }
public bool ConfirmarReceberChave(int idAdm, string senha, int idAluguel) { Administrador = UsuarioDao.Pegar(idAdm); if (Administrador.Senha.Equals(senha)) { Aluguel = AluguelDao.Pegar(idAluguel); Aluguel.ClienteComAChave = false; Aluguel.DataRecebimento = DateTime.Now; AluguelDao.Alterar(Aluguel); return(true); } else { return(false); } }
public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } try { Aluguel aluguel = service.Buscar(id); ReservaAluguelViewModel aluguelVM = Mapper.Map <Aluguel, ReservaAluguelViewModel>(aluguel); return(View(aluguelVM)); } catch (BusinessException ex) { return(HttpNotFound(ex.Message)); } }
public Aluguel CriarAluguel(Aluguel aluguel) { using (var transacao = _context.Database.BeginTransaction()) { try { var resultado = _context.Alugueis.Attach(aluguel); resultado.State = EntityState.Added; _context.SaveChanges(); transacao.Commit(); return(resultado.Entity); } catch (Exception e) { throw new Exception(e.Message); } } }
public JsonResult Alugar(int id, string dataIni, string dataFim, string cliente) { Veiculo veiculo = VeiculoDao.Pegar(id); string[] dataInicio = dataIni.Split('/'); string[] dataFinal = dataFim.Split('/'); Aluguel aluguel = new Aluguel { ClienteId = UsuarioDao.BuscarPorCpf(cliente).UsuarioId, DataAluguelInicio = new DateTime(Convert.ToInt32(dataInicio[2]), Convert.ToInt32(dataInicio[1]), Convert.ToInt32(dataInicio[0])), DataAluguelFim = new DateTime(Convert.ToInt32(dataFinal[2]), Convert.ToInt32(dataFinal[1]), Convert.ToInt32(dataFinal[0])), Veiculo = veiculo }; AluguelDao.Adicionar(aluguel); return(Json(new { id = aluguel.AluguelId })); }
public DetalhesAluguel(Aluguel aluguel) { InitializeComponent(); this.aluguel = aluguel; aluguel.IdAluguel = this.aluguel.IdAluguel; aluguel.DataAluguel = this.aluguel.DataAluguel; aluguel.ValorAluguel = this.aluguel.ValorAluguel; tblockIdAluguel.Text = Convert.ToString(aluguel.IdAluguel); tblockData.Text = aluguel.DataAluguel.ToString("dd/MM/yyyy"); tblockIdValor.Text = aluguel.ValorAluguel.ToString("c"); produtoController = new ProdutoController(); this.listaProdutosAluguel = produtoController.ListarProdutoAluguel(aluguel.IdAluguel); this.dgDetalhe.ItemsSource = this.listaProdutosAluguel; }
public IActionResult RealizaAluguel(Guid id, [Bind("IdAluguel, IdCliente, Filmes")] Aluguel aluguel, List<Filme> filmes) { try { aluguel.RealizarEmprestimo(filmes); aluguel = _repositoryAluguel.CriarAluguel(aluguel); filmes = aluguel.AluguelFilmes.Select(m => m.Filme).ToList(); foreach (var filme in filmes) { _repositoryFilme.EditarFilme(filme); } return View(aluguel); } catch (Exception e) { throw new Exception(e.Message); } }
public void DevolverAluguel(Aluguel aluguel) { ConectarSQL(); foreach (var item in aluguel.Items.Where(item => item.StatusDevolucao)) { DevolverItem(item); DevolverEstoque(item.Midia); } if (aluguel.Items.All(item => item.StatusDevolucao)) { aluguel.DataEntrega = DateTime.Now; PagarAluguel(aluguel); //Colocar o Valor Total no Caixa //Podemos colocar os descontos e multas apenas para apreciacao } DesconectarSQL(); }
public JsonResult AtualizarAluguel(AluguelAtualizaSolicitacaoViewModel model) { if (ModelState.IsValid) { try { Aluguel a = new Aluguel(); a.IdAluguel = model.IdAluguel; a.DataAlguel = model.DataAluguel; a.HoraInicio = model.HorInicio; a.HoraFim = model.HoraFim; a.Descricao = model.DescricaoEvento; a.IdEspaco = model.IdEspaco; a.IdUsuario = model.IdUsuario; a.ValorAluguel = 0; a.FlCancelado = 0; a.FlVerificado = 0; repository.Update(a); return(Json("Aluguel atualizado com sucesso!")); } catch (Exception e) { return(Json($"Ocorreu um erro:{e.Message}")); } } else { Hashtable erros = new Hashtable(); foreach (var m in ModelState) { if (m.Value.Errors.Count > 0) { erros[m.Key] = m.Value.Errors.Select(e => e.ErrorMessage); } } return(Json(erros)); } }
public IActionResult Cadastrar([FromForm] ViewModelAluguel viewModelAluguel) { var livro = _SisAluguelContexto.Livros.FirstOrDefault(i => i.Id == viewModelAluguel.IdLivro); if (livro != null) { livro.SituacaoAluguel = SituacaoAluguel.Alugado; Guid id = Guid.NewGuid(); Aluguel aluguel = new Aluguel(id, viewModelAluguel.IdCliente, livro, viewModelAluguel.DataDeEmprestimo, viewModelAluguel.DataDeDevolucao); _SisAluguelContexto.Alugueis.Add(aluguel); _SisAluguelContexto.SaveChanges(); TempData["msg"] = "<script>alert('Cadastrado com sucesso ');</script>"; return(View("../Livro/livros", Ok())); } return(View("../Livro/livros", NoContent())); }
public ActionResult Detalhes(long?id) { string email = HttpContext.GetOwinContext().Authentication.User.Identity.Name; long? idCliente = (long?)long.Parse(Gerenciador.FindByEmail(email).Id); Aluguel aluguel = AluguelService.ObterAluguelPorId(id); if (aluguel != null) { if (aluguel.ClienteId != idCliente) { return(new HttpStatusCodeResult(HttpStatusCode.Unauthorized)); } return(View(aluguel)); } return(HttpNotFound()); }
public bool Adicionar(Aluguel obj) { using (var cmd = _uow.CreateCommand()) { cmd.CommandText = "Insert Into Alugueis (AluguelId, LocatarioId, EnderecoId, UsuarioId, Inicio, Fim) Values" + "(@AluguelId, @LocatarioId, @EnderecoId, @UsuarioId, @Inicio, @Fim)"; SqlParameter[] parametros = new SqlParameter[6]; parametros[0] = new SqlParameter() { Value = obj.AluguelId, ParameterName = "@AluguelId" }; parametros[0] = new SqlParameter() { Value = obj.LocatarioId, ParameterName = "@LocatarioId" }; parametros[0] = new SqlParameter() { Value = obj.EnderecoId, ParameterName = "@EnderecoId" }; parametros[0] = new SqlParameter() { Value = obj.LocadorId, ParameterName = "@UsuarioId" }; parametros[0] = new SqlParameter() { Value = obj.DataInicio, ParameterName = "@Inicio" }; parametros[0] = new SqlParameter() { Value = obj.DataFim, ParameterName = "@Fim" }; for (int i = 0; i < parametros.Length; i++) { cmd.Parameters.Add(parametros[i]); } bool success = cmd.ExecuteNonQuery() > 0; _uow.SaveChanges(); return(success); } }
public IActionResult Post(Guid idCliente, [FromBody] IEnumerable <Filme> filmes) { try { Aluguel aluguel = new Aluguel(idCliente); aluguel.RealizarEmprestimo(filmes); aluguel = _repositoryAluguel.CriarAluguel(aluguel); filmes = aluguel.AluguelFilmes.Select(m => m.Filme).ToList(); foreach (var filme in filmes) { _repositoryFilme.EditarFilme(filme); } return(Ok(aluguel)); } catch (Exception e) { throw new Exception(e.Message); } }
public Aluguel Alugar(Aluguel dadosAluguel) { Aluguel aluguelParaProcessamento = Simular(dadosAluguel); if (aluguelParaProcessamento.Valid) { Cliente clienteAluguel = _clienteRepository.Obter(dadosAluguel.IdCliente); if (clienteAluguel == null) { dadosAluguel.AddNotification(nameof(dadosAluguel.IdVeiculo), $"Cliente [ID:{dadosAluguel.IdCliente}] informado para aluguel não existe."); return(dadosAluguel); } aluguelParaProcessamento.IdAluguel = _aluguelRepository.Inserir(aluguelParaProcessamento); _veiculoRepository.AtualizarDisponibilidade(aluguelParaProcessamento.IdVeiculo, true); } return(aluguelParaProcessamento); }
private void btnSalvarAluguel_Click(object sender, EventArgs e) { //AluguelAction aluguelAction = new AluguelAction try { var IdCliente = _funcoes.PegarIdCombo(cmbCliente); var IdVeiculo = _funcoes.PegarIdCombo(cmbVeiculo); if (ValidaCampos() == false) { return; } AluguelAction aluguelAction = new AluguelAction(); Aluguel aluguel = new Aluguel(); aluguel.IdAluguel = Convert.ToInt32(_idAluguel); aluguel.Preco = Convert.ToInt32(txtPrecoAluguel.Text); aluguel.DataAluguel = txtDataAluguel.Text; aluguel.DataDevolucao = txtDataDevAluguel.Text; aluguel.IdCliente = IdCliente; aluguel.IdVeiculo = IdVeiculo; var retorno = aluguelAction.Salvar(aluguel); if (retorno) { MessageBox.Show("Aluguel Cadastrado com Sucesso!", "Cliente", MessageBoxButtons.OK, MessageBoxIcon.Information); btnNovo_Click(null, null); btnPesquisar_Click(null, null); } else { MessageBox.Show("Houve um erro ao Salvar!", "Cliente", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { throw new Exception("Houve um erro ao tentar realizar uma operação [" + MethodBase.GetCurrentMethod().ToString() + "]: " + ex.Message); } }
public async Task <IActionResult> Create([Bind("AluguelId,Valor,MesId,Ano")] Aluguel aluguel) { if (ModelState.IsValid) { if (!AluguelRepositorio.AluguelJaExiste(aluguel.MesId, aluguel.Ano)) { await AluguelRepositorio.Inserir(aluguel); var usuarios = await UsuariosRepositorio.PegarTodos(); Pagamento pagamento; var pagamentos = new List <Pagamento>(); foreach (var u in usuarios) { pagamento = new Pagamento { AluguelId = aluguel.AluguelId, UsuarioId = u.Id, DataPagamento = null, Status = StatusPagamento.Pendente }; pagamentos.Add(pagamento); } await PagamentoRepositorio.Inserir(pagamentos); TempData["NovoRegistro"] = $"Aluguel no valor de {aluguel.Valor} do mês {aluguel.MesId} do ano {aluguel.Ano} adicionado"; return(RedirectToAction(nameof(Index))); } else { ModelState.AddModelError("", "Aluguel já existe"); ViewData["MesId"] = new SelectList(await MesRepositorio.PegarTodos(), "MesId", "Nome"); return(View(aluguel)); } } ViewData["MesId"] = new SelectList(await MesRepositorio.PegarTodos(), "MesId", "Nome"); return(View(aluguel)); }
public void Cadastrar(FaturaAluguel faturaAluguel) { FaturaAluguel items; var lista_itens = JsonConvert.DeserializeObject <List <FaturaAluguel> >(faturaAluguel.ListaProdutos); items = new FaturaAluguel { AluguelId = lista_itens[0].AluguelId, DataInicio = DateTime.Parse(lista_itens[0].DataInicio).ToString("yyyy/MM/dd"), DataRetorno = DateTime.Parse(lista_itens[0].DataRetorno).ToString("yyyy/MM/dd"), ValorTotal = faturaAluguel.ValorTotal }; _banco.Add(items); Aluguel aluguel = _banco.Alugueis.Include(a => a.VeiculoEmpresa).FirstOrDefault(a => a.Id.Equals(items.AluguelId)); aluguel.Status = 1; aluguel.VeiculoEmpresa.Status = 1; _banco.SaveChanges(); }
public ActionResult Edit([Bind(Include = "Id,Dias")] Aluguel aluguel) { if (ModelState.IsValid) { using (var dbTransact = _contexto.Database.BeginTransaction()) { try { _repositorio.Editar(aluguel); dbTransact.Commit(); } catch (Exception) { dbTransact.Rollback(); } } return(RedirectToAction("Index")); } return(View(aluguel)); }
public IActionResult AlugarCarro([FromBody] Aluguel dadosAluguel) { if (dadosAluguel == null || dadosAluguel == new Aluguel()) { return(BadRequest()); } var idAluguelJaOcupado = _carrosAlugados.Where(c => c.Id == dadosAluguel.Id).Any(); var carroExiste = _carros.Where(c => c.Id == dadosAluguel.IdCarro).Any(); if (!carroExiste || idAluguelJaOcupado) { return(BadRequest()); } _carrosAlugados.Add(dadosAluguel); return(Ok()); }
public IActionResult Put(int id, AluguelModel editedModel) { try { Aluguel currentModel = _aluguelBusiness.Get(id); if (currentModel == null) { return(NotFound()); } _aluguelBusiness.Edit(currentModel, editedModel.ToDomain()); return(Ok(editedModel.ToBody())); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
private List <Aluguel> ConvertAluguelToObject(MySqlDataReader reader) { var rents = new List <Aluguel>(); while (reader.Read()) { var temObjeto = new Aluguel() { idAluguel = int.Parse(reader["idAluguel"].ToString()), idCampo = int.Parse(reader["idCampo"].ToString()), // reponsavelId = (reader["responsavelId"].DB), //idPagamento = (reader["responsavelId"].ToString()), horarioInicio = reader["horarioInicio"].ToString(), horarioFim = reader["horarioFim"].ToString(), confirmado = bool.Parse(reader["confirmado"].ToString()) }; rents.Add(temObjeto); } reader.Close(); return(rents); }
public void CreateShouldReturnAluguel() { //Arrange var aluguelDto = new AluguelDto { IdVeiculo = 10, ValorMensal = 100, Nome = "Comprador", DataEntrega = DateTime.Now, DataRetirada = DateTime.Now }; var aluguel = new Aluguel(10, 100, "Comprador", DateTime.Now, DateTime.Now); //Act var result = repository.CreateAluguel(aluguelDto); //Assert result.Should().NotBeNull(); result.Should().Equals(aluguel); }
public void InserirAluguel(Aluguel aluguel) { repositorioAluguel.Inserir(aluguel); }
public void RemoverAluguel(Aluguel aluguel) { repositorioAluguel.Deletar(aluguel); }