Exemple #1
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);
        }
        public async Task <int> Insert(Product product)
        {
            using (var session = new Session())
            {
                var uow = session.UnitOfWork;
                _productRepository     = new ProductRepository(uow);
                _priceRepository       = new PriceRepository(uow);
                _businessRepository    = new BusinessRepository(uow);
                _imageRepository       = new ImagesRepository(uow);
                _strategy              = new FifoStrategy();
                _ordersRepository      = new OrdersRepository(uow);
                _orderDetailRepository = new OrderDetailRepository(uow);
                _costRepository        = new CostRepository(uow);
                var imgPath = string.Empty;

                uow.Begin();
                try
                {
                    var productId = await _productRepository.InsertUow(product);

                    if (product.Price != null && product.Price.price.HasValue)
                    {
                        await _priceRepository.InsertUow(new Price { price = product.Price.price, prod_id = productId });
                    }
                    else
                    {
                        await _priceRepository.InsertUow(new Price { prod_id = productId });
                    }

                    if (!string.IsNullOrEmpty(product.ImgBase64) && product.ImgMemoryStream != null)
                    {
                        var business = await _businessRepository.GetByIdUow(product.business_id.Value);

                        var imgParts = product.ImgBase64.Split('.');
                        imgPath = "/products/" + business.id + ". " + business.name + "/" +
                                  productId + "." + product.name + "." + imgParts.Last();
                        var imgUrl = await _dbBase.Upload(product.ImgMemoryStream, imgPath);

                        var img = new Image
                        {
                            img_url      = imgUrl,
                            prod_id      = productId,
                            img_name     = product.name,
                            img_type     = imgParts.LastOrDefault(),
                            img_url_temp = MakeTemporary(imgUrl),
                            img_path     = product.Category
                        };
                        await _imageRepository.InsertUow(img);
                    }

                    if (product.Orders.Any())
                    {
                        foreach (var order in product.Orders)
                        {
                            var orderId = await _ordersRepository.InsertUow(order);

                            foreach (var orderDetail in order.OrderDetails)
                            {
                                orderDetail.prod_id  = productId;
                                orderDetail.order_id = orderId;
                                await _orderDetailRepository.InsertUow(orderDetail);
                            }

                            var orderDal = await _ordersRepository.GetByIdWithMultiUow(orderId);

                            await _strategy.UpdateAverageCostUow(Direction.Order, orderDal, uow);
                        }
                    }
                    else if (product.Cost.Any())
                    {
                        var cost = product.Cost.FirstOrDefault();
                        if (cost != null && cost.value.HasValue)
                        {
                            cost.prod_id = productId;
                            await _costRepository.InsertUow(cost);
                        }
                        else
                        {
                            await _costRepository.InsertUow(new Cost { prod_id = productId });
                        }
                    }

                    uow.Commit();
                    return(productId);
                }
                catch (Exception e)
                {
                    uow.RollBack();
                    if (!string.IsNullOrEmpty(imgPath))
                    {
                        await _dbBase.Delete(imgPath);
                    }

                    throw e;
                }
            }
        }