예제 #1
0
        public IActionResult Create(CreateOrderModel model)
        {
            if (!model.LineItems.Any())
            {
                return(BadRequest("Please submit line items"));
            }

            if (string.IsNullOrWhiteSpace(model.Customer.Name))
            {
                return(BadRequest("Customer needs a name"));
            }

            var customer = new Customer
            {
                Name            = model.Customer.Name,
                ShippingAddress = model.Customer.ShippingAddress,
                City            = model.Customer.City,
                PostalCode      = model.Customer.PostalCode,
                Country         = model.Customer.Country
            };

            var order = new Order
            {
                LineItems = model.LineItems
                            .Select(line => new LineItem {
                    ProductId = line.ProductId, Quantity = line.Quantity
                })
                            .ToList(),

                Customer = customer
            };

            orderRepository.Add(order);

            orderRepository.SaveChanges();

            return(Ok("Order Created"));
        }
예제 #2
0
        public OrderDTO CreateOrder(CreateOrderModel Order, string UserName)
        {
            var user = _UserManager.FindByNameAsync(UserName).Result;

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

                _Context.Orders.Add(order);
                foreach (var item in Order.OrderItems)
                {
                    var product = _Context.Products.FirstOrDefault(p => p.Id == item.Id);
                    if (product is null)
                    {
                        throw new InvalidOperationException($"Продукт id:{item.Id} отсутвтует в базе");
                    }
                    _Context.OrderItems.Add(new OrderItem
                    {
                        Order    = order,
                        Product  = product,
                        Price    = product.Price,
                        Quantity = item.Quantity
                    });
                }

                _Context.SaveChanges();
                transaction.Commit();

                return(OrderDTO2Order.Map(order));
            }
        }
예제 #3
0
        public OrderDto CreateOrder(CreateOrderModel orderModel, string
                                    userName)
        {
            var user = _userManager.FindByNameAsync(userName).Result;

            using (var transaction = _context.Database.BeginTransaction())
            {
                var order = new Order
                {
                    Address = orderModel.OrderViewModel.Address,
                    Name    = orderModel.OrderViewModel.Name,
                    Date    = DateTime.Now,
                    Phone   = orderModel.OrderViewModel.Phone,
                    User    = user
                };
                _context.Orders.Add(order);
                foreach (var item in orderModel.OrderItems)
                {
                    var product = _context.Products.FirstOrDefault(p =>
                                                                   p.Id.Equals(item.Id));
                    if (product == null)
                    {
                        throw new InvalidOperationException("Продукт не найден в базе");
                    }
                    var orderItem = new OrderItem
                    {
                        Order    = order,
                        Price    = product.Price,
                        Quantity = item.Quantity,
                        Product  = product
                    };
                    _context.OrderItems.Add(orderItem);
                }
                _context.SaveChanges();
                transaction.Commit();
                return(GetOrderById(order.Id));
            }
        }
예제 #4
0
        public async Task <IActionResult> Register(CreateOrderModel model)
        {
            LoadData();
            model.Status = StatusOrder.Open;
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            try
            {
                await _appOrder.RegisterAsync(model);

                TempData["Success"] = true;
                TempData["Message"] = "Ordem de Serviço Criada";
                return(RedirectToAction("Index"));
            }
            catch (Exception x)
            {
                ViewBag.Success = false;
                ViewBag.Message = x.Message;
                return(View(model));
            }
        }
예제 #5
0
        public IActionResult CheckOut(OrderViewModel model)
        {
            if (ModelState.IsValid)
            {
                var orderModel = new CreateOrderModel()
                {
                    OrderItems     = _cartService.TCart(),
                    OrderViewModel = model
                };

                var orderResult = _ordersService.CreateOrder(orderModel, User.Identity.Name);
                _cartService.RemoveAll();
                return(RedirectToAction("OrderConfirmed", new { id = orderResult.Id }));
            }

            var detailsModel = new DetailsViewModel()
            {
                CartViewModel  = _cartService.TransformCart(),
                OrderViewModel = model
            };

            return(View("Details", detailsModel));
        }
        public CreateOrderCommandTests()
        {
            var fixture = new Fixture();

            fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
            fixture.Behaviors.Add(new OmitOnRecursionBehavior());

            _customer = fixture.Create <Customer>();

            _dateTime = fixture.Create <DateTime>();

            _order = fixture.Create <Order>();

            _shoppingCartItems = fixture.CreateMany <ShoppingCartItem>().ToList();

            _createOrderModel = new CreateOrderModel(CustomerEmail, CartId);

            _mocker = new AutoMoqer();

            _mocker.GetMock <IOrderRepositoryFacade>()
            .Setup(o => o.GetCustomer(CustomerEmail))
            .Returns(_customer);

            _mocker.GetMock <IOrderRepositoryFacade>()
            .Setup(o => o.GetCartItems(CartId))
            .Returns(_shoppingCartItems);

            _mocker.GetMock <IDateTimeService>()
            .Setup(d => d.GetDateTimeUtc())
            .Returns(_dateTime);

            _mocker.GetMock <IOrderFactory>()
            .Setup(o => o.Create(_dateTime, _customer, _shoppingCartItems))
            .Returns(_order);

            _sut = _mocker.Create <CreateOrderCommand>();
        }
예제 #7
0
        public IActionResult CreateOrder(CreateOrderModel orderModel)
        {
            orderModel.OrderDetails.RemoveAll(od => od.IsDeleted);
            var order = _mapper.Map <Data.Models.Order>(orderModel);

            order.IsSpecialPromo = _promotionRepository.CheckPromotionBuy1Get1();
            var success = _orderRepository.Create(order);

            if (success)
            {
                _hubContext.Clients.All.SendAsync("ReceiveNewOrder", $"{order.LastName} {order.MiddleName} {order.FirstName}", order.PhoneNumber, order.OrderDeliveried.ToString("HH:mm dd/MM"));

                foreach (var device in _deviceRepository.GetAll())
                {
                    try
                    {
                        var    payload         = "{\"title\":\"Đơn hàng mới\",\"message\":\"Họ tên: " + $"{order.LastName} {order.MiddleName} {order.FirstName}" + "\\nThời gian giao: " + order.OrderDeliveried.ToString("HH:mm dd/MM") + "\\nĐiện thoại: " + order.PhoneNumber + "\"}";
                        string vapidPublicKey  = _configuration.GetSection("VapidKeys")["PublicKey"];
                        string vapidPrivateKey = _configuration.GetSection("VapidKeys")["PrivateKey"];

                        var pushSubscription = new PushSubscription(device.PushEndpoint,
                                                                    device.PushP256DH,
                                                                    device.PushAuth);
                        var vapidDetails = new VapidDetails("https://admin.ninjasaigon.com/Orders", vapidPublicKey, vapidPrivateKey);

                        var webPushClient = new WebPushClient();
                        webPushClient.SendNotification(pushSubscription, payload, vapidDetails);
                    }
                    catch
                    {
                        //fail device
                    }
                }
            }

            return(Json(new { success }));
        }
예제 #8
0
        /// <summary>
        /// Process Every Incoming Transaction
        /// </summary>
        /// <param name="Transaction">string Message consisting values delimited by ','</param>

        public void Transaction(string Transaction)
        {
            string[] array = new string[5];

            if (Transaction.Contains("Order"))
            {
                array = Transaction.Split(',');
            }

            CreateOrderModel createOrder = new CreateOrderModel()
            {
                userId   = array[1],
                Symbol   = array[2],
                Quantity = int.Parse(array[3]),
                Price    = double.Parse(array[4])
            };

            if (Transaction.Contains("Buy"))
            {
                CreateBuyOrder(createOrder);
                if (PendingSellOrders.Count > 0)
                {
                    ProcessPendingSaleOrders();
                }
            }

            else if (Transaction.Contains("sell"))
            {
                PendingSellOrders.Add(createOrder);
                SellOrderStatus = CreateSellOrder(createOrder);

                if (SellOrderStatus)
                {
                    PendingSellOrders.Remove(createOrder);
                }
            }
        }
        public IActionResult Checkout(CreateOrderViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var shoppingCartItems = _getShoppingCartItemsListQuery.Execute(_cartIdProvider.CartId);

            if (!shoppingCartItems.Any())
            {
                ModelState.AddModelError("", "You cart is empty.Add some goods first");
            }

            var userId = _getApplicationUserId.Execute(HttpContext.User);

            _saveApplicationUserDetails.Execute(userId, viewModel);

            var orderModel = new CreateOrderModel(userId, _cartIdProvider.CartId);

            _createOrderCommand.Execute(orderModel);

            return(RedirectToAction("CheckoutComplete", new { userId, userEmail = viewModel.Email }));
        }
예제 #10
0
        public IActionResult CheckOut(OrderViewModel model, [FromServices] ILogger logger)
        {
            if (!ModelState.IsValid)
            {
                return(View("Details", new DetailsViewModel
                {
                    CartViewModel = _CartService.TransformCart(),
                    OrderViewModel = model
                }));
            }
            logger.LogInformation("Оформление заказа");
            var create_order_model = new CreateOrderModel
            {
                OrderViewModel = model,
                Items          = new List <OrderItemDTO>()
            };

            var order = _OrderService.CreateOrder(
                create_order_model,
                User.Identity.Name);

            _CartService.RemoveAll();
            return(RedirectToAction("OrderConfirmed", new { id = order.Id }));
        }
예제 #11
0
        public ActionResult Edit(CreateOrderModel model, string itemsString)
        {
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);
            if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form);

            // Initializing needed temporary variables
            bool wasReturnedToCreator;
            bool allowExeeding = true;
            List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>();

            Order orderFromDatabase;
            List<Orders_OrderToItem> itemsFromEditForm = new List<Orders_OrderToItem>();
            List<Orders_OrderToItem> itemsToDelete = new List<Orders_OrderToItem>();
            List<Orders_OrderToItem> itemsToCreate = new List<Orders_OrderToItem>();
            List<Orders_OrderToItem> itemsToUpdate = new List<Orders_OrderToItem>();

            decimal totalOrderPrice;
            decimal totalAllocation;
            List<Budgets_Allocations> orderAllocations = new List<Budgets_Allocations>();

            using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId))
            {
                orderFromDatabase = orderRep.GetEntity(model.Order.Id, "Supplier", "Orders_OrderToItem", "Orders_OrderToAllocation", "Users_ApprovalRoutes.Users_ApprovalStep");
            }

            if (orderFromDatabase == null) return Error(Loc.Dic.error_order_not_found);
            if (orderFromDatabase.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission);

            if (orderFromDatabase.StatusId != (int)StatusType.Pending && orderFromDatabase.StatusId != (int)StatusType.PendingOrderCreator) return Error(Loc.Dic.error_order_edit_after_approval);
            wasReturnedToCreator = orderFromDatabase.StatusId == (int)StatusType.PendingOrderCreator;

            itemsFromEditForm = ItemsFromString(itemsString, model.Order.Id);
            if (itemsFromEditForm == null) return Error(Loc.Dic.error_invalid_form);
            if (itemsFromEditForm.Count == 0) return Error(Loc.Dic.error_order_has_no_items);
            if (itemsFromEditForm.Count == 0) return Error(Loc.Dic.error_order_has_no_items);

            totalOrderPrice = (decimal.Floor(itemsFromEditForm.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000);

            if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form);
            model.Allocations = model.Allocations.Where(x => x.IsActive).ToList();
            totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000);

            if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation);

            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            {
                Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.CompanyId == CurrentUser.CompanyId && x.IsActive);
                if (currentBudget == null) return Error(Loc.Dic.error_database_error);
                model.Order.BudgetId = currentBudget.Id;

                int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray();
                var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending);
                bool IsValidAllocations =
                    (allocationsData.Count == orderAllocationsIds.Length) &&
                    model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0);
                if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form);

                if (model.IsFutureOrder)
                {
                    foreach (var allocationData in allocationsData)
                    {
                        List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList();

                        foreach (var month in allocationMonths)
                        {
                            if (month.MonthId == DateTime.Now.Month)
                            {
                                OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                                var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month, orderFromDatabase.Id);
                                if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                                AllocationsToCreate.AddRange(newAllocations);
                            }
                            else
                            {
                                var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId);
                                if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation);

                                Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation()
                                {
                                    AllocationId = allocationData.AllocationId,
                                    MonthId = month.MonthId.Value,
                                    Amount = month.Amount,
                                    OrderId = orderFromDatabase.Id
                                };

                                AllocationsToCreate.Add(newAllocation);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var allocationData in allocationsData)
                    {
                        OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                        var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month, orderFromDatabase.Id);
                        if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                        AllocationsToCreate.AddRange(newAllocations);
                    }
                }
            }

            using (OrderToAllocationRepository orderAllocationRep = new OrderToAllocationRepository())
            {
                foreach (var item in orderFromDatabase.Orders_OrderToAllocation)
                {
                    orderAllocationRep.Delete(item.Id);
                }

                foreach (var item in AllocationsToCreate)
                {
                    orderAllocationRep.Create(item);
                }
            }

            foreach (var newItem in itemsFromEditForm)
            {
                Orders_OrderToItem existingItem = orderFromDatabase.Orders_OrderToItem.SingleOrDefault(x => x.ItemId == newItem.ItemId);

                if (existingItem != null)
                {
                    if (
                        existingItem.Quantity != newItem.Quantity ||
                        existingItem.SingleItemPrice != newItem.SingleItemPrice
                        )
                    {
                        newItem.Id = existingItem.Id;
                        itemsToUpdate.Add(newItem);
                    }
                }
                else
                {
                    itemsToCreate.Add(newItem);
                }
            }

            foreach (var existingItem in orderFromDatabase.Orders_OrderToItem)
            {
                Orders_OrderToItem newItem = itemsFromEditForm.SingleOrDefault(x => x.ItemId == existingItem.ItemId);

                if (newItem == null)
                {
                    itemsToDelete.Add(existingItem);
                }
            }

            bool noErrors = true;

            using (OrderToItemRepository orderToItemRep = new OrderToItemRepository())
            {
                foreach (var item in itemsToCreate)
                {
                    if (!orderToItemRep.Create(item) && noErrors)
                        noErrors = false;
                }
                foreach (var item in itemsToUpdate)
                {
                    if (orderToItemRep.Update(item) == null && noErrors)
                        noErrors = false;
                }
                foreach (var item in itemsToDelete)
                {
                    if (!orderToItemRep.Delete(item.Id) && noErrors)
                        noErrors = false;
                }

                using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                {
                    if (!CurrentUser.OrdersApprovalRouteId.HasValue)
                    {
                        model.Order.NextOrderApproverId = null;
                        model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                    }
                    else
                    {
                        Users_ApprovalRoutes orderRoute = orderFromDatabase.Users_ApprovalRoutes; //routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep");
                        Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault();

                        if (firstStep != null)
                        {
                            model.Order.ApprovalRouteId = orderRoute.Id;
                            model.Order.ApprovalRouteStep = firstStep.StepNumber;
                            model.Order.NextOrderApproverId = firstStep.UserId;
                            model.Order.StatusId = (int)StatusType.Pending;
                        }
                        else
                        {
                            model.Order.ApprovalRouteId = null;
                            model.Order.ApprovalRouteStep = null;
                            model.Order.NextOrderApproverId = null;
                            model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                        }
                    }

                    model.Order.CompanyId = orderFromDatabase.CompanyId;
                    model.Order.CreationDate = orderFromDatabase.CreationDate;
                    model.Order.SupplierId = orderFromDatabase.SupplierId;
                    model.Order.UserId = orderFromDatabase.UserId;
                    model.Order.OrderNumber = orderFromDatabase.OrderNumber;
                    model.Order.InvoiceNumber = orderFromDatabase.InvoiceNumber;
                    model.Order.InvoiceDate = orderFromDatabase.InvoiceDate;
                    model.Order.LastStatusChangeDate = DateTime.Now;
                    model.Order.ValueDate = orderFromDatabase.ValueDate;
                    model.Order.WasAddedToInventory = orderFromDatabase.WasAddedToInventory;
                    model.Order.IsFutureOrder = model.IsFutureOrder;

                    model.Order.Price = totalOrderPrice;

                    ordersRep.Update(model.Order);

                    model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1");
                }
            }

            if (noErrors)
            {
                int? historyActionId = null;
                historyActionId = (int)HistoryActions.Edited;
                Orders_History orderHistory = new Orders_History();
                using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id))
                    if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value, model.NotesForApprover);

                if (wasReturnedToCreator)
                {
                    if (model.Order.NextOrderApproverId.HasValue)
                    {
                        SendNotifications.OrderPendingApproval(model.Order, Url);
                    }
                }

                return RedirectToAction("MyOrders");
            }
            else
                return Error(Loc.Dic.error_order_update_items_error);
        }
예제 #12
0
        public ActionResult Edit(int id = 0)
        {
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);

            CreateOrderModel model = new CreateOrderModel();
            using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            {
                model.Order = orderRep.GetEntity(id, "Supplier", "Orders_OrderToItem", "Orders_OrderToItem.Orders_Items", "Orders_OrderToAllocation.Budgets_Allocations");
                if (model.Order == null) return Error(Loc.Dic.error_order_not_found);
                if (model.Order.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission);

                Budget activeBudget = budgetsRep.GetList().SingleOrDefault(x => x.CompanyId == CurrentUser.CompanyId && x.IsActive);
                if (activeBudget == null) return Error(Loc.Dic.error_no_active_budget);

                model.IsFutureOrder = model.Order.IsFutureOrder;

                List<Budgets_Allocations> userAllocations = allocationsRep.GetUserAllocations(CurrentUser.UserId, activeBudget.Id, id);
                if (!userAllocations.Any()) return Error(Loc.Dic.error_user_have_no_allocations);

                model.Allocations = new List<OrderAllocation>();
                List<Orders_OrderToAllocation> validOrderAllocations = model.Order.Orders_OrderToAllocation.ToList();

                var distinctAllocationIds = validOrderAllocations.Select(x => x.AllocationId).Distinct().ToList();
                foreach (var allocationId in distinctAllocationIds)
                {
                    var combineSplitted = validOrderAllocations.Where(x => x.MonthId <= model.Order.CreationDate.Month && x.AllocationId == allocationId);
                    model.Allocations.Add(
                        new OrderAllocation()
                            {
                                AllocationId = allocationId,
                                Name = validOrderAllocations.First(x => x.AllocationId == allocationId).Budgets_Allocations.DisplayName,
                                MonthId = model.Order.CreationDate.Month,
                                IsActive = true,
                                Amount = combineSplitted.Sum(x => x.Amount)
                            }
                    );

                    validOrderAllocations.RemoveAll(x => x.MonthId <= model.Order.CreationDate.Month && x.AllocationId == allocationId);
                }

                foreach (var allocation in validOrderAllocations)
                {
                    model.Allocations.Add(
                        new OrderAllocation()
                        {
                            AllocationId = allocation.AllocationId,
                            Name = allocation.Budgets_Allocations.Name,
                            MonthId = allocation.MonthId,
                            IsActive = true,
                            Amount = allocation.Amount
                        }
                    );
                }

                ViewBag.Allocations = userAllocations;

                int allAllocationsCount = model.Allocations.Count;
                model.Allocations = model.Allocations.Where(x => userAllocations.Any(a => a.Id == x.AllocationId)).ToList();
                int validAllocationsCount = model.Allocations.Count;

                ViewBag.ReAllocationRequired = allAllocationsCount > validAllocationsCount;
                ViewBag.BudgetYear = activeBudget.Year;
                ViewBag.ExistingItems = ItemsToString(model.Order.Orders_OrderToItem);
                return View(model);
            }
        }
예제 #13
0
        public ActionResult Create(CreateOrderModel model)
        {
            /// Validating user input
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);
            if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form);
            if (String.IsNullOrEmpty(model.ItemsString)) return Error(Loc.Dic.error_invalid_form);
            List<Orders_OrderToItem> ItemsList = ItemsFromString(model.ItemsString, 0);
            if (ItemsList == null || ItemsList.Count == 0) return Error(Loc.Dic.error_invalid_form);
            if (model.IsFutureOrder && !Authorized(RoleType.FutureOrderWriter)) return Error(Loc.Dic.Error_NoPermission);
            if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form);
            model.Allocations = model.Allocations.Where(x => x.IsActive).ToList();
            decimal totalOrderPrice = (decimal.Floor(ItemsList.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000);
            decimal totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000);
            if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation);

            // Initializing needed temporary variables
            bool allowExeeding = true;
            List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>();

            // Setting order properties
            model.Order.UserId = CurrentUser.UserId;
            model.Order.Price = totalOrderPrice;
            model.Order.IsFutureOrder = model.IsFutureOrder;

            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId))
            {
                Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.IsActive);
                if (currentBudget == null) return Error(Loc.Dic.error_database_error);
                model.Order.BudgetId = currentBudget.Id;

                int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray();
                var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending);
                bool IsValidAllocations =
                    (allocationsData.Count == orderAllocationsIds.Length) &&
                    model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0);
                if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form);

                if (model.IsFutureOrder)
                {
                    foreach (var allocationData in allocationsData)
                    {
                        List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList();

                        foreach (var month in allocationMonths)
                        {
                            if (month.MonthId == DateTime.Now.Month)
                            {
                                OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                                var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month);
                                if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                                AllocationsToCreate.AddRange(newAllocations);
                            }
                            else
                            {
                                var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId);
                                if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation);

                                Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation()
                                {
                                    AllocationId = allocationData.AllocationId,
                                    MonthId = month.MonthId.Value,
                                    Amount = month.Amount,
                                    OrderId = 0
                                };

                                AllocationsToCreate.Add(newAllocation);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var allocationData in allocationsData)
                    {
                        OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                        var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month);
                        if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                        AllocationsToCreate.AddRange(newAllocations);
                    }
                }

                if (!CurrentUser.OrdersApprovalRouteId.HasValue)
                {
                    model.Order.NextOrderApproverId = null;
                    model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                }
                else
                {
                    Users_ApprovalRoutes orderRoute = routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep");
                    Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault();

                    if (firstStep != null)
                    {
                        model.Order.ApprovalRouteId = orderRoute.Id;
                        model.Order.ApprovalRouteStep = firstStep.StepNumber;
                        model.Order.NextOrderApproverId = firstStep.UserId;
                        model.Order.StatusId = (int)StatusType.Pending;
                    }
                    else
                    {
                        model.Order.ApprovalRouteStep = null;
                        model.Order.NextOrderApproverId = null;
                        model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                    }
                }
            }

            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (OrderToItemRepository orderToItemRep = new OrderToItemRepository())
            using (OrderToAllocationRepository orderAllocationsRep = new OrderToAllocationRepository())
            {
                bool creationError = false;
                if (!ordersRep.Create(model.Order)) return Error(Loc.Dic.error_orders_create_error);

                model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1");

                foreach (Orders_OrderToItem item in ItemsList)
                {
                    item.OrderId = model.Order.Id;

                    if (!orderToItemRep.Create(item))
                    {
                        creationError = true;
                        break;
                    }
                }

                foreach (var allocation in AllocationsToCreate)
                {
                    allocation.OrderId = model.Order.Id;

                    if (!orderAllocationsRep.Create(allocation))
                    {
                        creationError = true;
                        break;
                    }
                }

                if (creationError)
                {
                    ordersRep.Delete(model.Order.Id);
                    return Error(Loc.Dic.error_orders_create_error);
                }
            }

            using (OrdersHistoryRepository ordersHistoryRepository = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id))
            {
                Orders_History orderHis = new Orders_History();
                ordersHistoryRepository.Create(orderHis, (int)HistoryActions.Created, model.NotesForApprover);
            }

            if (model.Order.NextOrderApproverId.HasValue)
            {
                SendNotifications.OrderPendingApproval(model.Order, Url);
            }

            return RedirectToAction("MyOrders");
        }
예제 #14
0
 public OrderDTO CreateOrder(CreateOrderModel OrderModel, string UserName) =>
 Post($"{_ServiceAddress}/{UserName}", OrderModel)
 .Content
 .ReadAsAsync <OrderDTO>()
 .Result;
예제 #15
0
        public OrderDTO CreateOrder(CreateOrderModel OrderModel, string UserName)
        {
            var response = Post($"{_ServiceAddress}/{UserName}", OrderModel);

            return(response.Content.ReadAsAsync <OrderDTO>().Result);
        }
 public async Task <OrderDTO> CreateOrder(string UserName, [FromBody] CreateOrderModel OrderModel)
 {
     _Logger.LogInformation("Формирование заказа для пользователя {0}", UserName);
     return(await _OrderService.CreateOrder(UserName, OrderModel));
 }
예제 #17
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());
        }
예제 #18
0
 public CreateOrderEventArgs(ExchangeBase exchange, CreateOrderModel model)
 {
     _exchange = exchange;
     _model    = model;
 }
예제 #19
0
 public Task <OrderDTO> CreateOrder(string userName, [FromBody] CreateOrderModel model)
 {
     return(_orderServicee.CreateOrder(userName, model));
 }
예제 #20
0
        public bool Post([FromBody] CreateOrderModel model)
        {
            var entity = new OrderEntity
            {
                OrderNum = GetNewOrderNum(),

                TransCost = GetTransCost(model.LocationX, model.LocationY), //Todo:use db data

                Discount = model.Discount,                                  //Todo:use db data

                Status = EnumOrderStatus.Created,

                DeliveryAddress = model.DeliveryAddress,

                IsPrint = false,

                PhoneNumber = model.PhoneNumber,

                Adduser = model.Type == EnumOrderType.OffLine?_userService.GetUserByName("admin"):(UserBase)_workContext.CurrentUser,

                Addtime = DateTime.Now,

                Upduser = model.Type == EnumOrderType.OffLine ? _userService.GetUserByName("admin") : (UserBase)_workContext.CurrentUser,

                Updtime = DateTime.Now,

                //				Details = model.Details,

                //				Coupon = model.Coupon,

                Type = model.Type,

                PayType = model.PayType,

                LocationX = model.LocationX,

                LocationY = model.LocationY,
            };

            #region 明细
            var details = (from detail in model.Details
                           let product = _productService.GetProductById(detail.ProductId)
                                         where product != null
                                         select new OrderDetailEntity
            {
                Count = detail.Count,
                Product = _productService.GetProductById(detail.ProductId),
                TotalPrice = detail.Count * product.Price,
                Order = entity,
                Remark = detail.Remark
            }).ToList();

            entity.ProductCost = details.Sum(d => d.TotalPrice);
            entity.TotalPrice  = entity.ProductCost - entity.Discount + entity.TransCost;
            entity.Details     = details;

            #endregion
            if (_OrderService.Create(entity).Id > 0)
            {
                return(true);
            }
            return(false);
        }
예제 #21
0
        public async Task <OrderDTO> CreateOrderAsync(string UserName, /*[FromBody]*/ CreateOrderModel OrderModel)
        {
            if (string.IsNullOrEmpty(UserName))
            {
                throw new ArgumentException("Не указано имя пользователя");
            }
            if (string.IsNullOrEmpty(OrderModel.OrderViewModel.Address))
            {
                throw new ArgumentException("Не указан адрес доставки");
            }


            _Logger.LogInformation("Создается заказ для пользователя {0}", UserName);

            var order = await _OrderService.CreateOrderAsync(UserName, OrderModel);

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

            return(await _OrderService.CreateOrderAsync(UserName, OrderModel));
        }
예제 #22
0
 /// <summary>
 /// creates the order when Buy is specified in the input transcation.
 /// Addes the value Mapped Object into a List and Dictionary
 /// </summary>
 /// <param name="createOrder"> Value Mapped Object</param>
 internal void CreateBuyOrder(CreateOrderModel createOrder)
 {
     createOrderModelsList.Add(createOrder);
     myOrderedDictionary.Add(createOrder, createOrder.Quantity);
 }
예제 #23
0
 public IActionResult Post([FromBody] CreateOrderModel createOrderModel)
 {
     CreateOrder(createOrderModel);
     return(Ok("The order request has been successful!"));
 }
예제 #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());
        }
예제 #25
0
        public IActionResult AddNewOrder(CreateOrderModel createOrderModel)
        {
            var timestamp = DateTime.UtcNow;

            var newOrder = new Order
            {
                CustomerIdRef = Int32.Parse(createOrderModel?.CustomerSelected),
                EmployeeRef   = Int32.Parse(createOrderModel?.EmployeeSelected),
                PaymentIdRef  = Int32.Parse(createOrderModel?.PaymentSelected),
                Description   =
                    $"Ordered at {timestamp.ToShortDateString()} by {Int32.Parse(createOrderModel?.CustomerSelected)}. Employee: {Int32.Parse(createOrderModel?.EmployeeSelected)}",
                Status    = (new OrderStatus {
                    Status = OrderStatusEnum.Pending
                }).ToString(),
                Timestamp = timestamp,
            };

            var newOrderCustomer = new OrderCustomer
            {
                CustomerIdRef        = newOrder.CustomerIdRef,
                OrderIdRefNavigation = newOrder
            };

            var newOrderEmployee = new OrderEmployee
            {
                EmployeeIdRef        = newOrder.EmployeeRef,
                OrderIdRefNavigation = newOrder
            };

            var newOrderItems = (from foodItem in createOrderModel?.FoodItemsSelected
                                 select new OrderItem
            {
                FoodItemIdRef = Int32.Parse(foodItem),
                Quantity = 1,
                Order = newOrder
            }).ToList();

            var publisher = new Publisher.Publisher();

            try
            {
                var newOrderMessage = new NewOrderMessage(newOrder, newOrderCustomer, newOrderEmployee, newOrderItems);
                publisher.Publish(newOrderMessage);

                string  customerFullName = null;
                string  employeeFullName = null;
                string  paymentCode      = null;
                decimal totalPrice       = 0;
                using (var context = new FoodServiceContext())
                {
                    var customer = context.Customer.FirstOrDefault(x => x.CustomerId == newOrder.CustomerIdRef);
                    customerFullName = $"{customer.FirstName}, {customer.LastName}";

                    var employee = context.Employee.FirstOrDefault(x => x.EmployeeId == newOrder.EmployeeRef);
                    employeeFullName = $"{employee.FirstName}, {employee.LastName}";

                    var payment = context.Payment.FirstOrDefault(x => x.PaymentId == newOrder.PaymentIdRef);
                    paymentCode = payment.Code;

                    foreach (var orderItem in newOrderItems)
                    {
                        var foodItem = context.FoodItem.FirstOrDefault(x => x.FoodItemId == orderItem.FoodItemIdRef);
                        totalPrice += foodItem.UnitPrice * orderItem.Quantity;
                    }
                }
                var toAppend = $"<tr>" +
                               $"<td>{customerFullName}</td>" +
                               $"<td>{employeeFullName}</td>" +
                               $"<td>{paymentCode}</td>" +
                               $"<td>{newOrder.Status}</td>" +
                               $"<td>{newOrder.Timestamp.ToString()}</td>" +
                               $"<td>{totalPrice}</tr>";
                return(Json(new
                {
                    status = "OK",
                    toAppend = toAppend
                }));
            }
            catch (Exception e)
            {
                return(Json(new
                {
                    status = "ERROR"
                }));
            }
        }
예제 #26
0
        public OrderModel CreateOrder([FromBody] CreateOrderModel model)
        {
            var OrderEntity = new OrderEntity
            {
                TotalPrice = model.TotalPrice,

                OrderNum = GetNewOrderNum(),

                TransCost = GetTransCost(model.LocationX, model.LocationY), //Todo:use db data

                Discount = model.Discount,                                  //Todo:use db data

                Status = EnumOrderStatus.Created,

                DeliveryAddress = model.DeliveryAddress,

                IsPrint = false,

                PhoneNumber = model.PhoneNumber,

                Adduser = model.Type == EnumOrderType.OffLine ? _userService.GetUserByName("13629609670") : (UserBase)_workContext.CurrentUser,

                Addtime = DateTime.Now,

                Upduser = model.Type == EnumOrderType.OffLine ? _userService.GetUserByName("13629609670") : (UserBase)_workContext.CurrentUser,

                Updtime = DateTime.Now,

                //				Details = model.Details,

                //				Coupon = model.Coupon,

                Type = model.Type,

                PayType = model.PayType,

                LocationX = model.LocationX,

                LocationY = model.LocationY,
            };

            #region 明细
            var details = (from detail in model.Details
                           let product = _productService.GetProductById(detail.ProductId)
                                         where product != null
                                         select new OrderDetailEntity
            {
                Count = detail.Count,
                Product = _productService.GetProductById(detail.ProductId),
                TotalPrice = detail.Count * product.Price,
                Order = OrderEntity,
                Remark = detail.Remark
            }).ToList();

            OrderEntity.ProductCost = details.Sum(d => d.TotalPrice);
            OrderEntity.TotalPrice  = OrderEntity.ProductCost - OrderEntity.Discount + OrderEntity.TransCost;
            OrderEntity.Details     = details;
            #endregion
            var OETemp = _OrderService.Create(OrderEntity);
            var entity = _OrderService.GetOrderById(OETemp.Id);
            var oe     = new OrderModel
            {
                Id = entity.Id,

                OrderNum = entity.OrderNum,

                TotalPrice = entity.TotalPrice,

                TransCost = entity.TransCost,

                ProductCost = entity.ProductCost,

                Discount = entity.Discount,

                Status = entity.Status,

                DeliveryAddress = entity.DeliveryAddress,

                IsPrint = entity.IsPrint,

                PhoneNumber = entity.PhoneNumber,

                Adduser = new UserModel {
                    Id = entity.Adduser.Id, UserName = entity.Adduser.UserName
                },

                Addtime = entity.Addtime,

                Upduser = new UserModel {
                    Id = entity.Upduser.Id, UserName = entity.Upduser.UserName
                },

                Updtime = entity.Updtime,

                //		        Details = entity.Details,

                //		        Coupon = entity.Coupon,

                Type = entity.Type,

                PayType = entity.PayType,

                LocationX = entity.LocationX,

                LocationY = entity.LocationY,

                Details = entity.Details.Select(d => new OrderDetailModel()
                {
                    Count       = d.Count,
                    Id          = d.Id,
                    ProductId   = d.Product.Id,
                    ProductName = d.Product.Name,
                    TotalPrice  = d.TotalPrice,
                    UnitPrice   = d.Product.Price,
                    Remark      = d.Remark
                }).ToList()
            };
            return(oe);
        }
예제 #27
0
 public Task <OrderDTO> CreateOrder(string UserName, [FromBody] CreateOrderModel OrderModel) => _OrderService.CreateOrder(UserName, OrderModel);
예제 #28
0
        public async Task <OrderDTO> CreateOrder(CreateOrderModel model)
        {
            var response = await PostAsync <CreateOrderModel>(Address, model);

            return(await response.Content.ReadAsAsync <OrderDTO>());
        }
예제 #29
0
 public OrderDTO CreateOrder([FromBody] CreateOrderModel Model, string UserName)
 {
     return(_orderService.CreateOrder(Model, UserName));
 }
예제 #30
0
        public async Task <OrderDTO> CreateOrder(string UserName, CreateOrderModel OrderModel)
        {
            var response = await PostAsync($"{_ServiceAddress}/{UserName}", OrderModel);

            return(await response.Content.ReadAsAsync <OrderDTO>());
        }
        public async Task <ActionResult <CreateOrderResponseModel> > CreateOrderAsync([FromBody][Required] CreateOrderModel order)
        {
            if (order is null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var primaryOrganisationId = User.GetPrimaryOrganisationId();

            if (primaryOrganisationId != order.OrganisationId)
            {
                return(Forbid());
            }

            var result = await _createOrderService.CreateAsync(new CreateOrderRequest
            {
                LastUpdatedByName = User.GetUserName(),
                LastUpdatedById   = User.GetUserId(),
                Description       = order.Description,
                OrganisationId    = order.OrganisationId,
            });

            var createOrderResponse = new CreateOrderResponseModel();

            if (result.IsSuccess)
            {
                createOrderResponse.OrderId = result.Value;
                return(CreatedAtAction(nameof(CreateOrderAsync).TrimAsync(), null, new { orderId = result.Value }, createOrderResponse));
            }

            createOrderResponse.Errors = result.Errors.Select(x => new ErrorModel(x.Id, x.Field));
            return(BadRequest(createOrderResponse));
        }
예제 #32
0
 public OrderDto CreateOrder([FromBody] CreateOrderModel orderModel, string userName)
 {
     return(_ordersService.CreateOrder(orderModel, userName));
 }
예제 #33
0
 public async Task <int> CreateAsync([FromBody] CreateOrderModel model)
 {
     return(await _orderService.CreateAsync(model));
 }