Esempio n. 1
0
        public async Task CreateOrdersAsync(IEnumerable <int> restaurantIds)
        {
            var existingRestaurantIds = await _context.Restaurants
                                        .Where(r => restaurantIds.Contains(r.Id))
                                        .Select(r => r.Id)
                                        .ToListAsync();

            var ordersToAdd = existingRestaurantIds
                              .Select(id => new Order
            {
                Username     = Context.User.GetSub(),
                OrderedAt    = DateTime.Now.Truncate(),
                CompletedAt  = null,
                RestaurantId = id,
            })
                              .ToList();

            await _context.Orders.AddRangeAsync(ordersToAdd);

            await _context.SaveChangesAsync();

            _updateService.SendRestaurantsUpdated(existingRestaurantIds).Forget();

            var newOrderIds = ordersToAdd.Select(o => o.Id).ToList();

            _updateService.SendDispatchPendingUpdate(newOrderIds).Forget();
            _updateService.SendUserOrdersCreated(newOrderIds, Context.User.GetSub()).Forget();
        }
Esempio n. 2
0
        public async Task <OperationResult <Unit> > Handle(DeleteDeliveryRequest request,
                                                           CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            _logger.LogInformation($"Delete deliveryRequest for Id {request.DeliveryId}");

            try
            {
                var orderDelivery =
                    await _dbContext.Deliveries.FirstOrDefaultAsync(x => x.DeliveryId == request.DeliveryId,
                                                                    cancellationToken);

                if (orderDelivery == null)
                {
                    return(OperationResult <Unit> .Error(OperationErrorReason.ResourceNotFound,
                                                         $"The deliveryRequest not found for Id {request.DeliveryId}"));
                }

                _dbContext.Deliveries.Remove(orderDelivery);
                await _dbContext.SaveChangesAsync(cancellationToken);

                return(OperationResult <Unit> .Success(Unit.Value));
            }
            catch (Exception e)
            {
                var message = $"Error in deleteing the deliveryRequest for Id {request.DeliveryId}";

                _logger.LogError(message, e);
                return(OperationResult <Unit> .Error(message));
            }
        }
Esempio n. 3
0
        public async Task <OperationResult <OrderDeliveryDto> > Handle(NewDeliveryRequest request,
                                                                       CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var orderNumber = request.DeliveryRequestDto?.Order?.OrderNumber;

            _logger.LogInformation($"Create deliveryRequest for order {orderNumber}");

            try
            {
                var orderDelivery = _mapper.Map <OrderDelivery>(request.DeliveryRequestDto);

                _dbContext.Deliveries.Add(orderDelivery);
                await _dbContext.SaveChangesAsync(cancellationToken);

                _logger.LogInformation($"Delivery for {orderNumber} has been created successfully");

                var result = _mapper.Map <OrderDeliveryDto>(orderDelivery);
                return(OperationResult <OrderDeliveryDto> .Success(result));
            }
            catch (Exception e)
            {
                var message = $"Error in creating the deliveryRequest for order {orderNumber}";

                _logger.LogError(message, e);
                return(OperationResult <OrderDeliveryDto> .Error(message));
            }
        }
Esempio n. 4
0
        public async Task <bool> AddDelivery(int BookingId)
        {
            //List<Customer> reservationList = new List<Customer>();
            using (var httpClient = new HttpClient())
            {
                try
                {
                    using (var response = await httpClient.PostAsJsonAsync("http://localhost:57207/api/Booking/GetDetail", BookingId))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        //reservationList = apiResponse;
                        //reservationList = JsonConvert.DeserializeObject<List<Customer>>(apiResponse);
                        result = (Booking)JsonConvert.DeserializeObject(apiResponse, typeof(Booking));
                        if (result == null)
                        {
                            throw new Exception("Exception in fetching");
                        }
                        Delivery deliveryobj = new Delivery()
                        {
                            BookingId        = result.BookingId,
                            BicycleId        = result.BicycleId,
                            UserName         = result.UserName,
                            DateTime         = result.DateTime,
                            BicycleNumber    = result.BicycleNumber,
                            DeliveryAddress  = result.DeliveryAddress,
                            Deliverylat      = result.Latitude,
                            Deliverylng      = result.Longitude,
                            OrderTime        = DateTime.Now,
                            DeliverTime      = default(DateTime),
                            Cancelationtime  = default(DateTime),
                            ConfirmationTime = default(DateTime),
                            Status           = "Intial",
                            DeliveryUserName = ""
                        };

                        await db.delivery.AddAsync(deliveryobj);

                        await db.SaveChangesAsync();
                    }
                    return(true);
                }
                catch (Exception exp)
                {
                    throw exp;
                }
            }
        }
Esempio n. 5
0
        public async Task CompleteOrderAsync(int orderId)
        {
            var order = await _context.Orders.SingleAsync(o => o.Id == orderId);

            if (order.CompletedAt != null)
            {
                throw new AlreadyCompletedOrderException(orderId);
            }

            order.CompletedAt = DateTime.Now.Truncate();
            await _context.SaveChangesAsync();

            _updateService.SendDispatchOrderCompleted(orderId).Forget();
            _updateService.SendRestaurantsUpdated(new[] { order.RestaurantId }).Forget();
            _updateService.SendUserOrdersUpdated(new[] { orderId }, order.Username).Forget();
        }
Esempio n. 6
0
        public async Task <OperationResult <Unit> > Handle(ChangeDeliveryStateRequest request,
                                                           CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            _logger.LogInformation($"Apply {request.Action} action on delivery Id {request.DeliveryId}");

            try
            {
                var orderDelivery = await _dbContext.Deliveries
                                    .FirstOrDefaultAsync(x => x.DeliveryId == request.DeliveryId, cancellationToken);

                if (orderDelivery == null)
                {
                    return(OperationResult <Unit> .Error(OperationErrorReason.ResourceNotFound,
                                                         $"The deliveryRequest not found for Id {request.DeliveryId}"));
                }

                var(allowed, target) = _stateRuleEngine.ApplyAction(request.Action,
                                                                    new ActionContext(orderDelivery, request.RequesterRole));

                if (!allowed)
                {
                    return(OperationResult <Unit> .Error(OperationErrorReason.InvalidOperation, $"{request.Action} is not possible on delivery in {orderDelivery.State} state"));
                }

                orderDelivery.State = target.Value;
                await _dbContext.SaveChangesAsync(cancellationToken);

                _logger.LogInformation($"Delivery for Id {request.DeliveryId} has been updated successfully");

                return(OperationResult <Unit> .Success(Unit.Value));
            }
            catch (Exception e)
            {
                var message = $"Error in updating the deliveryRequest for for Id {request.DeliveryId}";

                _logger.LogError(message, e);
                return(OperationResult <Unit> .Error(message));
            }
        }
        public async Task <OperationResult <OrderDeliveryDto> > Handle(UpdateDeliveryRequest request,
                                                                       CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            _logger.LogInformation($"Update deliveryRequest for Id {request.DeliveryId}");

            try
            {
                var orderDelivery = await _dbContext.Deliveries
                                    .FirstOrDefaultAsync(x => x.DeliveryId == request.DeliveryId, cancellationToken);

                if (orderDelivery == null)
                {
                    return(OperationResult <OrderDeliveryDto> .Error(OperationErrorReason.ResourceNotFound,
                                                                     $"The deliveryRequest not found for Id {request.DeliveryId}"));
                }

                orderDelivery.Order        = _mapper.Map <Order>(request.DeliveryRequestDto.Order);
                orderDelivery.Recipient    = _mapper.Map <Recipient>(request.DeliveryRequestDto.Recipient);
                orderDelivery.AccessWindow = _mapper.Map <AccessWindow>(request.DeliveryRequestDto.AccessWindow);
                _dbContext.Update(orderDelivery);

                await _dbContext.SaveChangesAsync(cancellationToken);

                _logger.LogInformation($"Delivery for Id {request.DeliveryId} has been updated successfully");

                var result = _mapper.Map <OrderDeliveryDto>(orderDelivery);
                return(OperationResult <OrderDeliveryDto> .Success(result));
            }
            catch (Exception e)
            {
                var message = $"Error in updating the deliveryRequest for for Id {request.DeliveryId}";

                _logger.LogError(message, e);
                return(OperationResult <OrderDeliveryDto> .Error(message));
            }
        }
        [AllowAnonymous] //Permite o acesso de usuários não autenticados a se registrar.
        public async Task <IActionResult> Register(User user)
        {
            var userWithSameEmail = _dbContext.Users.SingleOrDefault(u => u.Email == user.Email); //Verifica se ja existe o mesmo email cadastrado no banco de dados

            if (userWithSameEmail != null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest));
            }

            //Cria um objeto User com os dados informados e realiza a proteção da senha por Hash.
            var userObj = new User
            {
                Name     = user.Name,
                Email    = user.Email,
                Password = SecurePasswordHasherHelper.Hash(user.Password),
                Role     = "User"
            };

            //Adiciona e salva o novo usuário ao banco de dados e retorna o StatusCode201Created.
            _dbContext.Users.Add(userObj);
            await _dbContext.SaveChangesAsync();

            return(StatusCode(StatusCodes.Status201Created));
        }