/// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var queue = await StateManager.GetOrAddAsync <IReliableConcurrentQueue <Order> >(StateName);

            var statistics = await StateManager.GetOrAddAsync <IReliableDictionary2 <string, string> >(StatisticsName);

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                using (var tx = StateManager.CreateTransaction())
                {
                    var result = await queue.TryDequeueAsync(tx, cancellationToken);

                    if (result.HasValue)
                    {
                        var currentStatistics = await repository.AddOrderAsync(result.Value, cancellationToken);

                        if (currentStatistics != null)
                        {
                            var json = JsonConvert.SerializeObject(currentStatistics);
                            await statistics.AddOrUpdateAsync(tx, $"{result.Value.OrderDateTime:yyyyMMdd}", json, (id, stats) => json);
                        }

                        await tx.CommitAsync();
                    }
                    else
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
                    }
                }
            }
        }
        public async Task <ActionResult> Order()
        {
            var cart = await _repository.GetCartListAsync(User.Identity.GetUserId());

            if (cart == null || cart.Count() == 0)
            {
                return(RedirectToAction("List", "ShoppingCart"));
            }

            var order = new Orders()
            {
                UserId = User.Identity.GetUserId(),
                Date   = DateTime.Now,
                Status = "OCZEKUJĄCE"
            };

            foreach (var item in cart)
            {
                var product = await _repository.GetProductAsync(item.ProductId);

                order.Name  += item.Quantity + " x " + product.Name + ", ";
                order.Price += item.Price;

                await _repository.ReduceProductStack(product.Id, item.Quantity);
            }

            await _repository.AddOrderAsync(order);

            await _repository.ClearCartAsync(order.UserId);

            return(View(order));
        }
Beispiel #3
0
        public async Task <OrderCreateViewModel> AddOrder(OrderCreateViewModel model)
        {
            var order = new Order
            {
                isOrder     = true,
                report_date = model.reportDate,
                shop_id     = model.shopId
            };

            order.OrderDetails = model.products.Select(p => new OrderDetail
            {
                prod_id = p.id,
                cost    = p.price.Value,
                count   = p.count
            }).ToList();

            var id = 0;

            try
            {
                id = await ordersRepo.AddOrderAsync(order);

                var orderDal = await ordersRepo.GetByIdAsync(id);

                await strategy.UpdateAverageCost(Direction.Order, orderDal);
            }
            catch (Exception)
            {
                throw new Exception("Случилась ошибка при добавлении прихода.");
            }

            model.id = id;
            return(model);
        }
        //public  IActionResult AddOrder(Order model)
        //{
        //    if (model == null)
        //    {
        //        return BadRequest();
        //    }
        //    var _order = _repo.AddOrderAsync(model);
        //    if (_order != null)
        //    {
        //        return Ok();
        //    }
        //    return BadRequest();
        //}
        public async Task <ActionResult <Order> > AddOrder(Order model)
        {
            if (model == null)
            {
                return(BadRequest());
            }
            var _order = await _repo.AddOrderAsync(model);

            if (_order != null)
            {
                return(Ok());
            }
            return(BadRequest());
        }
Beispiel #5
0
        private async void OnSave()
        {
            try
            {
                UpdateCustomer(Order, _editingOrder);

                await _repo.AddOrderAsync(_editingOrder);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }

            Done();
        }
        public async Task Consume(ConsumeContext <BasketCheckoutEvent> context)
        {
            var basketCheckoutDetails = (BasketCheckoutEvent)context.Message;


            // if (!await _tokenValidationService.ValidateTokenAsync(basketCheckoutDetails.SecurityContext.AccessToken, basketCheckoutDetails.CreationDateTime))
            // {
            //     _logger.LogError("Token is not valid! Order was not completed.");
            //     return;
            // }

            var order = new Order
            {
                UserId      = basketCheckoutDetails.UserId,
                OrderPaid   = false,
                OrderPlaced = DateTime.Now,
                TotalPrice  = basketCheckoutDetails.BasketTotal,
                OrderTotal  = (basketCheckoutDetails.Basket != null) ? basketCheckoutDetails.Basket.Count : -1,
            };

            order.OrderId    = Guid.NewGuid();
            order.OrderItems = new List <OrderItem>();
            foreach (var bLine in basketCheckoutDetails.Basket)
            {
                OrderItem item = new OrderItem
                {
                    OrderLineId = Guid.NewGuid(),
                    OrderId     = order.OrderId,
                    Price       = bLine.Price,
                    Quantity    = bLine.Quantity,
                    TruckId     = bLine.TruckId,
                    TruckName   = bLine.Name,
                    PhotoPath   = bLine.DefaultPhotoPath,
                };
                order.OrderItems.Add(item);
            }

            var returnOrder = await _service.AddOrderAsync(order);

            await UpdateInventory(context.Message.Basket);

            _logger.LogInformation($"Order added {returnOrder.OrderId}");
        }
Beispiel #7
0
        /// <summary>
        /// Inserting product
        /// </summary>
        /// <param name="user">user info</param>
        /// <param name="product">product view model</param>
        public async Task <ProductDetailViewModel> AddProduct(UserProfile user, ProductDetailViewModel product)
        {
            if (string.IsNullOrEmpty(product.ProdName))
            {
                throw new Exception("Наименование товара не может быть пустым.");
            }
            var business = await _businessRepo.GetByIdAsync(user.business_id.Value);

            //create product model
            var prod = new Product
            {
                name        = product.ProdName,
                business_id = business.id,
                unit_id     = product.UnitId,
                attr1       = product.VendorCode,
                attr9       = product.Size,
                attr10      = product.Color
            };


            //add price link
            prod.Prices.Add(new Price {
                price = product.Price
            });
            int pId = 0;

            try
            {
                //await foldersDataService.AddFoldersByPath(product.Category, business.id);
                prod.folder_id = await _foldersDataService.GetFolderIdByPath(product.Category, business.id);

                //add with repo
                pId = _prodRepo.AddProduct(prod);
            }
            catch (Exception)
            {
                throw new Exception("Не получилось добавить товар в базу. Проверьте правильность заполнения полей.");
            }

            if (!string.IsNullOrEmpty(product.ImgBase64))
            {
                try
                {
                    using (var stream = product.img.OpenReadStream())
                    {
                        var bytes    = ReadToEnd(stream);
                        var memory   = new MemoryStream(bytes);
                        var imgParts = product.ImgBase64.Split(".");
                        var imgUrl   = await _dbBase.Upload(memory,
                                                            "/" + ". " + business.name + "/" +
                                                            pId + "." + product.ProdName + "." + imgParts[imgParts.Length - 1]);

                        var img = new Image
                        {
                            img_url      = imgUrl,
                            prod_id      = pId,
                            img_name     = product.ProdName,
                            img_type     = imgParts[imgParts.Length - 1],
                            img_url_temp = MakeTemporary(imgUrl),
                            img_path     = product.Category
                        };
                        _imgRepo.Add(img);
                    }
                }
                catch (Exception)
                {
                    throw new Exception("Не получилось добавить картинку товара. Попробуйте снова.");
                }
            }

            var dt = DateTime.Now;

            if (product.Cost.HasValue && product.Cost < 0)
            {
                throw new Exception("Себестоимость должна быть > 0.");
            }
            if (product.Cost.HasValue && product.Cost >= 0)
            {
                if (product.Stocks != null && product.Stocks.Any())
                {
                    foreach (var s in product.Stocks)
                    {
                        var order = new Order
                        {
                            isOrder      = true,
                            report_date  = dt,
                            shop_id      = s.ShopId,
                            OrderDetails = new List <OrderDetail>
                            {
                                new OrderDetail
                                {
                                    prod_id = pId,
                                    cost    = product.Cost.Value,
                                    count   = s.Stock
                                }
                            }
                        };

                        try
                        {
                            var orderId = await _ordersRepo.AddOrderAsync(order);

                            var orderDal = await _ordersRepo.GetByIdWithMultiAsync(orderId);

                            await _strategy.UpdateAverageCost(Direction.Order, orderDal);
                        }
                        catch (Exception)
                        {
                            throw new Exception("Не удалось добавить остаток на склад.");
                        }
                    }
                }
                else
                {
                    var cost = new Cost
                    {
                        prod_id = pId,
                        value   = product.Cost
                    };
                    await _costRepo.AddCostAsync(cost);
                }
            }

            product.Id = pId;
            return(product);
        }