private async Task <Data.Entities.Order> CreateOrderAsync(string externalId, User user, Data.Entities.Product product, int amount, string statusInformation = "", PaymentMethodEnum paymentMethod = PaymentMethodEnum.STRIPE, OrderStatusEnum status = OrderStatusEnum.PROCESING) { var order = new Data.Entities.Order { ExternalId = externalId, UserId = user.Id, UserEmail = user.Email, UserFullName = user.FullName, ProductId = product?.Id, ProductName = product?.Name, ProductDescription = product?.Description, Amount = amount / 100m, Status = status, StatusInformation = statusInformation, PaymentMethod = paymentMethod, CreatedAt = DateTime.UtcNow, ModifiedAt = DateTime.UtcNow }; await _uow.OrderRepository.AddAsync(order); await _uow.CommitAsync(); return(order); }
private async Task HandlePaymentIntentNotSuccess(PaymentIntent paymentIntent, Data.Entities.Order order, OrderStatusEnum orderStatus) { var statusInformation = orderStatus == OrderStatusEnum.CANCELED ? paymentIntent.CancellationReason : paymentIntent.LastPaymentError?.Message; if (order == null) { order = new Data.Entities.Order { ExternalId = paymentIntent.ClientSecret, Amount = paymentIntent.Amount / 100m, Status = orderStatus, StatusInformation = statusInformation, PaymentMethod = PaymentMethodEnum.STRIPE, CreatedAt = DateTime.UtcNow, ModifiedAt = DateTime.UtcNow }; await _uow.OrderRepository.AddAsync(order); await _uow.CommitAsync(); } else { order.Status = orderStatus; order.StatusInformation = statusInformation; order.ModifiedAt = DateTime.UtcNow; await _uow.OrderRepository.UpdateAsync(order, order.Id); await _uow.CommitAsync(); } }
public void SaveOrder(Domain.Order order, Domain.Location loc, Domain.User u) { try { List <Data.Entities.Location> location = db.Location .Where(l => l.Name.ToLower().Equals(loc.Name.ToLower())) .ToList(); Data.Entities.Location locEntity = location.First(); List <Data.Entities.User> user = db.User .Where(us => us.Username.ToLower().Equals(u.Username.ToLower())) .ToList(); Data.Entities.User userEntity = user.First(); Data.Entities.Order result = new Data.Entities.Order(); result.User = userEntity; result.Loc = locEntity; foreach (var p in order._pizzas) { Data.Entities.Pizza pizzaEntity = new Data.Entities.Pizza(); Data.Entities.PizzaComponent cheeseEntity = new Data.Entities.PizzaComponent(); cheeseEntity.C = GetComponentEntity(p.Cheese); Data.Entities.PizzaComponent crustEntity = new Data.Entities.PizzaComponent(); crustEntity.C = GetComponentEntity(p.Crust); Data.Entities.PizzaComponent sizeEntity = new Data.Entities.PizzaComponent(); sizeEntity.C = GetComponentEntity(p.Size); pizzaEntity.PizzaComponent.Add(cheeseEntity); pizzaEntity.PizzaComponent.Add(crustEntity); pizzaEntity.PizzaComponent.Add(sizeEntity); foreach (var t in p._toppings) { Data.Entities.PizzaComponent toppingEntity = new Data.Entities.PizzaComponent(); toppingEntity.C = GetComponentEntity(t); pizzaEntity.PizzaComponent.Add(toppingEntity); } result.Pizza.Add(pizzaEntity); } db.Add(result); db.SaveChanges(); } catch (System.InvalidOperationException) { } }
private async Task HandleCoinsIncrementActionAsync(Data.Entities.Order order) { var user = order.User; var product = order.Product; if (user != null && product != null && product.Type == ProductEnum.COIN_OFFER) { await _userStatisticsService.UpdateTotalCoinsAsync(user, product.Value); } // TODO: Evaluate with Frontend devs y they need a PN with the success payment completed }
/// <summary> /// Stripe Webhook /// </summary> /// <param name="paymentIntent"></param> /// <returns></returns> public async Task HandlePaymentIntentSucceeded(PaymentIntent paymentIntent) { var clientSecret = paymentIntent.ClientSecret; var order = await GetOrderAsync(clientSecret); if (order == null) { order = new Data.Entities.Order { ExternalId = clientSecret, Amount = paymentIntent.Amount / 100m, Status = OrderStatusEnum.SUCCED, StatusInformation = paymentIntent.ToString(), PaymentMethod = PaymentMethodEnum.STRIPE, CreatedAt = DateTime.UtcNow, ModifiedAt = DateTime.UtcNow }; await _uow.OrderRepository.AddAsync(order); await _uow.CommitAsync(); } else { if (order.Status == OrderStatusEnum.SUCCED) { return; } order.Status = OrderStatusEnum.SUCCED; order.StatusInformation = paymentIntent.Description; order.ModifiedAt = DateTime.UtcNow; await _uow.OrderRepository.UpdateAsync(order, order.Id); await HandleCoinsIncrementActionAsync(order); await _uow.CommitAsync(); } }
public static Domain.Order Map(Data.Entities.Order deOrder) => new Domain.Order { Orderid = deOrder.Orderid, Ocustomerid = deOrder.Ocustomerid, Datetime = deOrder.Datetime };
public void ConfirmOrder() { if (_user == null) { System.Console.WriteLine("Please log in and create an order to confirm your order..."); } else if (_user.CurrentOrder == null) { System.Console.WriteLine("Please create an order to confirm your order..."); } else { ViewLocations(); System.Console.Write("Enter location id: "); int locationId = System.Convert.ToInt32(System.Console.ReadLine()); if (_db.Location.Find(locationId) == null) { System.Console.WriteLine("Please enter a valid id and try again..."); return; } Data.Entities.Order dbOrder = new Data.Entities.Order() { User = _db.User.Find(_user.Id), Location = _db.Location.Find(locationId), OrderTime = System.DateTime.Now }; _db.Add(dbOrder); foreach (Pizza pizza in _user.CurrentOrder.ShoppingCart) { Data.Entities.Pizza p = new Data.Entities.Pizza() { Size = _db.Size.Find(pizza.Size.Id), Crust = _db.Crust.Find(pizza.Crust.Id), Price = pizza.Price }; if (pizza.ToppingList.Count >= 1) { p.ToppingId1 = pizza.ToppingList[0].Id; } if (pizza.ToppingList.Count >= 2) { p.ToppingId2 = pizza.ToppingList[1].Id; } if (pizza.ToppingList.Count >= 3) { p.ToppingId3 = pizza.ToppingList[2].Id; } if (pizza.ToppingList.Count >= 4) { p.ToppingId4 = pizza.ToppingList[3].Id; } if (pizza.ToppingList.Count >= 5) { p.ToppingId5 = pizza.ToppingList[4].Id; } p.OrderId = dbOrder.OrderId; _db.Add(p); } _user.CurrentOrder.CalculatePrice(); _user.OrderHistory.Add(_user.CurrentOrder); _user.CurrentOrder = null; _db.SaveChanges(); } }
public async Task <IActionResult> Create([FromBody] CreateOrderViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _db.Users.SingleAsync(x => x.UserName == HttpContext.User.Identity.Name); var order = new Data.Entities.Order { DeliveryAddress = new Data.Entities.Address { FirstName = model.FirstName, LastName = model.LastName, Address1 = model.Address1, Address2 = model.Address2, TownCity = model.TownCity, County = model.County, Postcode = model.Postcode }, Items = model.Items.Select(x => new Data.Entities.OrderItem { ProductId = x.ProductId, ColorId = x.ColorId, StorageId = x.StorageId, Quantity = x.Quantity }).ToList() }; user.Orders.Add(order); await _db.SaveChangesAsync(); var total = await _db.Orders .Where(x => x.Id == order.Id) .Select(x => Convert.ToInt32(x.Items.Sum(i => i.ProductVariant.Price * i.Quantity) * 100)) .SingleAsync(); var charges = new StripeChargeService(); var charge = await charges.CreateAsync(new StripeChargeCreateOptions { Amount = total, Description = $"Order {order.Id} payment", Currency = "USD", SourceTokenOrExistingSourceId = model.StripeToken }); if (string.IsNullOrEmpty(charge.FailureCode)) { order.PaymentStatus = PaymentStatus.Paid; } else { order.PaymentStatus = PaymentStatus.Declined; } await _db.SaveChangesAsync(); return(Ok(new CreateOrderResponseViewModel(order.Id, order.PaymentStatus))); }
public async Task <bool> ExecutedAsync(int userId, OrderCartViewModel orderCartViewModel) { try { Data.Entities.Order order = new Data.Entities.Order(); if (userId != 0) { order.CreatedBy = userId; orderCartViewModel.ShipmentDetail.UserId = userId; } if (await db.ShipmentDetails.AnyAsync(x => x.Id == orderCartViewModel.ShipmentDetail.Id)) { order.ShipmentDetailId = orderCartViewModel.ShipmentDetail.Id; } else { order.ShipmentDetail = orderCartViewModel.ShipmentDetail; } foreach (CartItemViewModel item in orderCartViewModel.CartItems) { if (await db.Products.Where(x => x.Id == item.Id).AnyAsync(x => x.Quantity.GetValueOrDefault() < orderCartViewModel.CartItems.Count)) { return(false); } order.OrderDetails.Add(new OrderDetail() { ProductId = item.Id, Count = item.Count, Price = item.Price, PromotionPrice = item.PromotionPrice }); } order.DeliveryMethod = orderCartViewModel.DeliveryMethod.Name; order.TotalShipping = orderCartViewModel.DeliveryMethod.Cost; order.PaymentMethod = orderCartViewModel.PaymentMethod; order.Ordered = DateTime.Now; order.Status = 1; db.Orders.Add(order); string body = File.ReadAllText("./Templates/MailOrderInformationTemplate.html"); body = body.Replace("@Name", orderCartViewModel.ShipmentDetail.Name); body = body.Replace("@Status", "được đặt"); body = body.Replace("@Time", DateTime.Now.ToString("dd/MM/yyyy HH:mm")); await sendMail.ExecutedAsync(orderCartViewModel.ShipmentDetail.Email, "Order information", body); await db.SaveChangesAsync(); return(true); } catch (Exception ex) { return(false); } }
public async Task <ApiResult <string> > CreateOrderForUnknownUser(CartDto cartDto) { var sequenceNumber = await _context.Orders.CountAsync(); var orderId = IdentifyGenerator.GenerateOrderId(sequenceNumber + 1); var orderDetail = new List <OrderDetail>(); foreach (var item in cartDto.ListProduct) { var result = await GetProductPrice(item.ProductId); orderDetail.Add(new OrderDetail() { Id = Guid.NewGuid().ToString("D"), Quantity = item.Quantity, OrderId = orderId, ProductId = item.ProductId, UnitPrice = result.Item1 }); } var order = new Data.Entities.Order() { Id = orderId, CustomerAddress = cartDto.Address, CustomerName = cartDto.CustomerName, CustomerPhone = cartDto.PhoneNumber, DateCreated = DateTime.Now, TransactionStatusId = GlobalProperties.WaitingTransactionId, PaymentStatusId = GlobalProperties.UnpaidPaymentId, TotalAmount = orderDetail.Select(x => x.Quantity * x.UnitPrice).Sum(), DiscountValue = 0, DiscountType = "$", OrderDetails = orderDetail }; await _context.Orders.AddAsync(order); await _context.SaveChangesAsync(); var content = $"Cảm ơn quý khách: {order.CustomerName} đã mua hàng tại Máy tính Quang Anh. Đơn hàng của quý khách gồm các sản phẩm: "; foreach (var item in order.OrderDetails) { var product = await _context.Products.Where(x => x.Id == item.ProductId).SingleOrDefaultAsync(); content += $"{product.Name} (Đơn giá: {item.UnitPrice} đồng, Số lượng: {item.Quantity} cái), "; } content += $"để công ty có thể đóng gói và gửi hàng cho quý khách theo địa chỉ:{order.CustomerAddress}, quý khách vui lòng chuyển khoản trước 10% giá trị tổng đơn hàng: {(order.TotalAmount.ToString("#,##0"))} đồng, " + $"tức: {(order.TotalAmount * 10 / 100).ToString("#,##0")} đồng vào Số tài khoản: 0123456789101112, Chủ sở hữu: Hoàng Kim Quang, Ngân hàng Vietcombank với nội dung như sau: \"Chuyen tien dat coc 10% cho don hang ma so: {order.Id}\" " + $".Mong quý khách hãy để ý điện thoại để có thể nhận được thông tin đơn vận chuyển từ nhà vận chuyển, xin cảm ơn quý khách!"; var sendTestEmail = new Message(new string[] { cartDto.Email }, "Xác nhận đơn hàng Máy tính Quang Anh", content, null); try { await _emailSender.SendEmailAsync(sendTestEmail); } catch { return(new ApiResult <string>(HttpStatusCode.OK, $"Tạo đơn hàng thành công") { ResultObj = orderId }); } return(new ApiResult <string>(HttpStatusCode.OK, $"Tạo đơn hàng thành công") { ResultObj = orderId }); }
public async Task <Guid> CreateOrderAsync(NewOrder newOrder) { if (!newOrder.CustomerId.HasValue) { throw new ArgumentException("Customer Id is invalid", "Order.CustomerId"); } if (!newOrder.ResellerId.HasValue) { throw new ArgumentException("Reseller Id is invalid", "Order.ResellerId"); } if (newOrder.Items == null || !newOrder.Items.Any()) { throw new ArgumentException("An order must have at least one order line", "Order.Items"); } var orderId = Guid.NewGuid(); //Get the "Created" status var status = await _orderStatusRepository.GetStatusByName("Created"); var order = new Data.Entities.Order { Id = orderId.ToByteArray(), CreatedDate = DateTime.Now, CustomerId = newOrder.CustomerId.Value.ToByteArray(), ResellerId = newOrder.ResellerId.Value.ToByteArray(), StatusId = status.Id, Items = new List <Data.Entities.OrderItem>() }; foreach (var item in newOrder.Items) { if (!item.ProductId.HasValue) { throw new ArgumentException($"Product Id must be supplied ", "Order.Item.ProductId"); } else { var product = await _orderProductRepository.GetProductById(item.ProductId.Value); if (product == null) { throw new ArgumentException($"Invalid Order Product Id : {item.ProductId}", "Order.Item.ProductId"); } order.Items.Add(new Data.Entities.OrderItem { Id = Guid.NewGuid().ToByteArray(), ProductId = product.Id, Quantity = item.Quantity, ServiceId = product.ServiceId }); } } await _orderRepository.AddOrder(order); return(orderId); }
public async Task AddOrder(Data.Entities.Order order) { _orderContext.Order.Add(order); await _orderContext.SaveChangesAsync(); }
public async Task <ApiResult <string> > CreateOrderFromCartAsync(string customerId) { var checkCustomerAccount = await _context.AppUsers.Where(x => x.Id.ToString() == customerId).SingleOrDefaultAsync(); if (checkCustomerAccount == null) { return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy tài khoản")); } var checkCustomer = await _context.Customers.Where(x => x.AppUserId == checkCustomerAccount.Id).SingleOrDefaultAsync(); if (checkCustomer == null) { return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy khách hàng")); } var carts = await _context.Carts.Where(x => x.AppUserId == checkCustomerAccount.Id).ToListAsync(); if (carts == null || carts.Count == 0) { return(new ApiResult <string>(HttpStatusCode.NotFound, $"Giỏ hàng của khách hàng đang trống")); } if (string.IsNullOrEmpty(checkCustomer.Name) || string.IsNullOrEmpty(checkCustomer.PhoneNumber) || string.IsNullOrEmpty(checkCustomer.Address)) { return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Hãy cập nhập thông tin cá nhân trước khi đặt hàng")); } var sequenceNumber = await _context.Orders.CountAsync(); var orderId = IdentifyGenerator.GenerateOrderId(sequenceNumber + 1); var orderDetails = new List <OrderDetail>(); foreach (var cart in carts) { orderDetails.Add(new OrderDetail() { Id = Guid.NewGuid().ToString("D"), OrderId = orderId, ProductId = cart.ProductId, Quantity = cart.Quantity, UnitPrice = await GetProductPrice(cart.ProductId) }); } var order = new Data.Entities.Order() { Id = orderId, CustomerId = checkCustomer.Id, TransactionStatusId = GlobalProperties.WaitingTransactionId, PaymentStatusId = GlobalProperties.UnpaidPaymentId, TotalAmount = orderDetails.Sum(x => x.Quantity * x.UnitPrice), DateCreated = DateTime.Now, OrderDetails = orderDetails }; await _context.Orders.AddAsync(order); _context.RemoveRange(carts); await _context.SaveChangesAsync(); return(new ApiResult <string>(HttpStatusCode.OK) { ResultObj = orderId, Message = "Đã tạo đơn hàng" }); }