Example #1
0
        public async Task <ISaida> CadastrarPeriodo(CadastrarPeriodoEntrada cadastroEntrada)
        {
            // Verifica se as informações para cadastro foram informadas corretamente
            if (cadastroEntrada.Invalido)
            {
                return(new Saida(false, cadastroEntrada.Mensagens, null));
            }

            // Verifica se já existe um período que abrange as datas informadas
            this.NotificarSeVerdadeiro(
                await _periodoRepositorio.VerificarExistenciaPorDataInicioFim(cadastroEntrada.IdUsuario, cadastroEntrada.DataInicio, cadastroEntrada.DataFim),
                PeriodoMensagem.Datas_Abrangidas_Outro_Periodo);

            if (this.Invalido)
            {
                return(new Saida(false, this.Mensagens, null));
            }

            var periodo = new Periodo(cadastroEntrada);

            await _periodoRepositorio.Inserir(periodo);

            await _uow.Commit();

            return(_uow.Invalido
                ? new Saida(false, _uow.Mensagens, null)
                : new Saida(true, new[] { PeriodoMensagem.Periodo_Cadastrado_Com_Sucesso }, new PeriodoSaida(periodo)));
        }
Example #2
0
        public async Task <ISaida> CadastrarConta(CadastrarContaEntrada cadastroEntrada)
        {
            // Verifica se as informações para cadastro foram informadas corretamente
            if (cadastroEntrada.Invalido)
            {
                return(new Saida(false, cadastroEntrada.Mensagens, null));
            }

            // Verifica se o usuário já possui alguma conta com o nome informado
            this.NotificarSeVerdadeiro(await _contaRepositorio.VerificarExistenciaPorNome(cadastroEntrada.IdUsuario, cadastroEntrada.Nome), ContaMensagem.Conta_Com_Mesmo_Nome);

            if (this.Invalido)
            {
                return(new Saida(false, this.Mensagens, null));
            }

            var conta = new Conta(cadastroEntrada);

            await _contaRepositorio.Inserir(conta);

            await _uow.Commit();

            return(_uow.Invalido
                ? new Saida(false, _uow.Mensagens, null)
                : new Saida(true, new[] { ContaMensagem.Conta_Cadastrada_Com_Sucesso }, new ContaSaida(conta)));
        }
Example #3
0
        public async Task <ISaida> CadastrarPessoa(CadastrarPessoaEntrada cadastroEntrada)
        {
            // Verifica se as informações para cadastro foram informadas corretamente
            if (cadastroEntrada.Invalido)
            {
                return(new Saida(false, cadastroEntrada.Mensagens, null));
            }

            // Verifica se já existe uma pessoa com o mesmo nome informado
            this.NotificarSeVerdadeiro(await _pessoaRepositorio.VerificarExistenciaPorNome(cadastroEntrada.IdUsuario, cadastroEntrada.Nome), PessoaMensagem.Pessoa_Com_Mesmo_Nome);

            if (this.Invalido)
            {
                return(new Saida(false, this.Mensagens, null));
            }

            var pessoa = new Pessoa(cadastroEntrada);

            await _pessoaRepositorio.Inserir(pessoa);

            await _uow.Commit();

            return(_uow.Invalido
                ? new Saida(false, _uow.Mensagens, null)
                : new Saida(true, new[] { PessoaMensagem.Pessoa_Cadastrada_Com_Sucesso }, new PessoaSaida(pessoa)));
        }
Example #4
0
        public CommandResult CadastrarTipoInscricao(TipoInscricao tipoInscricao)
        {
            try
            {
                _uow.BeginTransaction();
                _uow.GetConnection().Execute(
                    "dbo.spGravaTipoInscricao",
                    new
                {
                    Id           = tipoInscricao.Id,
                    Descricao    = tipoInscricao.Descricao,
                    Status       = tipoInscricao.Status,
                    AliasUsuario = tipoInscricao.AliasUsuario
                },
                    _uow.GetTransaction(),
                    commandType: CommandType.StoredProcedure
                    );

                _uow.Commit();
                return(new CommandResult(true, "Cadastro realizado com sucesso.", null));
            }
            catch (Exception e)
            {
                _uow.Rollback();
                return(new CommandResult(false, "Erro ao tentar realizar cadastro: " + e.Message, null));
            }
        }
Example #5
0
        public void Add(RegisterUserModel userEditor)
        {
            var name = new Name(userEditor.FirstName, userEditor.LastName);
            var user = new User(name);

            _userRepository.Add(user);
            _uow.Commit();
        }
Example #6
0
        public IActionResult PostCreateUser([FromForm] User user)
        {
            if (ModelState.IsValid)
            {
                _userRepository.Save(user);
                _uow.Commit();
            }

            return(RedirectToAction("Index"));
        }
        public async Task <AbrirComandaResponse> AbrirComanda([FromRoute] byte mesa)
        {
            var command = new AbrirComandaCommand
            {
                Mesa = mesa
            };

            var response = await _abrirComandaCommandHandler.Handler(command);

            _uow.Commit();

            return(response);
        }
        public async Task <CancelarPedidoResponse> CancelarPedido([FromRoute] Guid pedidoId)
        {
            var command = new CancelarPedidoCommand
            {
                PedidoId = pedidoId
            };

            var response = await _cancelarPedidoCommandHandler.Handler(command);

            _uow.Commit();

            return(response);
        }
Example #9
0
        public IActionResult AddCategory([FromBody] CategoryDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _unitOfWork.CategoryRepository.Insert(_mapper.Map <Category>(dto));
            _unitOfWork.Commit();

            var product = _unitOfWork.CategoryRepository.List().OrderByDescending(x => x.Id).FirstOrDefault();

            return(Ok(_mapper.Map <CategoryDto>(product)));
        }
Example #10
0
        public User Add(AddUserInput userInput)
        {
            var login = new Login(userInput.UserName, userInput.Password, userInput.Password);
            var email = new Email(userInput.Email);
            var user  = new User(login, email, userInput.Name);

            if (user.Invalid)
            {
                return(user);
            }

            _respository.Add(user);
            _uow.Commit();
            return(user);
        }
 public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(new
             {
                 success = true,
                 data = result
             }));
         }
         catch (Exception ex)
         {
             //logar error
             return(BadRequest(new
             {
                 succssesResult = false,
                 error = new[] { $"Houve um erro interno: {ex.Message}" }
             }));
         }
     }
     else
     {
         return(BadRequest(new
         {
             success = false,
             errors = notifications
         }));
     }
 }
Example #12
0
        public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
        {
            if (!notifications.Any())
            {
                try
                {
                    bool ExistsNofications = false;

                    _uow.OpenTransaction();

                    await _uow.Commit();


                    return(Ok(new
                    {
                        success = true,
                        data = result
                    }));
                }
                catch (Exception ex)
                {
                    return(await TryErrors(ex));
                }
            }
            else
            {
                _uow.Rollback();
                return(BadRequest(new { success = false, errors = notifications.GroupBy(x => new { x.Property, x.Message }).Select(x => x.FirstOrDefault()) }));
            }
        }
Example #13
0
 public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(new
             {
                 success = true,
                 data = result
             }));
         }
         catch
         {
             //Elmah(log error);
             return(BadRequest(new
             {
                 success = false,
                 errors = new[] { "A Internal Failure occurred on the server." }
             }));
         }
     }
     else
     {
         return(BadRequest(new
         {
             success = false,
             errors = notifications
         }));
     }
 }
Example #14
0
 public async Task <IActionResult> Response(object Resultado, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(new
             {
                 sucesso = true,
                 data = Resultado
             }));
         }
         catch
         {
             return(BadRequest(new
             {
                 sucesso = false,
                 erro = new[] { "Ocorreu uma falha interna" }
             }));
         }
     }
     else
     {
         return(BadRequest(new
         {
             sucesso = false,
             erro = notifications
         }));
     }
 }
Example #15
0
        private void btnUOW_Click(object sender, EventArgs e)
        {
            IUow uow = FactoryDAL <IUow> .Create("EFUow");

            try
            {
                CustomerBase cust1 = new CustomerBase();
                cust1.CustomerType = "Lead";
                cust1.CustomerName = "Cust1";
                cust1.BillDate     = Convert.ToDateTime(txtBillingDate.Text);
                IRepository <CustomerBase> dal1 = FactoryDAL <IRepository <CustomerBase> > .Create(DalLayer.Text);

                dal1.SetUnitOfWork(uow);
                dal1.Add(cust1);

                CustomerBase cust2 = new CustomerBase();
                cust2.CustomerType = "Lead";
                cust2.CustomerName = "Cust2";
                cust2.BillDate     = Convert.ToDateTime(txtBillingDate.Text);
                cust2.Address      = "111111111111111111111111111111111111111111111111111111111111111";
                IRepository <CustomerBase> dal2 = FactoryDAL <IRepository <CustomerBase> > .Create(DalLayer.Text);

                dal2.SetUnitOfWork(uow);
                dal2.Add(cust2);

                uow.Commit();
            }
            catch (Exception ex)
            {
                uow.RollBack();
                MessageBox.Show(ex.Message);
            }
        }
 public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(new
             {
                 success = true,
                 data = result
             }));
         }
         catch (Exception ex)
         {
             return(BadRequest(new
             {
                 success = false,
                 data = new[] { "Ocorreu uma falha  interna no servidor.", ex.Source + " - " + ex.Message }
             }));
         }
     }
     else
     {
         return(Ok(new
         {
             success = false,
             data = notifications
         }));
     }
 }
Example #17
0
 public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(result));
         }
         catch (Exception e)
         {
             //Logar o erro (Elmah)
             return(StatusCode(500, new
             {
                 errors = new { causa = e }
             }));
         }
     }
     else
     {
         return(BadRequest(new
         {
             errors = notifications
         }));
     }
 }
Example #18
0
        public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
        {
            if (notifications.Any())
            {
                try
                {
                    _uow.Commit();

                    return(Ok(new
                    {
                        success = true,
                        data = result
                    }));
                }
                catch (Exception ex)
                {
                    return(BadRequest(new
                    {
                        success = false,
                        errors = new[] { "Ocorreu um erro no servidor." }
                    }));
                }
            }
            else
            {
                return(BadRequest(new
                {
                    success = false,
                    errors = notifications
                }));
            }
        }
Example #19
0
        public OperationResult PerformSale(byte premiseId, List <SaleLineDto> saleLineDtos, int sessionId, string saleDocumentType, string customerName, string dniRuc)
        {
            if (saleLineDtos == null || saleLineDtos.Count == 0)
            {
                throw new ArgumentNullException("saleLineDtos");
            }

            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions {
                IsolationLevel = IsolationLevel.RepeatableRead
            }))
            {
                var operationResult = CheckStockForProducts(premiseId, saleLineDtos);
                if (!operationResult.Succeed)
                {
                    scope.Dispose();
                    return(operationResult);
                }
                //Movements
                var productMovements = CreateSaleProductMovements(premiseId, saleLineDtos, sessionId);
                DiscountProductsPremiseStock(premiseId, saleLineDtos);
                //Cash
                DiscountAmountForCashbox(GetSaleAmount(saleLineDtos));
                var cashMovementCreated = CreateCashMovement(sessionId, GetSaleAmount(saleLineDtos),
                                                             Constants.CashMovementCategory.Sale, Constants.CashMovementType.In);
                //Sale and Sale Document
                CreateSaleInfo(sessionId, cashMovementCreated, GetSaleDocumentObject(saleDocumentType),
                               customerName, saleLineDtos, dniRuc, productMovements);
                uow.Commit();
                scope.Complete();
            }
            //TODO: Pending perform printing actions!!
            return(new OperationResult {
                Succeed = true
            });
        }
 public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(new
             {
                 success = true,
                 data = result
             }));
         }
         catch
         {
             // Logar o erro (Elmah)
             return(BadRequest(new
             {
                 success = false,
                 errors = new[] { "Ocorreu uma falha interna no servidor." }
             }));
         }
     }
     else
     {
         return(BadRequest(new
         {
             success = false,
             errors = notifications
         }));
     }
 }
Example #21
0
 public async Task <IActionResult> Response(object result, IEnumerable <Notification> notifications)
 {
     if (!notifications.Any())
     {
         try
         {
             _uow.Commit();
             return(Ok(new
             {
                 success = true,
                 data = result
             }));
         }
         catch
         {
             //log the error with something (like Elmah)
             return(BadRequest(new
             {
                 success = false,
                 errors = new[] { "A Internal-Server error occured." }
             }));
         }
     }
     else
     {
         return(BadRequest(new
         {
             success = false,
             errors = notifications
         }));
     }
 }
        public void PlaceOrder(Guid customerId, string productCode, int quantity)
        {
            var result = PotentialOrder.BuildOrder(customerId, productCode, quantity);

            _uow.Repository.Save(result.Entity);
            _uow.Bus.Publish(result.Event);
            _uow.Commit();
        }
        public async Task <InserirItemResponse> InserirItem([FromBody] InserirItemCommand command)
        {
            var response = await _inserirItemCommandHandler.Handler(command);

            _uow.Commit();

            return(response);
        }
Example #24
0
        public void Handle(PotentialOrderPlaced evt)
        {
            var result = OrderFullFullfilment.CreateFrom(evt.Id, evt.ProductCode, evt.Quantity);

            _uow.Repository.Save(result.Entity);
            _uow.Bus.Publish(result.Event);
            _uow.Commit();
        }
Example #25
0
        public bool Commit()
        {
            if (_uow.Commit())
            {
                return(true);
            }

            return(false);
        }
Example #26
0
        public bool Commit()
        {
            if (HasNotification())
            {
                return(false);
            }

            _uow.Commit();
            return(true);
        }
Example #27
0
        public async Task <ISaida> CadastrarCategoria(CadastrarCategoriaEntrada cadastroEntrada)
        {
            // Verifica se as informações para cadastro foram informadas corretamente
            if (cadastroEntrada.Invalido)
            {
                return(new Saida(false, cadastroEntrada.Mensagens, null));
            }

            // Verifica se já existe uma categoria com o mesmo nome e mesmo tipo
            this.NotificarSeVerdadeiro(
                await _categoriaRepositorio.VerificarExistenciaPorNomeTipo(cadastroEntrada.IdUsuario, cadastroEntrada.Nome, cadastroEntrada.Tipo),
                CategoriaMensagem.Categoria_Com_Mesmo_Nome_Tipo);

            if (cadastroEntrada.IdCategoriaPai.HasValue)
            {
                var categoriaPai = await _categoriaRepositorio.ObterPorId(cadastroEntrada.IdCategoriaPai.Value);

                // Verifica se a categoria pai existe
                this.NotificarSeNulo(categoriaPai, string.Format(CategoriaMensagem.Categoria_Pai_Nao_Existe, cadastroEntrada.IdCategoriaPai.Value));

                if (categoriaPai != null)
                {
                    // Verificar se o tipo da categoria é igual ao tipo da categoria pai
                    this.NotificarSeDiferentes(cadastroEntrada.Tipo, categoriaPai.Tipo, CategoriaMensagem.Tipo_Nao_Pode_Ser_Diferente_Tipo_Categoria_Pai);
                }
            }

            if (this.Invalido)
            {
                return(new Saida(false, this.Mensagens, null));
            }

            var categoria = new Categoria(cadastroEntrada);

            await _categoriaRepositorio.Inserir(categoria);

            await _uow.Commit();

            return(_uow.Invalido
                ? new Saida(false, _uow.Mensagens, null)
                : new Saida(true, new[] { CategoriaMensagem.Categoria_Cadastrada_Com_Sucesso }, new CategoriaSaida(await _categoriaRepositorio.ObterPorId(categoria.Id))));
        }
        public async Task <ISaida> CadastrarLancamento(CadastrarLancamentoEntrada cadastroEntrada)
        {
            // Verifica se as informações para cadastro foram informadas corretamente
            if (cadastroEntrada.Invalido)
            {
                return(new Saida(false, cadastroEntrada.Mensagens, null));
            }

            // Verifica se a categoria existe a partir do ID informado.
            this.NotificarSeFalso(await _categoriaRepositorio.VerificarExistenciaPorId(cadastroEntrada.IdUsuario, cadastroEntrada.IdCategoria), CategoriaMensagem.Id_Categoria_Nao_Existe);

            // Verifica se a conta existe a partir do ID informado.
            this.NotificarSeFalso(await _contaRepositorio.VerificarExistenciaPorId(cadastroEntrada.IdUsuario, cadastroEntrada.IdConta), ContaMensagem.Id_Conta_Nao_Existe);

            // Verifica se a pessoa existe a partir do ID informado.
            if (cadastroEntrada.IdPessoa.HasValue)
            {
                this.NotificarSeFalso(await _pessoaRepositorio.VerificarExistenciaPorId(cadastroEntrada.IdUsuario, cadastroEntrada.IdPessoa.Value), PessoaMensagem.Id_Pessoa_Nao_Existe);
            }

            // Verifica se a parcela existe a partir do ID informado.
            if (cadastroEntrada.IdParcela.HasValue)
            {
                this.NotificarSeFalso(await _parcelaRepositorio.VerificarExistenciaPorId(cadastroEntrada.IdUsuario, cadastroEntrada.IdParcela.Value), ParcelaMensagem.Id_Parcela_Nao_Existe);
            }

            if (this.Invalido)
            {
                return(new Saida(false, this.Mensagens, null));
            }

            var lancamento = new Lancamento(cadastroEntrada);

            await _lancamentoRepositorio.Inserir(lancamento);

            await _uow.Commit();

            return(_uow.Invalido
                ? new Saida(false, _uow.Mensagens, null)
                : new Saida(true, new[] { LancamentoMensagem.Lancamento_Cadastrado_Com_Sucesso }, new LancamentoSaida(await _lancamentoRepositorio.ObterPorId(lancamento.Id))));
        }
Example #29
0
        public IActionResult CheckOut([FromBody] CheckOutDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _unitOfWork.CheckOutRepository.Insert(_mapper.Map <CheckOut>(dto));
            _unitOfWork.Commit();

            var id = _unitOfWork.CheckOutRepository.List().OrderByDescending(x => x.Id).FirstOrDefault().Id;

            _unitOfWork.CartRepository.Insert(dto.Cart.Select(x => new Cart
            {
                CheckOutId  = id,
                ProductId   = int.Parse(x.Id),
                Amount      = x.Amount,
                Image       = x.Image,
                Name        = x.Name,
                NewQuantity = x.NewQuantity,
                OldQuantity = x.OldQuantity,
                TotalAmount = x.TotalAmount
            }).FirstOrDefault());

            foreach (var item in dto.Cart)
            {
                var product = _unitOfWork.ProductRepository.GetById(long.Parse(item.Id));
                if (product != null)
                {
                    product.Quantity -= item.NewQuantity;
                    _unitOfWork.ProductRepository.Update(_mapper.Map <Product>(product));
                }
            }

            _unitOfWork.Commit();
            return(Ok(true));
        }
Example #30
0
        public IHttpActionResult SalveTask([FromBody] CommandsTasks commands)
        {
            if (commands != null)
            {
                var result = _taskService.save(commands);
                _uow.Commit();
                return(Ok(new
                {
                    success = true,
                    data = result
                }));
            }

            return(NotFound());
        }