public void Create(OrderCreateDTO item)
        {
            var order = _mapper.Map <Order>(item);

            _context.Add(order);
            _context.SaveChanges();
        }
示例#2
0
        public void Post([FromBody] OrderCreateDTO orderCreateDTO)
        {
            using (var db = new DBEntities())
            {
                // Create the user
                var newUser = Mapper.Map <User>(orderCreateDTO.User);
                newUser.Id = Guid.NewGuid();

                // Create the order and map the user
                Order newOrder = new Order();
                newOrder.Id              = Guid.NewGuid();
                newOrder.UserId          = newUser.Id.ToString();
                newOrder.TransactionDate = DateTime.UtcNow;

                // Add each item in the order
                foreach (var item in orderCreateDTO.Items)
                {
                    var product = db.Products.Where(p => p.Id.ToString() == item.ProductId).Single();

                    OrderItem orderItem = new OrderItem();
                    orderItem.OrderId       = newOrder.Id.ToString();
                    orderItem.ProductId     = product.Id.ToString();
                    orderItem.Qty           = item.Qty;
                    orderItem.PurchasePrice = product.PurchasePrice;
                    orderItem.SalePrice     = product.SalePrice;
                    db.OrderItems.Add(orderItem);
                }
                db.SaveChanges();
            }
        }
示例#3
0
        public async Task <Order> CreateOrderAsync(Client client, OrderCreateDTO orderInfo)
        {
            Company company = await db.Companies.FirstOrDefaultAsync(c => c.Id == orderInfo.CompanyId, include : c => c.Workers);

            Worker worker = await db.Workers.FirstOrDefaultAsync(w => w.Id == orderInfo.WorkerId, include : w => w.LastLocation);

            if (!ValidateCompany(company, worker))
            {
                return(null);
            }

            if (worker.LastLocation == null)
            {
                return(null);
            }

            var order = Mapper.Map <OrderCreateDTO, Order>(orderInfo);

            order.ClientId        = client.Id;
            order.StartWorkerLat  = worker.LastLocation.Latitude;
            order.StartWorkerLong = worker.LastLocation.Longitude;
            order.BeginingTime    = DateTime.Now;
            order.StatusId        = (int)BuisnessModels.OrderStatus.Awaiting;
            order.Rate            = 0;
            order.Worker          = worker;
            await db.Orders.CreateAsync(order);

            return(order);
        }
示例#4
0
        public void Create(OrderCreateDTO item)
        {
            var order = new Order(item.Date);

            _context.Add(order);
            _context.SaveChanges();
        }
示例#5
0
        public async Task <IActionResult> Create([FromBody] OrderCreateDTO orderCreateDTO)
        {
            var location = GetControllerActionNames();

            try
            {
                _logger.LogInfo($"{location}: Create Attempted");
                if (orderCreateDTO == null)
                {
                    _logger.LogWarn($"{location}: Empty Request was submitted");
                    return(BadRequest(ModelState));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogWarn($"{location}: Data was Incomplete");
                    return(BadRequest(ModelState));
                }

                var order  = _mapper.Map <Order>(orderCreateDTO);
                var result = await _businessLogic.Add(order);

                if (result.IsFailed)
                {
                    return(StatusCode(450, result.Errors[0].Message));
                }
                _logger.LogInfo($"{location}: Creation was successful");
                return(Created("Create", 1));
            }
            catch (Exception e)
            {
                return(InternalError($"{location}: {e.Message} - {e.InnerException}"));
            }
        }
        public async Task <OrderDTO> Create(OrderCreateDTO model)
        {
            var entry = _mapper.Map <Order>(model);

            //complete details
            foreach (var item in entry.items)
            {
                item.Total    = item.UnitPrice * item.Quantity;
                item.Iva      = item.Total * 0.13m;
                item.SubTotal = item.Total - item.Iva;
            }

            //complete order
            entry.Total    = entry.items.Sum(x => x.Total);
            entry.Subtotal = entry.items.Sum(x => x.SubTotal);
            entry.Iva      = entry.items.Sum(x => x.Iva);


            await _context.Orders.AddAsync(entry);

            await _context.SaveChangesAsync();

            return(_mapper.Map <OrderDTO>(await _context.Orders
                                          .Include(x => x.Client)
                                          .Include(x => x.items)
                                          .ThenInclude(x => x.Product)
                                          .SingleAsync(x => x.OrderId == entry.OrderId)));
        }
示例#7
0
        public async Task <OrderDTO> PutAsync(OrderCreateDTO order)
        {
            this.Logger.LogTrace($"{nameof(this.PutAsync)} called");

            var result = await this.OrderCreateService.CreateAsync(this.Mapper.Map <OrderUpdateModel>(order));

            return(this.Mapper.Map <OrderDTO>(result));
        }
        public async Task <ActionResult <OrderCreateDTO> > Post(OrderCreateDTO newOrder)
        {
            //check if order exists
            var check = await _orderRepo.GetOneOrder(newOrder.OrderId);

            if (check == null)
            {
                var createdOrder = new AppOrder()
                {
                    //order
                    OrderId   = await _orderRepo.IdGen(),
                    OrdererId = newOrder.UserId,
                    Date      = newOrder.Date,
                    Total     = newOrder.Total,

                    //order details
                    PackId  = newOrder.PackId,
                    PackQty = newOrder.PackQty // pack qty saved in order detail db table
                };

                //execute any business logic associated with the order
                createdOrder.Pack = await _packRepo.GetOnePack(createdOrder.PackId);

                createdOrder.Orderer = await _userRepo.GetOneUser(createdOrder.OrdererId);

                createdOrder.CalculateTotal();
                //createdOrder.FillOrder();

                //should just call fillOrder(), will modify later
                Random rand = new Random();
                if (createdOrder.Orderer.CurrencyAmount >= createdOrder.Total)
                {
                    createdOrder.Orderer.CurrencyAmount -= createdOrder.Total;
                    int cards = 5 * createdOrder.PackQty;
                    for (int i = 0; i < cards; ++i)
                    {
                        string  cardId = Convert.ToString(rand.Next(64)); //only grabs from the first 64 cards in the set, PackId = base set number
                        AppCard card   = await _orderRepo.GetCardFromApi(cardId, createdOrder.PackId);

                        createdOrder.Orderer.AddCardToInventory(card); //add to the AppUser
                        await _cardRepo.AddOneCard(card);              //add to card table

                        await _userRepo.AddOneCardToOneUser(createdOrder.OrdererId, card.CardId);
                    }
                }
                else
                {
                    throw new Exception("User funds insufficient.");
                }
                await _userRepo.UpdateUserById(createdOrder.OrdererId, createdOrder.Orderer);

                await _orderRepo.AddOneOrder(createdOrder.PackQty, createdOrder);

                return(CreatedAtAction(nameof(GetOrderById), new { id = createdOrder.OrderId }, createdOrder)); //201 new order created
            }

            return(Conflict()); //order already exists and cant be created
        }
        public IActionResult AddOrder(OrderCreateDTO order)
        {
            try
            {
                OrderRepository.Add(order);

                return(Ok("Data inserted"));
            }
            catch (ValidationException)
            {
                return(BadRequest());
            }
        }
示例#10
0
        public async Task <IActionResult> AddOrder([FromBody] OrderCreateDTO orderDTO)
        {
            var execResult = await _service.AddOrder(orderDTO);

            if (execResult.IsSuccess)
            {
                return(Success(execResult.Result));
            }
            else
            {
                return(BadRequest(execResult.Error, execResult.Result));
            }
        }
示例#11
0
 public async Task <IActionResult> Create(OrderCreateDTO orderCreate)
 {
     try
     {
         var order =
             Mapper.Map <OrderDTO>(
                 await OrderCreateService.CreateAsync(Mapper.Map <OrderUpdateModel>(orderCreate)));
         return(Redirect($"/orders/{order.Id}"));
     }
     catch
     {
         ViewData["BookId"]     = new SelectList(Mapper.Map <IEnumerable <BookDTO> >(await BookGetService.GetAsync()), "Id", "Title");
         ViewData["CustomerId"] = new SelectList(Mapper.Map <IEnumerable <CustomerDTO> >(await CustomerGetService.GetAsync()), "Id", "FullName");
         return(View());
     }
 }
示例#12
0
        public async Task <IActionResult> CreateOrderDetail([FromBody] OrderCreateDTO model)
        {
            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    await connection.OpenAsync();

                    var query = @"INSERT INTO [OrderDetail] (orderId, productId, quantity) VALUES (@orderID, @productID, @quantity); SELECT SCOPE_IDENTITY()";
                    await connection.QuerySingleAsync <int>(query, new { model.orderID, model.productID, model.quantity });
                }
                return(Ok());
            }
            catch (Exception e)
            {
                return(Ok(e.Message));
            }
        }
        /// <summary>
        ///  add a new order
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public OrderDTO Add(OrderCreateDTO order)
        {
            Order addedOrder = new Order()
            {
                Id           = Guid.NewGuid(),
                User         = order.BuyerID,
                Address      = order.Address,
                Quantity     = order.Quantity,
                ProductName  = order.ProductName,
                Price        = order.Price,
                Contact      = order.Contact,
                Details      = order.Details,
                OrderDate    = order.OrderDate,
                DeliveryDate = order.DeliveryDate
            };

            Context.Orders.Add(addedOrder);
            Context.SaveChanges();

            return(Mapper.Map <OrderDTO>(addedOrder));
        }
示例#14
0
 public async Task <OrderDTO> Create(OrderCreateDTO orderCreate)
 {
     return(Mapper.Map <OrderDTO>(await OrderCreateService.CreateAsync(Mapper.Map <OrderUpdateModel>(orderCreate))));
 }
示例#15
0
        public async Task <IActionResult> Create([FromHeader(Name = "api_key")] string apiKey, [FromBody] OrderCreateDTO orderInfo)
        {
            Client client = await clientService.GetByApiKeyAsync(apiKey);

            if (client == null)
            {
                return(Unauthorized());
            }

            if (orderInfo == null || !TryValidateModel(orderInfo))
            {
                return(BadRequest(ModelState));
            }

            Order order = await orderService.CreateOrderAsync(client, orderInfo);

            if (order == null)
            {
                return(NotFound());
            }

            var response = new OrderWorkerVM()
            {
                OrderId   = order.Id,
                Name      = order.Worker.Name,
                Latitude  = order.Worker.LastLocation.Latitude,
                Longitude = order.Worker.LastLocation.Longitude,
                Phone     = order.Worker.Phone
            };

            return(Created("", response));
        }
示例#16
0
        public async Task <IHttpActionResult> PostOrder(OrderCreateDTO orderData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            Branch branch = await db.Branches.FindAsync(orderData.branchId);

            if (branch == null)
            {
                return(BadRequest("Branch does not Exist"));
            }

            Customer customer = await db.Customers.FindAsync(branch.customerId);

            if (customer == null)
            {
                return(BadRequest("Customer does not Exist"));
            }

            if (customer.id != branch.customerId)
            {
                return(BadRequest("This branch does not belong to this customer"));
            }

            //ProductPrice price = await db.ProductPrices.Where(b => b.productId==product.id).SingleOrDefaultAsync();

            string   reg   = User.Identity.GetUserId();
            SalesRep sales = await db.SalesReps.Where(a => a.userid == reg).SingleAsync();

            TimeZoneInfo timeInfo = TimeZoneInfo.FindSystemTimeZoneById("South Africa Standard Time");
            DateTime     userTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeInfo);
            Order        order    = new Order
            {
                date       = userTime,
                customerId = branch.customerId,
                branchId   = orderData.branchId,
                status     = "pending",
                salesRepId = sales.id,
            };
            Order odr = db.Orders.Add(order);
            await db.SaveChangesAsync();

            double totalPrice = 0;
            List <OrderProduct> orderItems = new List <OrderProduct>();

            foreach (OrderItem orderItem in orderData.orderItem)
            {
                double  currentPrice = 0;
                Product product      = await db.Products.FindAsync(orderItem.productId);

                if (product == null)
                {
                    return(BadRequest("Product of id " + orderItem.productId + " does not Exist"));
                }

                BranchProductPrice priceBr = await db.BranchProductPrices.Where(b => b.productId == product.id && b.branchId == branch.id).SingleOrDefaultAsync();

                ProductPrice priceCus = await db.ProductPrices.Where(b => b.productId == product.id && b.customerId == customer.id).SingleOrDefaultAsync();


                if (priceBr != null)
                {
                    currentPrice = priceBr.amount * priceBr.case_size;
                    totalPrice  += currentPrice * orderItem.quantity;


                    orderItems.Add(new OrderProduct {
                        orderId = odr.id, price = currentPrice, productId = orderItem.productId, quantity = orderItem.quantity, sku = priceBr.sku
                    });
                }

                else if (priceCus != null)
                {
                    currentPrice = priceCus.amount * priceCus.case_size;
                    totalPrice  += currentPrice * orderItem.quantity;


                    orderItems.Add(new OrderProduct {
                        orderId = odr.id, price = currentPrice, productId = orderItem.productId, quantity = orderItem.quantity, sku = priceCus.sku
                    });
                }

                else
                {
                    return(BadRequest("This retailer does not have this product"));
                }


                //db.OrderProducts.
            }
            lock (Lock)
            {
                string year      = DateTime.Now.Year.ToString();
                string reference = "PO-" + year + "-";
                int    ordNum    = db.Orders.Count();
                if (ordNum == 0)
                {
                    ordNum    += 1;
                    reference += String.Format("{0:00000}", ordNum);
                }
                else
                {
                    ordNum     = db.Orders.Count(b => b.orderNumber.Substring(3, 4) == year);
                    ordNum    += 1;
                    reference += String.Format("{0:00000}", ordNum);
                }
                while (db.Orders.Count(d => d.orderNumber == reference) != 0)
                {
                    reference = "INV-" + year + "-" + String.Format("{0:00000}", ++ordNum);
                }


                odr.price           = totalPrice;
                odr.orderNumber     = reference;
                db.Entry(odr).State = EntityState.Modified;
                db.OrderProducts.AddRange(orderItems);
                db.SaveChanges();
            }


            return(Ok(odr.orderNumber));
        }
示例#17
0
        /// <inheritdoc/>
        public async Task <ServiceExecuteResult <int> > AddOrder(OrderCreateDTO orderDTO)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();

            var orderId = -1;

            try
            {
                /// Создаём рыбу модели заказа
                var order = new Order()
                {
                    OrderId    = 0,
                    FIO        = orderDTO.FIO,
                    Phone      = orderDTO.Phone,
                    Email      = orderDTO.Email,
                    Date       = DateTime.Now,
                    StatusId   = (int)OrderStatusEnum.New,
                    TotalPrice = 0
                };

                var client = new Client()
                {
                    Email = orderDTO.Email,
                    FIO   = orderDTO.FIO,
                    Phone = orderDTO.Phone,
                    IsIncludeInMailing = true
                };

                await _repository.AddOrder(order);

                await _repository.AddClient(client);

                /// Прокидываем связь в позиции заказа
                /// с настоящим товаром
                order.OrderPositions = orderDTO.OrderPositions.Select(x =>
                                                                      new OrderPosition()
                {
                    OrderPositionId = 0,

                    Number = x.Number,
                    Price  = 0,
                    Name   = "",

                    OrderId = order.OrderId,

                    CategoryId    = x.Product.CategoryId,
                    SubcategoryId = x.Product.SubcategoryId,
                    ProductId     = x.Product.ProductId
                })
                                       .ToList();

                await _repository.UpdateOrder(order);

                /// Подгружаем товары, которые мы связали на прошлом шагу
                await _context.Entry(order)
                .Collection(x => x.OrderPositions)
                .Query()
                .Include(x => x.Product)
                .LoadAsync();

                foreach (var orderPos in order.OrderPositions)
                {
                    orderPos.Price = orderPos.Product.Price;
                    orderPos.Name  = orderPos.Product.Alias;
                }
                order.TotalPrice = order.OrderPositions.Select(x => x.Number * x.Price).Sum();

                await _repository.UpdateOrder(order);

                orderId = order.OrderId;

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();

                var msg = $"Не удалось создать заказ по след. причине: {ex.Message}";
                _logger.LogError(ex, $"{msg}. Модель запроса:\n{JsonHelper.Serialize(orderDTO)}");

                return(new ServiceExecuteResult <int>
                {
                    IsSuccess = false,
                    Error = msg,
                    Result = 0
                });
            }

            try
            {
                if (orderId <= 0)
                {
                    throw new Exception($"Отсутствует номер заказа.");
                }

                await _emailService.SendOrderInformation(orderId);
            }
            catch (Exception ex)
            {
                var msg = $"Не удалось отправить письмо на почту по след. причине: {ex.Message}";
                _logger.LogError(ex, msg);

                return(new ServiceExecuteResult <int>
                {
                    IsSuccess = false,
                    Error = msg,
                    Result = orderId != -1 ? orderId : 0
                });
            }

            return(new ServiceExecuteResult <int>
            {
                IsSuccess = true,
                Result = orderId,
            });
        }
示例#18
0
 public async Task <ActionResult <OrderDTO> > Create(OrderCreateDTO orderCreate)
 {
     return(await _orderService.Create(orderCreate));
 }