public Order AddToCart(CartViewModel cart)
        {
            var newOrder = new Order
            {
                TotalPrice = cart.TotalPrice,
                Date       = DateTime.UtcNow,
                UserId     = new Guid(),
                UserName   = "******"
            };

            _context.Add(newOrder);

            foreach (var product in cart.FoodProducts)
            {
                var foodProduct = _context.FoodProducts.Where(p => p.Name == product.FoodProduct.Name).FirstOrDefault();
                if (foodProduct != null)
                {
                    var orderProduct = new OrderProduct
                    {
                        Order       = newOrder,
                        FoodProduct = foodProduct
                    };
                    _context.Add(orderProduct);
                    _context.SaveChanges();

                    return(newOrder);
                }
            }

            return(null);
        }
        public AddOrderResponse AddOrder(int id, AddOrderRequest request)
        {
            var exists = _orderDbContext.Customers.Any(c => c.IdClient.Equals(id));

            if (!exists)
            {
                return(null);
            }

            // taking random employee to perform the order
            Random rand  = new Random();
            int    num   = rand.Next(0, _orderDbContext.Employees.Count() - 1);
            var    order = new Order()
            {
                DataAccepted = request.DateAccepted,
                idClient     = id,
                idEmployee   = _orderDbContext.Employees.Skip(num).Take(1).First().idEmployee,
                Notes        = request.Notes
            };

            _orderDbContext.Add(order);
            _orderDbContext.SaveChanges();


            // foreach in request
            var confExists = false;

            foreach (var cnf in request.Confectionery)
            {
                //checking if such product exists
                confExists = _orderDbContext.Confectioneries.Any(c => c.Name.Equals(cnf.Name));
                if (!confExists)
                {
                    return(null);
                }

                var confectioneryId = _orderDbContext.Confectioneries.Where(c => c.Name.Equals(cnf.Name))
                                      .Select(c => c.IdConfectionery).FirstOrDefault();
                var conf_order = new ConfectioneryOrder()
                {
                    IdConfection = confectioneryId,
                    IdOrder      = order.idOrder,
                    Notes        = cnf.Notes,
                    Quantity     = cnf.Quantity
                };
                _orderDbContext.Add(conf_order);
                _orderDbContext.SaveChanges();
            }


            return(new AddOrderResponse
            {
                IdOrder = order.idOrder,
                Confectionery = request.Confectionery
            });
        }
示例#3
0
        public async Task SupplyItemsAsync(int itemId, int amount, string name, decimal price)
        {
            using (var transaction = _orderDbContext.Database.BeginTransaction())
            {
                try
                {
                    var warehouseItem = await _orderDbContext.WarehouseItems
                                        .FirstOrDefaultAsync(wi => wi.ItemId == itemId);

                    if (warehouseItem == null)
                    {
                        if (string.IsNullOrEmpty(name) || price == 0m)
                        {
                            throw new ArgumentException("Provide name and price for new item.");
                        }
                        if (price < 0)
                        {
                            throw new ArgumentException("Price should be positive number.");
                        }
                        _orderDbContext.Add(new Item
                        {
                            ItemId = itemId,
                            Name   = name,
                            Price  = price
                        });
                        _orderDbContext.Add(new WarehouseItem
                        {
                            ItemId = itemId,
                            Amount = amount
                        });
                    }
                    else
                    {
                        if (amount > warehouseItem.Amount)
                        {
                            warehouseItem.Amount = amount;
                        }
                    }
                    if (!await SaveChangesAsync())
                    {
                        throw new DbUpdateException("Database failure");
                    }
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw e;
                }
            }
        }
        public void TestOrderDbContextWithOrderOk()
        {
            //SETUP
            var userId  = Guid.NewGuid();
            var options = SqliteInMemory.CreateOptions <OrderDbContext>();

            using var context = new OrderDbContext(options, new FakeUserIdService(userId));
            context.Database.EnsureCreated();
            var bookViews = context.SeedFourBookDdPartWithOptionalDbSchemaAdd(true).ToList();

            //ATTEMPT
            var status = Order.CreateOrder(userId, new[]
            {
                new OrderBookDto(bookViews[0], 1),
                new OrderBookDto(bookViews[1], 1),
            });

            context.Add(status.Result);
            context.SaveChanges();

            //VERIFY
            context.Orders.Count().ShouldEqual(1);
            context.Set <LineItem>().Count().ShouldEqual(2);
            context.BookViews.Count().ShouldEqual(4);
        }
        public async Task <Domain.Entity.Order> PlaceCustomerOrderAsync(Domain.Entity.Order order)
        {
            _dbContext.Add(order);
            await _dbContext.SaveChangesAsync();

            return(order);
        }
示例#6
0
        public async Task <IActionResult> Add(int goodsId, int shopId, decimal price)
        {
            var res = new ResultModel();

            var isAdd = await _context.GoodsPrices.AnyAsync(p => p.ShopId == shopId && p.GoodsId == goodsId);

            if (isAdd)
            {
                res.Code    = 0;
                res.Message = "店铺价格已存在,请勿重复添加";
                return(Json(res));
            }

            var entity = new GoodsPrice
            {
                ShopId   = shopId,
                Price    = price,
                GoodsId  = goodsId,
                IsDelete = false
            };

            _context.Add(entity);

            await _context.SaveChangesAsync();

            res.Code    = 100;
            res.Message = "新增成功";
            return(Json(res));
        }
        /// <summary>
        /// 生成订单的服务方法
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="userId">用户号</param>
        /// <param name="buyItems">购买的商品简要清单</param>
        /// <returns>订单是否创建成功</returns>
        public bool CreateOrder(int orderId, int userId, IEnumerable <BuyProductDto> buyItems)
        {
            //在分布式事务的发起端,需要先定义分布式事务标识:
            string DT_Identity = System.Guid.NewGuid().ToString();

            //使用3阶段提交的分布式事务,保存订单到数据库
            OrderDbContext context = new OrderDbContext();

            DTController controller = new DTController(DT_Identity);

            return(controller.DistTrans3PCRequest <bool>(DTS_Proxy,
                                                         context.CurrentDataBase,
                                                         db =>
            {
                //先请求商品服务,扣减库存,并获取商品的仓库信息
                ServiceRequest request = new ServiceRequest();
                request.ServiceName = "ProductService";
                request.MethodName = "UpdateProductOnhand";
                request.Parameters = new object[] { DT_Identity, buyItems };
                List <SellProductDto> sellProducts = productProxy.RequestServiceAsync <List <SellProductDto> >(request).Result;

                #region 构造订单明细和订单对象
                //
                List <OrderItemEntity> orderItems = new List <OrderItemEntity>();
                OrderEntity order = new OrderEntity()
                {
                    ID = orderId,
                    OwnerID = userId,
                    OrderTime = DateTime.Now,
                    OrderName = "Prudoct:"
                };
                foreach (BuyProductDto item in buyItems)
                {
                    //注意:在商品数据库上,前面更新商品,但还没有提交事务,下面这个查询直接使用的话会导致查询等待,因为SQLSERVER的事务隔离级别是这样的
                    //所以 GetProductInfo 的实现需要注意。
                    ProductDto product = this.GetProductInfo(item.ProductId).Result;

                    OrderItemEntity temp = new OrderItemEntity()
                    {
                        OrderID = orderId,
                        ProductID = product.ID,
                        BuyNumber = item.BuyNumber,
                        OnePrice = product.Price,
                        ProductName = product.ProductName
                    };
                    temp.StoreHouse = (from i in sellProducts where i.ProductId == temp.ProductID select i.StoreHouse).FirstOrDefault();

                    orderItems.Add(temp);
                    order.OrderName += "," + temp.ProductName;
                    order.AmountPrice += temp.OnePrice * temp.BuyNumber;
                }
                //
                #endregion

                //保存订单数据到数据库
                context.Add <OrderEntity>(order);
                context.AddList <OrderItemEntity>(orderItems);
                return true;
            }));
        }
        public void Test1()
        {
            try
            {
                int externalOrderId;
                using (var dbc = new OrderDbContext())
                {
                    var externalOrder = new ExternalOrder(_nextId++)
                    {
                        Recipient = "me", Supplier = null
                    };
                    dbc.Add(externalOrder);
                    dbc.SaveChanges();

                    Assert.Null(externalOrder.Supplier);
                    externalOrderId = externalOrder.Id;
                }

                using (var dbc = new OrderDbContext())
                {
                    var externalOrder = dbc.Find <ExternalOrder>(externalOrderId);
                    Assert.Null(externalOrder.Supplier);
                }
            }
            catch (Exception ex)
            {
                _testOutputHelper.WriteLine(ex.ToString());
                throw;
            }
        }
示例#9
0
        public async Task <int> CreateOrder(Order order)
        {
            order.State = OrderState.Created;
            dbContext.Add(order);
            await dbContext.SaveChangesAsync();

            return(order.Id);
        }
示例#10
0
 public Item AddNewitemToDatabase(Item item)
 {
     if (item == null)
     {
         return(null);
     }
     _context.Add(item);
     _context.SaveChanges();
     return(item);
 }
        public async Task <bool> CreateAsync(OrderEntity order)
        {
            if (!IsIDExistsAsync(order.OrderID).Result)
            {
                _context.Add(order);
                await _context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
示例#12
0
        public void GivenCreateNewUser_WhenCreatingANewUserWhoIsAlreadyInDatabase_ThenReturnException()
        {
            using (var context = new OrderDbContext(CreateNewInMemoryDatabase()))
            {
                var userService = new UserService(context);
                context.Add(testUser);
                context.SaveChanges();

                var ex = Assert.Throws <UserException>(() => userService.CreateNewCustomer(testUser));
                Assert.Equal("Email is already in use", ex.Message);
            }
        }
示例#13
0
        public void GivenGetSingleItem_WhenRequestingOneItem_ThenItemIsReturned()
        {
            using (var context = new OrderDbContext(CreateNewInMemoryDatabase()))
            {
                var itemService = new ItemService(context);
                context.Add(testItem);
                context.SaveChanges();
                var result = itemService.GetSingleItem(testItem.ItemID);

                Assert.Same(testItem, result);
            }
        }
示例#14
0
        public void GivenUpdateItem_WhenUpdatingAnItem_ThenItemIsUpdated()
        {
            using (var context = new OrderDbContext(CreateNewInMemoryDatabase()))
            {
                var itemService = new ItemService(context);
                context.Add(testItem);
                context.SaveChanges();
                testItem = itemService.UpdateItem(testItem2);

                Assert.Equal("peelman", testItem.Name);
            }
        }
示例#15
0
        public void GivenGetSingleUser_WhenRequestingOneUser_ThenUserIsReturned()
        {
            using (var context = new OrderDbContext(CreateNewInMemoryDatabase()))
            {
                var userService = new UserService(context);
                context.Add(testUser);
                context.SaveChanges();
                var result = userService.GetSingleUser(testUser.UserID);

                Assert.Same(testUser, result);
            }
        }
 public int Add(Models.Order item)
 {
     try
     {
         dbContext.Add(item);
         Save();
         return(item.OrderId);
     }
     catch (Exception)
     {
         return(0);
     }
 }
示例#17
0
        public async Task <IActionResult> Create(Brand brand)
        {
            if (ModelState.IsValid)
            {
                brand.IsDelete = false;
                brand.AddTime  = DateTime.Now;
                _context.Add(brand);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(brand));
        }
示例#18
0
        public async Task <IActionResult> Create([Bind("Id,Name,Phone,Linkman,Address,RegionId")] Shop shop)
        {
            if (ModelState.IsValid)
            {
                shop.AddDate  = DateTime.Now;
                shop.Password = Utils.MD5Encrypt("888888");
                shop.Status   = AccountState.Certified;
                _context.Add(shop);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(shop));
        }
示例#19
0
        public async Task <IActionResult> Create([Bind("Id,BrandId,GoodsImg,GoodsCode,GoodsName,GoodsSepc,GoodsUnit,AddTime")] Goods goods, decimal price = 0)
        {
            if (ModelState.IsValid)
            {
                goods.Status   = 1;
                goods.IsDelete = false;
                goods.AddTime  = DateTime.Now;
                _context.Add(goods);
                await _context.SaveChangesAsync();

                if (price > 0)
                {
                    GoodsPrice goodsPrice = new GoodsPrice();
                    goodsPrice.GoodsId = goods.Id;
                    goodsPrice.Price   = price;
                    goodsPrice.ShopId  = 0;
                    _context.Add(goodsPrice);
                    await _context.SaveChangesAsync();
                }

                return(RedirectToAction(nameof(Index)));
            }
            return(View(goods));
        }
        public void TestOrderDbContextUserIdQueryFilterWorkingOk()
        {
            //SETUP
            var userId1 = Guid.NewGuid();
            var options = SqliteInMemory.CreateOptions <OrderDbContext>();

            options.TurnOffDispose();
            using (var context = new OrderDbContext(options, new FakeUserIdService(userId1)))
            {
                context.Database.EnsureCreated();
                var bookViews = context.SeedFourBookDdPartWithOptionalDbSchemaAdd(true).ToList();

                var status = Order.CreateOrder(userId1, new[]
                {
                    new OrderBookDto(bookViews[0], 1),
                    new OrderBookDto(bookViews[1], 1),
                });
                context.Add(status.Result);
                context.SaveChanges();
            }
            var userId2 = Guid.NewGuid();

            using (var context = new OrderDbContext(options, new FakeUserIdService(userId2)))
            {
                //ATTEMPT
                var status = Order.CreateOrder(userId2, new[]
                {
                    new OrderBookDto(context.BookViews.First(), 1),
                });
                context.Add(status.Result);
                context.SaveChanges();
            }
            using (var context = new OrderDbContext(options, new FakeUserIdService(userId2)))
            {
                //VERIFY
                var orders = context.Orders.ToList();
                orders.Count.ShouldEqual(1);
                orders.Single().UserId.ShouldEqual(userId2);
            }
            using (var context = new OrderDbContext(options, new FakeUserIdService(userId1)))
            {
                //VERIFY
                var orders = context.Orders.ToList();
                orders.Count.ShouldEqual(1);
                orders.Single().UserId.ShouldEqual(userId1);
            }
            options.ManualDispose();
        }
        private void Seed()
        {
            using (var context = new OrderDbContext(ContextOptions))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                var mockFoodList = new MockFoodProductRepository();
                var foodList     = mockFoodList.FoodProducts();


                foreach (var foodProduct in foodList)
                {
                    context.Add(foodProduct);
                }
                context.SaveChanges();
            }
        }
        public async Task <IActionResult> Create([Bind("AmountOfBooks,AmountOfDvds,AmountOfShirts,CustomerName,Phone,Email,IsCompany,Address,RegistrationNumber,PVNRegistrationNumber,DeliveryAddress,DeliveryDetails,DeliveryDateTime,PaymentType")] Order order)
        {
            if (ModelState.IsValid)
            {
                var isError = false;

                if (string.IsNullOrEmpty(order.Email) && string.IsNullOrEmpty(order.Phone))
                {
                    isError = true;
                    ModelState.AddModelError("phone-email-mandatory", "E-pasts vai tālrunis ir obligāts!");
                }

                if (order.IsCompany)
                {
                    if (string.IsNullOrEmpty(order.Address))
                    {
                        isError = true;
                        ModelState.AddModelError("address-mandatory", "Juridiskām personām adrese obligāta!");
                    }

                    if (string.IsNullOrEmpty(order.RegistrationNumber))
                    {
                        isError = true;
                        ModelState.AddModelError("reg-mandatory", "Juridiskām personām reģ.nr. obligāts!");
                    }
                }

                if (isError)
                {
                    return(View(order));
                }

                _context.Add(order);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(order));
        }
示例#23
0
        public AddOrderResponce AddOrder(int idCustomer, AddOrderRequest request)
        {
            AddOrderResponce responce = new AddOrderResponce()
            {
                Conf_Ids = new List <int>()
            };



            int countUserId = _context.Customer.Where(c => c.IdCustomer == idCustomer).Count();

            if (countUserId != 1)
            {
                throw new NoSuchCustomerException("No customer with id " + idCustomer + " found");
            }

            foreach (AddConfectioneryRequest item in request.Confectionery)
            {
                if (_context.Confectionery.Select(conf => conf.Name).Where(n => n == item.Name).Count() != 1)
                {
                    throw new NoSuchConfectioneryException("No conf with name \"" + item.Name + "\" found");
                }
            }


            using (var trans = _context.Database.BeginTransaction())
            {
                Order order = new Order()
                {
                    DateAccepted = request.DateAccepted,
                    Notes        = request.Notes,
                    IdCustomer   = idCustomer,
                    IdEmployee   = request.IdEmployee
                };

                _context.Add <Order>(order);

                _context.SaveChanges();


                responce.IdOrder = order.IdOrder;



                foreach (AddConfectioneryRequest item in request.Confectionery)
                {
                    int id = _context.Confectionery.Where(conf => conf.Name == item.Name).Select(conf => conf.IdConfectionery).FirstOrDefault();

                    responce.Conf_Ids.Add(id);

                    _context.Add <Confectionery_Order>(new Confectionery_Order()
                    {
                        IdConfectionary = id,
                        IdOrder         = order.IdOrder,
                        Quantity        = item.Quantity,
                        Notes           = item.Notes
                    });
                }

                _context.SaveChanges();

                trans.Commit();
            }

            return(responce);
        }
示例#24
0
        public async Task <ApiJsonResult> Create(int?tenantId, long userId, OrderItemDto data)
        {
            var result          = new ApiJsonResult();
            var orderItemModels = new List <OrderItem>();

            foreach (var product in data.Products)
            {
                var orderItem = new OrderItem
                {
                    TenantId       = tenantId.Value,
                    ProductId      = product.Id,
                    Amount         = product.Amount,
                    Price          = product.Price,
                    CreatedDate    = DateTime.Now,
                    UserModifiedId = userId
                };
                orderItemModels.Add(orderItem);
            }
            var orderModel = new Order
            {
                CustomerId = data.CustomerId,
                SellerId   = data.SellerId,
                TenantId   = tenantId.Value,
                OrderNote  = new OrderNote
                {
                    TenantId       = tenantId.Value,
                    Note           = data.OrderNote,
                    CreatedDate    = DateTime.Now,
                    UserModifiedId = userId
                },
                OrderCode      = Constants.GenerateCode(),
                OrderItems     = orderItemModels,
                SaleDate       = data.SaleDateUtc,
                CreatedDate    = DateTime.Now,
                UserModifiedId = userId,
                OrderType      = data.OrderType,
                OrderTotal     = data.OrderTotal,
                OrderDiscount  = data.OrderDiscount,
                OrderPaid      = data.OrderPaid,
                OrderDebt      = data.OrderDebt,
                StoreId        = data.StoreId,
                OrderStatusId  = OrderStatus.Ordered
            };

            switch (data.OrderType)
            {
            case OrderType.Order:
                if (data.CarrierId.HasValue)
                {
                    var shipment = new Shipment
                    {
                        TenantId        = tenantId.Value,
                        DeliveryDateUtc = data.DeliveryDate,
                        Note            = data.ShipmentNote,
                        Shipper         = data.Shipper,
                        CarrierId       = data.CarrierId,
                        CreatedDate     = DateTime.Now,
                        UserModifiedId  = userId
                    };
                    orderModel.Shipment = shipment;
                }
                break;

            case OrderType.Sale:
            case OrderType.ReturnSupplier:
                orderModel.PaymentMethodId = data.PaymentMethodId;
                break;

            default:
                break;
            }
            _salesDbContext.Add(orderModel);
            await _unitOfWork.Commit();

            var userModified = new UserModified
            {
                TenantId = tenantId,
                UserId   = userId
            };
            await _inventoryService.UpdateAllInventories(orderModel.Id, userModified);

            return(result);
        }