private async Task InitializeProductsAsync()
        {
            if (await _db.Products.AnyAsync())
            {
                return;
            }

            var db = _db.Database;

            using (var transaction = await db.BeginTransactionAsync().ConfigureAwait(false))
            {
                await _db.Sections.AddRangeAsync(TestData.Sections).ConfigureAwait(false);

                await db.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Sections] ON");

                await _db.SaveChangesAsync().ConfigureAwait(false);

                await db.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }

            using (var transaction = await db.BeginTransactionAsync().ConfigureAwait(false))
            {
                await _db.Brands.AddRangeAsync(TestData.Brands).ConfigureAwait(false);

                await db.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Brands] ON");

                await _db.SaveChangesAsync().ConfigureAwait(false);

                await db.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }

            using (var transaction = await db.BeginTransactionAsync().ConfigureAwait(false))
            {
                await _db.Products.AddRangeAsync(TestData.Products).ConfigureAwait(false);

                await db.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Products] ON");

                await _db.SaveChangesAsync().ConfigureAwait(false);

                await db.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Products] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 2
0
        public async Task AddToRoleAsync([FromBody] User user, string role, [FromServices] WebStoreDB db)
        {
            // [FromServices] WebStoreDB db - так можно получать доступ к сервисам напрямую
            await _UserStore.AddToRoleAsync(user, role);

            await db.SaveChangesAsync();
        }
        public async Task RemoveLoginAsync([FromBody] User user, string LoginProvider, string ProviderKey,
                                           [FromServices] WebStoreDB db)
        {
            await _UserStore.RemoveLoginAsync(user, LoginProvider, ProviderKey);

            await db.SaveChangesAsync();
        }
Exemplo n.º 4
0
        public async Task <bool> RemoveLoginAsync([FromBody] User user, string loginProvider, string providerKey, [FromServices] WebStoreDB dB)
        {
            await _userStore.RemoveLoginAsync(user, loginProvider, providerKey);

            await dB.SaveChangesAsync();

            return(user.PhoneNumberConfirmed);
        }
Exemplo n.º 5
0
        public async Task <Order> CreateOrder(string UserName, CartViewModel Cart, OrderViewModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} не найден в БД");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = OrderModel.Name,
                Address = OrderModel.Address,
                Phone   = OrderModel.Phone,
                User    = user,
                Date    = DateTime.Now,
            };

            var product_ids   = Cart.Items.Select(i => i.Product.Id).ToArray();
            var cart_products = await _db.Products
                                .Where(p => product_ids.Contains(p.Id))
                                .ToArrayAsync();

            var items =
                from cart_item in Cart.Items
                join product in cart_products
                on cart_item.Product.Id equals product.Id
                select new OrderItem
            {
                Order    = order,
                Price    = product.Price,
                Quantity = cart_item.Quantity,
                Product  = product
            };

            foreach (var order_item in items)
            {
                order.Items.Add(order_item);
            }

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order);
        }
Exemplo n.º 6
0
        public async Task <Order> CreateOrder(string userName, CartViewModel cartViewModel,
                                              OrderViewModel orderViewModel)
        {
            var user = await _userManager.FindByNameAsync(userName : userName);

            Order order;

            await using (var transaction = await _webStoreDb.Database.BeginTransactionAsync())
            {
                order = new Order
                {
                    User    = user,
                    Address = orderViewModel.Address,
                    Name    = orderViewModel.Name,
                    Phone   = orderViewModel.Phone,
                    Date    = DateTime.Now
                };

                await _webStoreDb.Orders.AddAsync(entity : order);


                foreach (var(productViewModel, quantity) in cartViewModel.Items)
                {
                    var product = await _webStoreDb.Products.FirstOrDefaultAsync(p => p.Id == productViewModel.Id);

                    if (product is null)
                    {
                        return(null);
                    }

                    var orderItem = new OrderItem
                    {
                        Order    = order,
                        Quantity = quantity,
                        Price    = productViewModel.Price,
                        Product  = product
                    };
                    await _webStoreDb.OrderItems.AddAsync(orderItem);
                }



                await _webStoreDb.SaveChangesAsync();

                await _webStoreDb.Database.CommitTransactionAsync();
            }

            return(order);
        }
Exemplo n.º 7
0
        public async Task <OrderDto> CreateOrder(string UserName, CreateOrderModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} на найден");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = OrderModel.Order.Name,
                Address = OrderModel.Order.Address,
                Phone   = OrderModel.Order.Phone,
                User    = user,
                Date    = DateTime.Now
            };

            foreach (var item in OrderModel.Items)
            {
                var product = await _db.Products.FindAsync(item.Id);

                if (product is null)
                {
                    continue;
                }


                var order_item = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price, // здесь может быть применена скидка
                    Quantity = item.Quantity,
                    Product  = product
                };
                order.Items.Add(order_item);
            }

            await _db.Orders.AddAsync(order);

            //await _db.OrderItems.AddRangeAsync(order.Items); // излишняя операция - элементы заказа и так попадут в БД
            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order.ToDto());
        }
Exemplo n.º 8
0
        public async Task CreateOrder(OrderViewModel viewModel)
        {
            Order order = await OrderViewModelToOrder(viewModel);

            if (!Validator.TryValidateObject(order, new ValidationContext(order), null))
            {
                throw new InvalidOperationException("Модель Order не валидна");
            }

            await _dB.Orders.AddAsync(order);

            await _dB.SaveChangesAsync();

            _cart.Clear();
        }
Exemplo n.º 9
0
        public async Task <OrderDTO> CreateOrder(string userName, CreateOrderModel orderModel)
        {
            var user = await userManager.FindByNameAsync(userName);

            if (user is null)
            {
                throw new InvalidOperationException($"User {userName} not exist");
            }

            await using var transaction = await db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = orderModel.Order.Name,
                Address = orderModel.Order.Address,
                Phone   = orderModel.Order.Phone,
                User    = user,
                Date    = DateTime.Now,
                Items   = new List <OrderItem>()
            };

            foreach (var item in orderModel.Items)
            {
                var product = await db.Products.FindAsync(item.Id);

                if (product is null)
                {
                    throw new InvalidOperationException($"Product id:{item.Id} not exist");
                }

                var orderItem = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price,
                    Quantity = item.Quantity,
                    Product  = product
                };
                order.Items.Add(orderItem);
            }

            await db.Orders.AddAsync(order);

            await db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(mapper.Map <OrderDTO>(order));
        }
        public async Task <OrderDTO> CreateOrder(string UserName, CreateOrderModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} не найден в БД");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = OrderModel.Order.Name,
                Address = OrderModel.Order.Address,
                Phone   = OrderModel.Order.Phone,
                User    = user,
                Date    = DateTime.Now,
                Items   = new List <OrderItem>()
            };

            foreach (var item in OrderModel.Items)
            {
                var product = await _db.Products.FindAsync(item.Id);

                if (product is null)
                {
                    throw new InvalidOperationException($"Товар id:{item.Id} не найден в БД");
                }

                var order_item = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price,
                    Quantity = item.Quantity,
                    Product  = product
                };
                order.Items.Add(order_item);
            }

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order.ToDTO());
        }
Exemplo n.º 11
0
        public async Task <OrderDTO> CreateOrder(string userName, CreateOrderModel orderModel)
        {
            var user = await userManager.FindByNameAsync(userName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {userName} не найден!");
            }

            await using (var transaction = await dB.Database.BeginTransactionAsync())
            {
                var order = new Order
                {
                    Name    = orderModel.Order.Name,
                    Address = orderModel.Order.Adress,
                    Phone   = orderModel.Order.Phone,
                    Date    = DateTime.Now,
                    User    = user
                };

                foreach (var item in orderModel.Items)
                {
                    var product = await dB.Products.FindAsync(item.Id);

                    if (product is null)
                    {
                        continue;
                    }

                    var orderItem = new OrderItem
                    {
                        Order    = order,
                        Product  = product,
                        Quantity = item.Quantity,
                        Price    = product.Price
                    };
                    order.Items.Add(orderItem);
                }
                await dB.Orders.AddAsync(order);

                await dB.SaveChangesAsync();

                await transaction.CommitAsync();

                return(order.ToDTO());
            }
        }
Exemplo n.º 12
0
        public async Task <Order> CreateOrder(string UserName, CartViewModel Cart, OrderViewModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} не найден в БД");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = OrderModel.Name,
                Address = OrderModel.Address,
                Phone   = OrderModel.Phone,
                User    = user,
                Date    = DateTime.Now,
            };

            foreach (var(product_model, quantity) in Cart.Items)
            {
                var product = await _db.Products.FindAsync(product_model.Id);

                if (product is null)
                {
                    continue;
                }

                var order_item = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price,
                    Quantity = quantity,
                    Product  = product
                };
                order.Items.Add(order_item);
            }

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order);
        }
        public async Task <OrderDTO> CreateOrderAsync(string UserName, CreateOrderModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            //if (user is null)
            //    RedirectToPageResult

            using (var transaction = await _db.Database.BeginTransactionAsync())
            {
                var order = new Order
                {
                    Name    = OrderModel.OrderViewModel.Name,
                    Address = OrderModel.OrderViewModel.Address,
                    Phone   = OrderModel.OrderViewModel.Phone,
                    User    = user,
                    Date    = DateTime.Now
                };

                await _db.Orders.AddAsync(order);

                foreach (var item in OrderModel.OrderItems)
                {
                    var product = await _db.Products.FirstOrDefaultAsync(p => p.Id == item.Id);

                    if (product is null)
                    {
                        throw new InvalidOperationException($"Товар с id:{item.Id} в базе данных на найден!");
                    }

                    var order_item = new OrderItem
                    {
                        Order    = order,
                        Price    = product.Price,
                        Quantity = item.Quantity,
                        Product  = product
                    };

                    await _db.OrderItems.AddAsync(order_item);
                }

                await _db.SaveChangesAsync();

                await transaction.CommitAsync();

                return(order.ToDTO());
            }
        }
Exemplo n.º 14
0
        public async Task <Order> CreateOrder(string UserName, CartViewModel Cart, OrderViewModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} не найден в БД");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync().ConfigureAwait(false);

            var order = new Order
            {
                Name    = OrderModel.Name,
                Address = OrderModel.Address,
                Phone   = OrderModel.Phone,
                User    = user,
            };

            var products_ids = Cart.Items.Select(item => item.Product.Id).ToArray();

            var cart_products = await _db.Products
                                .Where(p => products_ids.Contains(p.Id))
                                .ToArrayAsync();

            order.Items = Cart.Items.Join
                          (
                cart_products,
                cart_item => cart_item.Product.Id,
                product => product.Id,
                (cart_item, product) => new OrderItem
            {
                Order    = order,
                Product  = product,
                Price    = product.Price,      //Для скидок можно здесь
                Quantity = cart_item.Quantity
            }).ToArray();

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order);
        }
Exemplo n.º 15
0
        public async Task <Order> CreateOrder(string userName, CartViewModel cartViewModel, OrderViewModel orderViewModel)
        {
            var user = await _userManager.FindByNameAsync(userName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь с именем {userName} в БД отсутствует");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = orderViewModel.Name,
                Address = orderViewModel.Address,
                Phone   = orderViewModel.Phone,
                User    = user
            };

            var product_ids = cartViewModel.Items.Select(item => item.product.Id).ToArray();

            var cart_products = await _db.Products
                                .Where(p => product_ids.Contains(p.Id))
                                .ToArrayAsync();

            order.Items = cartViewModel.Items.Join(
                cart_products,
                cart_item => cart_item.product.Id,
                product => product.Id,
                (cart_item, product) => new OrderItem
            {
                Order    = order,
                Product  = product,
                Price    = product.Price,
                Quantity = cart_item.quantity
            }).ToArray();

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order);
        }
Exemplo n.º 16
0
        public async Task <OrderDTO> CreateOrder(CreateOrderModel model)
        {
            User user = await _userManager.FindByIdAsync(model.Order.UserId);

            if (user == null)
            {
                throw new InvalidOperationException($"User {model.Order.UserId} not found in database");
            }

            Order order = new Order()
            {
                User    = user,
                Name    = user.UserName,
                Address = model.Order.Address,
                Phone   = model.Order.Phone,
                Date    = model.Order.Date
            };

            await using var transaction = await _dB.Database.BeginTransactionAsync();

            List <OrderItem> items = new List <OrderItem>();

            foreach (var item in model.Items)
            {
                OrderItem orderItem = new OrderItem();
                orderItem.Order   = order;
                orderItem.Product = await _dB.Products.FirstOrDefaultAsync(p => p.Id == item.Id);

                orderItem.Quantity = item.Quantity;
                orderItem.Price    = item.Price;

                items.Add(orderItem);
            }

            order.Items = items;

            await _dB.Orders.AddAsync(order);

            await _dB.SaveChangesAsync();

            await transaction.CommitAsync();

            return(order.ToDTO());
        }
Exemplo n.º 17
0
        public async Task <Order> CreateOrderAsync(string Username, CartViewModel cart, OrderViewModel orderModel)
        {
            var user = await userManager.FindByNameAsync(Username);

            using (var transaction = await db.Database.BeginTransactionAsync())
            {
                var order = new Order
                {
                    Name    = orderModel.Name,
                    Address = orderModel.Address,
                    Phone   = orderModel.Phone,
                    User    = user,
                    Date    = DateTime.Now
                };

                await db.AddAsync(order);

                foreach (var(productModel, quantity) in cart.Items)
                {
                    var product = await db.Products.FirstOrDefaultAsync(x => x.Id == productModel.Id);

                    if (product is null)
                    {
                        throw new InvalidOperationException($"Товар с Id: {productModel.Id} в базе данных не найден!");
                    }

                    var orderItem = new OrderItem
                    {
                        Order    = order,
                        Product  = product,
                        Price    = product.Price,
                        Quantity = quantity
                    };

                    await db.OrderItems.AddAsync(orderItem);
                }

                await db.SaveChangesAsync();

                await transaction.CommitAsync();

                return(order);
            }
        }
Exemplo n.º 18
0
        public async Task<Order> CreateOrder(string UserName, CartViewModel Cart, OrderViewModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);
            if (user is null)
                throw new InvalidOperationException($"Пользователь {UserName} отсутствует в БД");

            await using var transaction = await _db.Database.BeginTransactionAsync(); //начало транзакции -> тут весь заказ

            var order = new Order
            {
                User = user,
                Address = OrderModel.Address,
                Phone = OrderModel.Phone,
                Name = OrderModel.Name,
            };

            var product_ids = Cart.Items.Select(item => item.Product.Id).ToArray();

            var cart_products = await _db.Products
                .Where(p => product_ids.Contains(p.Id))
                .ToArrayAsync();

            order.Items = Cart.Items.Join(
                cart_products,
                cart_item => cart_item.Product.Id,
                cart_product => cart_product.Id,
                (cart_item, cart_product) => new OrderItem
                {
                    Order = order,
                    Product = cart_product,
                    Price = cart_product.Price, // здесь можно применить скидки...
                    Quantity = cart_item.Quantity,
                }).ToArray();

            await _db.Orders.AddAsync(order);
            await _db.SaveChangesAsync();

            await transaction.CommitAsync(); //окончание транзакции

            return order;
        }
Exemplo n.º 19
0
        public async Task RemoveClaimAsync([FromBody] RemoveClaimDTO claimInfo, [FromServices] WebStoreDB dB)
        {
            await _userStore.RemoveClaimsAsync(claimInfo.User, claimInfo.Claims);

            await dB.SaveChangesAsync();
        }
Exemplo n.º 20
0
        public async Task RemoveFromRoleAsync([FromBody] User user, string role, [FromServices] WebStoreDB dB)
        {
            await _userStore.RemoveFromRoleAsync(user, role);

            await dB.SaveChangesAsync();
        }
Exemplo n.º 21
0
        public async Task ReplaceClaimAsync([FromBody] ReplaceClaimDto claimInfo, [FromServices] WebStoreDB db)
        {
            await _userStore.ReplaceClaimAsync(claimInfo.User, claimInfo.Claim, claimInfo.NewClaim);

            await db.SaveChangesAsync();
        }
Exemplo n.º 22
0
        public async Task AddLoginAsync([FromBody] AddLoginDTO login, [FromServices] WebStoreDB db)
        {
            await _UserStore.AddLoginAsync(login.User, login.UserLoginInfo);

            await db.SaveChangesAsync();
        }
Exemplo n.º 23
0
        async Task InitializeProductsAsync()
        {
            if (await db.Products.AnyAsync())
            {
                return;
            }

            var database = db.Database;

            //if (!await db.Employees.AnyAsync())
            //{
            using (var Transaction = await database.BeginTransactionAsync().ConfigureAwait(false))
            {
                await db.Employees.AddRangeAsync(TestData.Employees).ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Employees] ON");// Разрешаем базе вставлять свой первичный кюч ID и внешний ключ ~ParentId, т.к. в TestData у нас прописаны эти данные

                await db.SaveChangesAsync().ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Employees] OFF");

                await Transaction.CommitAsync().ConfigureAwait(false);
            }
            //}



            using (var Transaction = await database.BeginTransactionAsync().ConfigureAwait(false))
            {
                await db.Sections.AddRangeAsync(TestData.Sections).ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Sections] ON");// Разрешаем базе вставлять свой первичный кюч ID и внешний ключ ~ParentId, т.к. в TestData у нас прописаны эти данные

                await db.SaveChangesAsync().ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                await Transaction.CommitAsync().ConfigureAwait(false);
            }

            using (var Transaction = await database.BeginTransactionAsync().ConfigureAwait(false))
            {
                await db.Brands.AddRangeAsync(TestData.Brands).ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Brands] ON");// Разрешаем базе вставлять свой первичный кюч ID и внешний ключ ~ParentId, т.к. в TestData у нас прописаны эти данные

                await db.SaveChangesAsync().ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                await Transaction.CommitAsync().ConfigureAwait(false);
            }

            using (var Transaction = await database.BeginTransactionAsync().ConfigureAwait(false))
            {
                await db.Products.AddRangeAsync(TestData.Products).ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Products] ON");// Разрешаем базе вставлять свой первичный кюч ID и внешний ключ ~ParentId, т.к. в TestData у нас прописаны эти данные

                await db.SaveChangesAsync().ConfigureAwait(false);

                await database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Products] OFF");

                await Transaction.CommitAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 24
0
        public async Task <OrderDTO> CreateOrder(string UserName, CreateOrderModel OrderModel)
        {
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                throw new InvalidOperationException($"Пользователь {UserName} не найден в БД");
            }
            _Logger.LogInformation("Оформление нового заказа для {0}",
                                   UserName);

            var timer = Stopwatch.StartNew();

            await using var transaction = await _db.Database.BeginTransactionAsync().ConfigureAwait(false);

            var order = new Order
            {
                Name    = OrderModel.Order.Name,
                Address = OrderModel.Order.Address,
                Phone   = OrderModel.Order.Phone,
                User    = user,
            };

            //var product_ids = Cart.Items.Select(item => item.Product.Id).ToArray();

            //var cart_products = await _db.Products
            //  .Where(p => product_ids.Contains(p.Id))
            //  .ToArrayAsync();

            //order.Items = Cart.Items.Join(
            //    cart_products,
            //    cart_item => cart_item.Product.Id,
            //    product => product.Id,
            //    (cart_item, product) => new OrderItem
            //    {
            //        Order = order,
            //        Product = product,
            //        Price = product.Price,  // место, где могут быть применены скидки
            //        Quantity = cart_item.Quantity,
            //    }).ToArray();

            foreach (var item in OrderModel.Items)
            {
                var product = await _db.Products.FindAsync(item.ProductId);

                if (product is null)
                {
                    continue;
                }

                var order_item = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price,
                    Quantity = item.Quantity,
                    Product  = product
                };
                order.Items.Add(order_item);
            }

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            _Logger.LogInformation("Заказа для {0} успешно сформирована за {1} с id:{2} на сумму {3}",
                                   UserName, timer.Elapsed, order.Id, order.Items.Sum(i => i.TotalItemPrice));

            return(order.ToDTO());
        }
Exemplo n.º 25
0
        public async Task <OrderDTO> CreateOrder(string UserName, CreateOrderModel OrderModel)
        {
            _Logger.LogInformation("Формирование нового заказа.");
            var user = await _UserManager.FindByNameAsync(UserName);

            if (user is null)
            {
                _Logger.LogError("Пользователь, формирующий заказ, с именем {0} в БД отсутствует.", UserName);
                throw new InvalidOperationException($"Пользователь с именем {UserName} в БД отсутствует");
            }

            await using var transaction = await _db.Database.BeginTransactionAsync();

            var order = new Order
            {
                Name    = OrderModel.OrderViewModel.Name,
                Address = OrderModel.OrderViewModel.Address,
                Phone   = OrderModel.OrderViewModel.Phone,
                User    = user
            };

            //var product_ids = Cart.Items.Select(item => item.Product.Id).ToArray();

            //var cart_products = await _db.Products
            //  .Where(p => product_ids.Contains(p.Id))
            //  .ToArrayAsync();

            //order.Items = Cart.Items.Join(
            //    cart_products,
            //    cart_item => cart_item.Product.Id,
            //    product => product.Id,
            //    (cart_item, product) => new OrderItem
            //    {
            //        Order = order,
            //        Product = product,
            //        Price = product.Price,  // место, где могут быть применены скидки
            //        Quantity = cart_item.Quantity,
            //    }).ToArray();

            foreach (var item in OrderModel.Items)
            {
                var product = await _db.Products.FindAsync(item.ProductId);

                if (product is null)
                {
                    continue;
                }

                var order_item = new OrderItem
                {
                    Order    = order,
                    Price    = product.Price,
                    Quantity = item.Quantity,
                    Product  = product,
                };
                order.Items.Add(order_item);
            }

            await _db.Orders.AddAsync(order);

            await _db.SaveChangesAsync();

            await transaction.CommitAsync();

            _Logger.LogInformation("Заказ для пользователя с именем {0} сформирован.", UserName);

            return(order.ToDTO());
        }
Exemplo n.º 26
0
        private async Task InitAsync()
        {
            await _webStoreDb.Database.EnsureCreatedAsync();

            if (await _webStoreDb.Products.AnyAsync().ConfigureAwait(false))
            {
                return;
            }

            //await _webStoreDb.Database.MigrateAsync().ConfigureAwait(false);

            if (await _webStoreDb.Sections.CountAsync().ConfigureAwait(false) == 0)
            {
                await using var transaction = await _webStoreDb.Database.BeginTransactionAsync().ConfigureAwait(false);

                await _webStoreDb.Sections.AddRangeAsync(entities : TestData.Sections).ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Sections] ON");

                await _webStoreDb.SaveChangesAsync().ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Sections] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }

            if (await _webStoreDb.Brands.CountAsync().ConfigureAwait(false) == 0)
            {
                await using var transaction = await _webStoreDb.Database.BeginTransactionAsync().ConfigureAwait(false);

                await _webStoreDb.Brands.AddRangeAsync(entities : TestData.Brands).ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Brands] ON");

                await _webStoreDb.SaveChangesAsync().ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Brands] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }

            if (await _webStoreDb.Products.CountAsync().ConfigureAwait(false) == 0)
            {
                await using var transaction = await _webStoreDb.Database.BeginTransactionAsync().ConfigureAwait(false);

                await _webStoreDb.Products.AddRangeAsync(entities : TestData.Products).ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Products] ON");

                await _webStoreDb.SaveChangesAsync().ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Products] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }

            await using (var transaction = await _webStoreDb.Database.BeginTransactionAsync().ConfigureAwait(false))
            {
                await _webStoreDb.Employee.AddRangeAsync(TestData.Employees).ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Employee] ON");

                await _webStoreDb.SaveChangesAsync().ConfigureAwait(false);

                await _webStoreDb.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Employee] OFF");

                await transaction.CommitAsync().ConfigureAwait(false);
            }


            if (!await _roleManager.RoleExistsAsync(Role.Administrator))
            {
                await _roleManager.CreateAsync(new Role()
                {
                    Name = Role.Administrator
                }).ConfigureAwait(false);
            }

            if (!await _roleManager.RoleExistsAsync(Role.User))
            {
                await _roleManager.CreateAsync(new Role()
                {
                    Name = Role.User
                }).ConfigureAwait(false);
            }

            if (await _userManager.FindByNameAsync(User.DefaultPassword) is null)
            {
                var user = new User()
                {
                    UserName = User.Administrator
                };

                var resultCreateUser = await _userManager.CreateAsync(user, User.DefaultPassword).ConfigureAwait(false);

                if (resultCreateUser.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, Role.Administrator);
                }
            }
        }
Exemplo n.º 27
0
        public async Task RemoveClaimsAsync([FromBody] RemoveClaimDTO ClaimInfo, [FromServices] WebStoreDB db)
        {
            await _UserStore.RemoveClaimsAsync(ClaimInfo.User, ClaimInfo.Claims);

            await db.SaveChangesAsync();
        }
Exemplo n.º 28
0
        public async Task ReplaceClaimAsync([FromBody] ReplaceClaimDTO ClaimInfo, [FromServices] WebStoreDB db)
        {
            await userStore.ReplaceClaimAsync(ClaimInfo.User, ClaimInfo.claim, ClaimInfo.newClaim);

            await db.SaveChangesAsync();
        }
Exemplo n.º 29
0
        public async Task AddToRoleAsync([FromBody] User user, string role, [FromServices] WebStoreDB db)
        {
            await _UserStore.AddToRoleAsync(user, role);

            await db.SaveChangesAsync();
        }
Exemplo n.º 30
0
        public async Task AddClaimsAsync([FromBody] AddClaimDto claimInfo, [FromServices] WebStoreDB db)
        {
            await _userStore.AddClaimsAsync(claimInfo.User, claimInfo.Claims);

            await db.SaveChangesAsync();
        }