public ResponseModel <Orders> CreateOrder(int customerId, List <ShoppingCart> shoppingCarts) { decimal totalAmount = 0; foreach (ShoppingCart item in shoppingCarts) { Product product = _productRepository.FindById(item.ProductId); totalAmount += product.Price * item.Quantity; } Orders order = new Orders { CustomerId = customerId, OrderDate = DateTime.Now, PaymentTypeId = (int)PaymentType.KrediKarti, StatusId = (int)Status.Kabul, TotalAmount = totalAmount, ApprovedDate = DateTime.Now, ApprovedById = 1 }; _ordersRepository.Add(order); List <OrderDetails> orderDetails = shoppingCarts.Select(x => new OrderDetails { Count = x.Quantity, OrderId = order.Id, ProductId = x.ProductId }).ToList(); foreach (OrderDetails item in orderDetails) { _orderDetailsRepository.Add(item); Product product = _productRepository.FindById(item.ProductId); product.StockQuantity = product.StockQuantity - item.Count; _productRepository.Update(product); } _unitOfWork.Complete(); return(new ResponseModel <Orders> { IsSuccess = true, Message = "Siparişiniz başarıyla alınmıştır", Model = order }); }
public async Task <IActionResult> AddOrder(Order model) { model.State = OrderState.accepted; if (ModelState.IsValid) { try { var OrderId = await OrdersRepository.Add(model); if (OrderId == true) { return(Ok(OrderId)); } else { return(NotFound()); } } catch (Exception) { return(BadRequest()); } } return(BadRequest()); }
public void MakeOrder(string itemName, int userId) { using (var tran = transactionFactory.GetTransaction()) { var order = new Order(itemName, userId); ordersRepository.Add(order); if (ShouldThrowAfterOrderAdd) { throw new Exception("simulated error after adding order"); } var user = usersRepository.Find(userId); user.IncreaseOrdersCount(); usersRepository.Update(user); if (ShouldThrowAfterUserUpdate) { throw new Exception("simulated error after updating user counter"); } tran.Commit(); } }
public Orders AddOrders(Orders orders) { var id = _ordersRepository.Add(orders); orders.Id = id; return(id > 0 ? orders : new Orders()); }
public Result <Order, OrderValidationResult> AddOrder(Order order) { // var customer = _customerRepository.GetCustomer(order.CustomerId); // _orderValidator.Validate(order, customer); // _discountService.ApplyDiscount(order, customer); if (order.OrderLines.Count == 0) { return(new OrderValidationResult { Errors = new List <string> { "Количество позиций не может быть пустым." } }); } _ordersRepository.Add(order); // уведомления других МС о создании нового заказа // OrderCheckoutUseCase - уже будет ответственным за запуск выполнения заказа return(order); }
public IActionResult Order(HomeOrderViewModel viewModel) { if (ModelState.IsValid) { var cocktail = new Cocktail { Id = 3, Name = viewModel.CocktailName, OrderId = _ordersRepository.GetOrders().Last().Id + 1, }; if (!_ordersRepository.GetOrders().Any(o => o.Status == Status.InProgress)) { var order = new Order { Id = _ordersRepository.GetOrders().Last().Id + 1, CustomerName = User.Identity.Name, Cocktails = new List <Cocktail> { cocktail }, Status = Status.InProgress }; _ordersRepository.Add(order); } else { _ordersRepository.GetOrders().First(o => o.Status == Status.InProgress) .Cocktails.Add(cocktail); } } return(RedirectToAction("MyOrders", "Order")); }
public async Task <CommandResult> Handle(CreateOrderCommand request, CancellationToken cancellationToken) { try { var item = _itemsRepository.Query().GetBySizeAndModel(request.Model, request.Size).FirstOrDefault(); var order = Order.Create(item); await _ordersRepository.Add(order); await _warehouseDbContext.SaveChangesAsync(); await _warrantyService.StartWarranty(order.OrderItemUid); return(new CommandResult { IsCompleted = true }); } catch (Exception ex) { return(new CommandResult { IsCompleted = false, Reason = ex.Message }); } }
public int ConfirmOrder(ref Cart cart) { var orderId = 0; using (var transacton = _ordersRepository.DataContext.Database.BeginTransaction()) { try { var order = new Order { MemberId = cart.MemberId, OrderValue = cart.CartTotalPriceOut, CreationDate = DateTime.Now }; _ordersRepository.Add(order); _ordersRepository.DataContext.SaveChanges(); var orderOrderStatus = new OrderOrderStatus { OrderId = order.OrderId, OrderOrderStatusId = (int)OrderStatusType.Confirmed, CreationDate = DateTime.Now }; _orderOrderStatusRepository.Add(orderOrderStatus); _orderOrderStatusRepository.DataContext.SaveChanges(); order.LatestOrderStatusId = orderOrderStatus.OrderOrderStatusId; _ordersRepository.DataContext.SaveChanges(); if (order.OrderId > 0 && cart.Items != null) { foreach (var item in cart.Items) { var orderItem = new OrderItem { OrderId = order.OrderId, ProductId = item.ProductId, ProductCount = item.ProductCount, PriceOut = item.PriceOut, TotalPriceOut = item.TotalPriceOut, CreationDate = DateTime.Now }; _orderItemRepository.Add(orderItem); _orderItemRepository.DataContext.SaveChanges(); } } transacton.Commit(); ClearCart(ref cart); orderId = order.OrderId; } catch (Exception) { transacton.Rollback(); } } return(orderId); }
public async Task Consume(ConsumeContext <OrderPlaced> context) { await _ordersRepository.Add(new Order { Id = context.Message.OrderId, Status = "Placed", Number = "", LastUpdate = context.Message.TimeStamp, UserId = context.Message.UserId }); await _dbContext.SaveChangesAsync(); }
internal int AddOrderToDB(OrdersRentVM viewModel) { Orders order = new Orders() { CarId = viewModel.CarId, RentalDate = viewModel.RentalDate, ReturnDate = viewModel.ReturnDate, KilometerBeforeRental = ordersRepository.GetKilometreBeforeRental(viewModel.CarId), CustomerId = customersService.GetCustomersIdFromPersonNumber(viewModel.personNumber) }; ordersRepository.Add(order); eventsService.CreateNewOrderEvent(order); return(order.Id); }
// POST api/Orders public IHttpActionResult Post([FromBody] Orders value) { try { _db.Add(value); } catch (Exception ex) { ModelState.AddModelError(nameof(Orders), ex.Message); return(BadRequest(ModelState)); } return(Ok()); }
public void CreateOrder(CreateOrderRequest orderDto) { ValidatePhoneNumber(orderDto.ReceiverPhoneNumber); ValidatePostamatNumber(orderDto.PostamatNumber); ValidateGoods(orderDto.Goods); var order = new Order(orderDto.PostamatNumber) { Goods = orderDto.Goods, OrderNumber = orderDto.OrderNumber, Price = orderDto.Price, ReceiverFullName = orderDto.ReceiverFullName, ReceiverPhoneNumber = orderDto.ReceiverPhoneNumber }; _ordersRepository.Add(order); }
public IHttpActionResult CreateOrders([FromBody] Order ordersObj) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ordersrepository.Add(ordersObj); } catch (Exception ex) { throw ex; } return(Ok(ordersObj)); }
public IActionResult AddOrder([FromBody] OrderToUpsert orderToAdd) { if (orderToAdd == null) { return(BadRequest()); } var order = _mapper.Map <Order>(orderToAdd); _ordersRepository.Add(order); _ordersRepository.Save(); var orderToGet = _mapper.Map <OrderToGet>(order); return(CreatedAtRoute("GetOrder", new { id = orderToGet.OrderId }, orderToGet)); }
public Order CreateOrder(CreateOrderQuery createOrderQuery) { Person person = _personsRepository.Add(new Person { Email = createOrderQuery.Person.Email, FirstName = createOrderQuery.Person.FirstName, LastName = createOrderQuery.Person.LastName, MiddleName = createOrderQuery.Person.MiddleName, PhoneNumber = createOrderQuery.Person.PhoneNumber }); Order order = _ordersRepository.Add(new Order { Person = person, AdditionalComment = createOrderQuery.AdditionalComment }); _orderStatusHistoryItemsRepository.Add(new OrderStatusHistoryItem { Created = DateTime.Now, OrderId = order.Id, Status = OrderStatus.Open }); foreach (CreateOrderQuery.AddOrderedProductQuery addOrderedProductQuery in createOrderQuery.OrderedProducts) { Product product = _productsRepository.GetById(addOrderedProductQuery.ProductId); _orderedProductsRepository.Add(new OrderedProduct { ProductId = addOrderedProductQuery.ProductId, Product = product, Quantity = addOrderedProductQuery.Quantity, OrderId = order.Id, PriceAtTheTimeOfPurchase = product.PriceInTheMainCurrency }); order.TotalAmount += product.PriceInTheMainCurrency * addOrderedProductQuery.Quantity; } _ordersRepository.Update(order); NotifyAboutOrder(order); return(order); }
public Result <Order> Add(Order item) { //TODO: Czy w tych godzinach nie ma problemu z zrobieniem item.OrderDate = System.DateTime.Now; item.ExpectedStartOfOrder = item.ExpectedStartOfOrder.Value.ToLocalTime(); item.ExpectedStartOfOrder = new DateTime(item.ExpectedStartOfOrder.Value.Ticks); item.User = null; item.OrdersTemplate = null; var r = _orderRepository.Add(item); if (r.status) { r.value.User = _userService.GetById(r.value.UserId).value; r.value.OrdersTemplate = orderTemplateService.GetById(r.value.OrderTemplateId).value; } return(r); }
public async Task Consume(ConsumeContext <PlaceOrder> context) { Console.WriteLine($"Message received: {JsonSerializer.Serialize(context.Message)}"); var orderNumber = await _orderNumberGenerator.GetNumber(context.Message.UserId); var order = new Order { Id = context.Message.Id, Number = orderNumber, ProductIds = string.Join(",", context.Message.ProductIds), ShippingTypeId = context.Message.ShippingTypeId, UserId = context.Message.UserId, TimeStamp = DateTime.UtcNow, Amount = _costCalculator.CostForProducts(context.Message.ProductIds) }; await _ordersRepository.Add(order); await _dbContext.SaveChangesAsync(); //Some expensive calculation Thread.Sleep(10000); await _eventBus.Publish(new OrderCreated { OrderId = order.Id, Number = order.Number, ProductIds = order.ProductIds.Split(","), ShippingTypeId = order.ShippingTypeId, UserId = order.UserId, TimeStamp = order.TimeStamp, Amount = order.Amount }); await _commandBus.Send(new CreateShipping { OrderId = order.Id, UserId = order.UserId, ShippingTypeId = order.ShippingTypeId }); }
public IActionResult CreateOrder([FromBody] OrderToUpsert orderToAdd) { if (orderToAdd == null) { return(BadRequest()); } var order = _mapper.Map <Order>(orderToAdd); if (order.StoreId == Guid.Empty) { return(new UnprocessableEntityResult(ModelState)); } _ordersRepository.Add(order); _ordersRepository.Save(); var orderToGet = _mapper.Map <OrderToGet>(order); return(CreatedAtRoute(new { OrderId = orderToGet.OrderId }, orderToGet)); }
public IHttpActionResult Post([FromBody] Product product) { try { if (product.Quantity < 0) { return(BadRequest($"Invalid quantity: {product.Quantity}")); } var createdProduct = _ordersRepository.Add(product); var url = Request.RequestUri + "/" + product.Name; return(Created(url, content: createdProduct)); } catch (Exception) { //Log the error return(InternalServerError()); } }
public void Create(Order order) { order.Status = OrderStatus.InProgress; _ordersRepository.Add(order); }
public void CompleteOrder(int userId, int cartsId, Orders order) { order.CartsId = cartsId; order.UsersId = userId; _repOrder.Add(order); }
public AddOrderResponse OrderAdd(DateTime date, Order order, int originalOrderNumber) { AddOrderResponse response = new AddOrderResponse(); response.order = new Order(); if (order.OrderDate < DateTime.Now) { response.Success = false; response.Message = "The date you entered was not in the future."; return(response); } if (order.Area < 100.00M) { response.Success = false; response.Message = "The area you entered was not greater than 100 sq feet."; return(response); } TaxesRepository taxRepo = new TaxesRepository(); Taxes tax = null; tax = taxRepo.List().FirstOrDefault(t => t.StateAbbreviation.ToUpper() == order.State); if (tax == null) { response.Success = false; response.Message = "The state abbreviation you entered does not match to any state we do business in"; return(response); } ProductRepository productRepo = new ProductRepository(); Product product = null; product = productRepo.List().FirstOrDefault(p => p.ProductType.ToUpper() == order.ProductType.ToUpper()); if (product == null) { response.Success = false; response.Message = "The product type you entered does not match to any of the prodcuts that we offer."; return(response); } bool result = order.CustomerName.All(c => Char.IsLetterOrDigit(c) || c == '.' || c == ',' || c == ' '); order.CustomerName = order.CustomerName.Trim(); if (order.CustomerName == string.Empty) { response.Success = false; response.Message = "The customer name you entered cannot contain only spaces"; return(response); } if (result == false) { response.Success = false; response.Message = "The customer name you entered contained an invalid value"; return(response); } else { _ordersRepository.Add(order, originalOrderNumber); response.Success = true; return(response); } }
public void Add(Order orders) { ordersRepository.Add(orders); unitOfWork.Commit(); }
public ActionResult UpdateLimitSuccess(string operation_xml, string signature) { string message = string.Format(Translation.Translation.UpdateFail, ConfigurationManager.AppSettings["ContactNumbers"]); User authenticatedUser = _userRepository.GetUserByPhone(User.Identity.Name); if (authenticatedUser != null) { string signatureFromAnswer = LiqPay.GetSignFromAnswer(operation_xml); if (signatureFromAnswer == signature) { Order order = new Order(); XmlDocument doc = new XmlDocument(); doc.LoadXml(LiqPay.GetOperationXmlFromAnswer(operation_xml)); XmlNode nodeOrderId = doc.SelectSingleNode("response/order_id"); if (nodeOrderId != null) { order.OrderId = Guid.Parse(nodeOrderId.InnerText); } XmlNode nodeGoodId = doc.SelectSingleNode("response/goods_id"); if (nodeGoodId != null) { order.ProfileId = int.Parse(nodeGoodId.InnerText); } XmlNode nodeAmmount = doc.SelectSingleNode("response/amount"); if (nodeAmmount != null) { order.Ammount = decimal.Parse(nodeAmmount.InnerText); } XmlNode nodeStatus = doc.SelectSingleNode("response/status"); if (nodeStatus != null) { order.Status = nodeStatus.InnerText; } order.User = authenticatedUser; order.Created = DateTime.Now; _ordersRepository.Add(order); _ordersRepository.SaveChanges(); if (order.Status == "success") { Profile profile = _profilesRepository.GetById(order.ProfileId); authenticatedUser.Profile = profile; if (authenticatedUser.ProfileExpires.HasValue) { authenticatedUser.ProfileExpires = authenticatedUser.ProfileExpires.Value.AddMonths(1); } else { authenticatedUser.ProfileExpires = DateTime.Now.AddMonths(1); } IEnumerable <Announcement> addAnnouncements = authenticatedUser.Apartments.OrderByDescending(an => an.Created).Skip(profile.MaxAnnouncements); foreach (Announcement announcement in addAnnouncements) { announcement.IsVisible = true; } foreach (Announcement announcement in authenticatedUser.Apartments) { IEnumerable <Photo> addPhotos = announcement.Photos.OrderByDescending(p => p.Created).Skip(profile.MaxPhotosPerAnnouncements); foreach (Photo photo in addPhotos) { photo.IsVisible = true; } } _userRepository.SaveChanges(); message = Translation.Translation.UpdateSuccess; } } } TempData["UpdateLimitSuccessMessage"] = message; return(RedirectToAction("UpdateLimit")); }
/// <summary> /// Create a new purchase order /// </summary> /// <param name="purchaseordertype"></param> public IHttpActionResult Post(Models.PurchaseOrderType purchaseordertype) { ordersRepository.Add(purchaseordertype); return(Ok()); }
public IActionResult HandlePurchase([FromBody] PaymentRequest paymentInfo) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //validating body if (paymentInfo.Amount <= 0) { return(BadRequest("Amount to pay must is invalid")); //change request code } if (!ValidCreditCardNumber(paymentInfo.Number)) { return(BadRequest("Credit card info is invalid")); } if (paymentInfo.Holder.Length < 2 || paymentInfo.Holder.Length > 32) { return(BadRequest("Card holder name is invalid")); } if (paymentInfo.Exp_Year < 1970) { return(BadRequest("Card expiration year is invalid")); } if (paymentInfo.Exp_Month < 1 || paymentInfo.Exp_Month > 12) { return(BadRequest("Card expiration month is invalid")); } if (!ValidCvv(paymentInfo.Cvv)) { return(BadRequest("Card cvv security code is invalid")); } //get user for further information var username = JWTtoken.GetUsernameFromToken(Request); var user = _ordersRepository.GetOrderingUser(username); //check if payment ammount matches shopping cart total amount decimal ammount = (decimal)paymentInfo.Amount / 100; if (!_ordersRepository.PaymentEqualsShoppingCartSum(user, ammount)) { return(BadRequest("Payment ammount does not match the shopping cart total ammount")); } //Get current user items in the shopping cart var items = _ordersRepository.GetShoppingCartItems(user); //make payment //*****make payment***** var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://mock-payment-processor.appspot.com/v1/payment"); httpWebRequest.Credentials = new NetworkCredential("technologines", "platformos"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(paymentInfo); streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } try { var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); PaymentResponse paymentResponseInfo = new PaymentResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); var paymentResponseJson = JObject.Parse(result); paymentResponseInfo.Created_At = (DateTime)paymentResponseJson["created_at"]; paymentResponseInfo.Id = (string)paymentResponseJson["id"]; } //*****payment made****** //create new order with those items list Order newOrder = new Order { Cost = ammount, Date = DateTime.Now, UserId = user.Id, OrderedItem = items, PaymentId = paymentResponseInfo.Id, PaymentDate = DateTime.Now }; //save order to the database newOrder = _ordersRepository.Add(newOrder); //add new orders id to the ordered items foreach (var orderedItem in items) { orderedItem.OrderId = newOrder.Id; } //clear shopping cart _ordersRepository.ClearUserShoppingCart(user); if (newOrder.PaymentId != null) { _ordersRepository.ClearUserShoppingCart(user); return(Ok("Purchase successful")); } } catch (Exception ex) { return(BadRequest("Payment went wrong")); } return(BadRequest("Payment went wrong")); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var orderSerializer = new XmlSerializer(typeof(PurchaseOrderType)); var ordersSerializer = new XmlSerializer(typeof(PurchaseOrdersType)); var responseMessage = new HttpResponseMessage(); var stream = new MemoryStream(); var localPath = request.RequestUri.LocalPath; // GET /orders/notshipped if (localPath.EndsWith("/orders/notshipped")) { ordersSerializer.Serialize(stream, repository.GetNotShipped()); } // GET /orders/shipped if (localPath.EndsWith("/orders/shipped")) { ordersSerializer.Serialize(stream, repository.GetShipped()); } // POST /orders/{id}/ship if (localPath.EndsWith("/ship") && request.Method == HttpMethod.Post) { var shipUrl = localPath; var shipId = shipUrl.Replace("/api/orders/", string.Empty).Replace("/ship", string.Empty); var shipOrder = repository.Get(shipId); shipOrder.shipped = true; repository.Update(shipOrder); } // POST /orders if (localPath.EndsWith("/orders") && request.Method == HttpMethod.Post) { var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); var xml = Encoding.UTF8.GetString(result); var newOrder = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml)); repository.Add(newOrder); } // PUT /orders if (request.Method == HttpMethod.Put) { var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); var xml = Encoding.UTF8.GetString(result); var orderToUpdate = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml)); repository.Update(orderToUpdate); } if (request.Method == HttpMethod.Get && !localPath.EndsWith("/orders") && !localPath.EndsWith("/orders/") && !localPath.EndsWith("shipped")) { // GET /orders/{id} var url = localPath; var id = url.Replace("/api/orders/", string.Empty); var order = repository.Get(id); orderSerializer.Serialize(stream, order); } var content = Encoding.UTF8.GetString(stream.GetBuffer()); content = content.Substring(content.IndexOf(Environment.NewLine) + 1); responseMessage.Content = new StringContent(content, Encoding.UTF8, "application/xml"); return(Task.FromResult(responseMessage)); }