public async Task<IActionResult> ClientCartGet() { var customer = await GetCustomerFromSession(); if (customer == null) { return Ok(ResponseDTO.BadRequest()); } var cart = await _context.Carts.FirstOrDefaultAsync(o => o.CustomerId == customer.Id); if (cart == null) { return Ok(ResponseDTO.OkEmpty()); } var cartItems = await _context.CartItems .Include(c => c.Stock).ThenInclude(o => o.Shoes).ThenInclude(o => o.ShoesImages) .Include(c => c.Stock).ThenInclude(o => o.Size) .Where(o => o.CartId == cart.Id) .ToListAsync(); var items = new List<dynamic>(); foreach (var item in cartItems) { items.Add(new { stockId = item.Stock.Id, shoesId = item.Stock.ShoesId, name = item.Stock.Shoes.Name, sizeName = item.Stock.Size.Name, quantity = item.Amount, price = item.Stock.Shoes.Price, image = item.Stock.Shoes.ShoesImages.FirstOrDefault().ImagePath }); } return Ok(ResponseDTO.Ok(items, items.Count)); }
public async Task <IActionResult> ClientUpdateAddress([FromBody] BodyAddressDTO dto) { var customer = await GetCustomer(); if (customer == null) { return(Ok(ResponseDTO.BadRequest("Invalid customers' username."))); } var updateAddress = customer.Addresses.FirstOrDefault(c => c.Id == dto.id); if (updateAddress != null) { updateAddress.City = dto.city; updateAddress.District = dto.district; updateAddress.Ward = dto.ward; updateAddress.Street = dto.street; updateAddress.CustomerId = customer.Id; updateAddress.RecipientName = dto.name; updateAddress.RecipientPhoneNumber = dto.phoneNumber; } else { return(Ok(ResponseDTO.NotFound("Invalid ID for updated address."))); } await _context.SaveChangesAsync(); var listResponse = new List <object>(); foreach (var add in customer.Addresses) { listResponse.Add(ConvertToResponseAddressDTO(add, customer.Id)); } return(Ok(ResponseDTO.Ok(listResponse))); }
public async Task <IActionResult> ClientGetCustomerAddress() { var sessionUsername = HttpContext.Session.GetString(SessionConstant.Username); if (string.IsNullOrEmpty(sessionUsername)) { return(Ok(ResponseDTO.BadRequest())); } var customer = await _repository.FirstOrDefault(c => c.Username == sessionUsername); if (customer == null) { return(Ok(ResponseDTO.NotFound())); } var listResult = new List <dynamic>(); foreach (var address in customer.Addresses) { listResult.Add(ConvertToResponseAddressDTO(address, customer.Id)); } return(Ok(ResponseDTO.Ok(listResult))); }
public async Task <IActionResult> AddShoesForAdmin([FromBody] BodyCreateShoes model) { // Validate if (!model.IsValid()) { return(Ok(ResponseDTO.BadRequest("Not enough information to create."))); } if (await isExist(model.Code)) { return(Ok(ResponseDTO.BadRequest("Shoes's code is already existed"))); } var images = model.Images; Console.WriteLine(model.Images.Count); var shoesImages = new List <ShoesImage>(); foreach (var image in images) { var shoesImage = new ShoesImage { ColorId = image.ColorId, ImagePath = image.ImagePath, }; shoesImages.Add(shoesImage); } var stocks = new List <Stock>(); foreach (var item in model.Stocks) { var s = new Stock { ColorId = item.ColorId, SizeId = item.SizeId, Instock = item.Instock, }; stocks.Add(s); } var shoes = new Shoes() { Code = model.Code, Name = model.Name, Description = model.Description, Rating = model.Rating, Price = model.Price, IsNew = model.IsNew, IsOnSale = model.IsOnSale, StyleId = model.StyleId, BrandId = model.BrandId, GenderId = model.GenderId, ShoesImages = shoesImages, Stocks = stocks }; if (shoes.IsNew) { shoes.IsNew = true; } return(await this._AddItem(shoes)); }
public async Task <IActionResult> ClientRateShoes([FromBody] BodyShoesRatingDTO model) { // Check customer var customer = GetCustomer(); if (customer == null) { return(Ok(ResponseDTO.BadRequest("Login required."))); } // Parse var shoesId = 0; try { shoesId = int.Parse(model.shoesId); } catch { return(Ok(ResponseDTO.BadRequest("Invalid shoesId."))); } // Check shoes var shoes = await _context.Shoes .Include(c => c.ShoesBrand) .Include(c => c.Gender) .Include(c => c.ShoesType) .Include(c => c.ShoesImages) .Include(c => c.Stocks).ThenInclude(c => c.Size) .FirstOrDefaultAsync(c => c.Id == shoesId); if (shoes == null) { return(Ok(ResponseDTO.BadRequest("Invalid shoesId."))); } if (model.rating < 0) { model.rating = 0; } if (model.rating > 5) { model.rating = 5; } var review = _context.CustomerReviews.FirstOrDefault(c => c.CustomerId == customer.Id && c.ShoesId == shoes.Id); if (review != null) { review.Rate = model.rating; await _context.SaveChangesAsync(); } else { review = new CustomerReview() { ShoesId = shoes.Id, CustomerId = customer.Id, Rate = model.rating, Content = "", Date = DateTime.Now }; _context.CustomerReviews.Add(review); await _context.SaveChangesAsync(); } // Get rating var ratingInfo = GetRatingForShoes(shoes.Id); // Update shoesrating shoes.Rating = ratingInfo.rating; await _context.SaveChangesAsync(); // Get sale var saleInfo = GetSaleInfo(shoes.Id); List <object> sizes = (List <object>)shoes.Stocks.Select(c => (object)c.Size.Name).ToList(); var result = new ResponseShoesDetailDTO() { id = shoes.Id, code = shoes.Code, name = shoes.Name, description = shoes.Description, rating = ratingInfo.rating, ratingCount = ratingInfo.ratingCount, styleName = shoes.ShoesType.Name, brandName = shoes.ShoesBrand.Name, genderName = shoes.Gender.Name, price = shoes.Price, isNew = shoes.IsNew, isOnSale = saleInfo.isOnSale, salePrice = saleInfo.salePrice, images = shoes.ShoesImages.Select(c => c.ImagePath).ToList(), sizes = sizes }; return(Ok(ResponseDTO.Ok(result))); }
public async Task <IActionResult> Get([FromQuery] ReportDto dto) { var target = dto.Target; if (dto.FromDate == null || dto.ToDate == null || DateTime.Compare(dto.FromDate, dto.ToDate) >= 0) { return(BadRequest(ResponseDTO.BadRequest())); } List <string> categories = new List <string>(); List <List <Order> > orderList = new List <List <Order> >() { }; List <BestSale> bests = new List <BestSale>() { }; List <CustomDate> months = new List <CustomDate>() { }; var totalDay = (int)(dto.ToDate - dto.FromDate).TotalDays; int step = 1; if (totalDay > 60) { step = 30; } else if (totalDay > 14) { step = (int)totalDay / 7; } bool add = true; DateTime checkpoint = dto.FromDate; for (DateTime date = dto.FromDate; date <= dto.ToDate; date = date.AddDays(1)) { if (step == 30) { if (date.Month == checkpoint.Month) { if (add == true) { categories.Add(date.ToString("MMM yyyy")); months.Add(new CustomDate { Month = date.Month, Year = date.Year }); add = false; checkpoint = date; } } else { categories.Add(date.ToString("MMM yyyy")); months.Add(new CustomDate { Month = date.Month, Year = date.Year }); checkpoint = date; } } else { if ((int)(date - checkpoint).TotalDays == step || date == dto.ToDate || date == dto.FromDate) { categories.Add(date.ToString("dd/MM")); checkpoint = date; } else { categories.Add(""); } } var orders = await GetOrder(date); orderList.Add(orders); if (orders != null) { foreach (var order in orders) { var items = _context.OrderItems.Where(x => x.OrderId == order.Id).ToList(); foreach (var item in items) { var stock = await _context.Stocks.FirstOrDefaultAsync(x => x.Id == item.StockId); var shoes = await _context.Shoes.FirstOrDefaultAsync(x => x.Id == stock.ShoesId); var shoesImages = _context.ShoesImages.Where(x => x.ShoesId == shoes.Id).ToList(); var image = ""; if (shoesImages.Count != 0) { image = shoesImages[0].ImagePath; } var id = stock.ShoesId; var bestSale = bests.FirstOrDefault(x => x.Id == id); if (bestSale == null) { var sale = new BestSale { Id = id, Name = shoes.Name, Image = image, Price = item.Total, Amount = item.Amount }; bests.Add(sale); } else { bestSale.Amount += item.Amount; bestSale.Price += item.Total; } } } } } bests = bests.OrderBy(x => x.Amount).Take(3).ToList(); if (target == ReportConstants.REVENUE) { List <int> data = new List <int>(); if (step != 30) { foreach (var orders in orderList) { if (orders == null) { data.Add(0); } else { var total = 0; foreach (var order in orders) { total += (int)order.Total; } data.Add(total); } } } else { foreach (var month in months) { var orders = orderList.FindAll(x => x.Count > 0 && x[0].OrderDate.Month == month.Month && x[0].OrderDate.Year == month.Year).ToList(); if (orders.Count == 0) { data.Add(0); } else { var total = 0; foreach (var order in orders) { foreach (var o in order) { total += (int)o.Total; } } data.Add(total); } } } var xAxis = new XAxis { categories = categories }; var yAxis = new YAxis { label = new Label { format = "{value} đ", style = new Style { } }, title = new Title { text = "Doanh thu", style = new Style { } } }; var series = new Series { name = "Doanh thu", type = "spline", data = data, tooltip = new Tooltip { valueSuffix = "đ" } }; var response = new ResponseReportDto { xAxis = xAxis, yAxis = yAxis, series = new List <Series>() { series }, bestSales = bests }; return(Ok(ResponseDTO.Ok(response))); } else if (target == ReportConstants.ORDERS) { List <int> data = new List <int>(); if (step != 30) { foreach (var orders in orderList) { if (orders == null) { data.Add(0); } else { data.Add(orders.Count); } } } else { foreach (var month in months) { var orders = orderList.FindAll(x => x.Count > 0 && x[0].OrderDate.Month == month.Month && x[0].OrderDate.Year == month.Year).ToList(); if (orders.Count == 0) { data.Add(0); } else { var total = 0; foreach (var order in orders) { total += order.Count; } data.Add(total); } } } var xAxis = new XAxis { categories = categories }; var yAxis = new YAxis { label = new Label { format = "{value} đơn", style = new Style { } }, title = new Title { text = "Đơn hàng", style = new Style { } } }; var series = new Series { name = "Doanh thu", type = "column", data = data, tooltip = new Tooltip { valueSuffix = " đơn" } }; var response = new ResponseReportDto { xAxis = xAxis, yAxis = yAxis, series = new List <Series>() { series }, bestSales = bests }; return(Ok(ResponseDTO.Ok(response))); } return(Ok(ResponseDTO.Ok("Ok"))); }
public async Task <IActionResult> ClientAddCustomer([FromBody] BodyCreateCustomer model) { // Get username if (model.username == null) { model.username = model.email; } // Get gender var gender = 0; if (model.gender.ToLower() == "nam" || model.gender.ToLower() == "male") { gender = 1; } // Validate var existed = await _repository.ExistWhere(c => c.Email == model.email || c.PhoneNumber == model.phoneNumber || c.Username == model.username); if (existed) { return(BadRequest(ResponseDTO.BadRequest("Khách hàng đã tồn tại."))); } // Create pass byte[] passwordHash, passwordSalt; SecurityHelper.CreatePasswordHash(model.password, out passwordHash, out passwordSalt); var customer = new Customer { DeleteFlag = false, Username = model.username, PasswordHash = passwordHash, PasswordSalt = passwordSalt, Name = model.name, Gender = gender, Point = 0, PhoneNumber = model.phoneNumber, Email = model.email, DateOfBirth = model.dateOfBirth, CustomerTypeId = model.customerTypeId }; // Create customer var result = await _repository.Add(customer); var claims = new[] { new Claim("sub", customer.Username) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds, }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); var response = new ResponseLoginDto { id = result.Id, name = result.Name, dateOfBirth = result.DateOfBirth, email = result.Email, phoneNumber = result.PhoneNumber, gender = result.Gender, authorizedToken = tokenString }; return(Ok(ResponseDTO.Ok(response))); }
public async Task <IActionResult> ClientGetOrderList() { // Get customer var customer = GetCustomer(); if (customer == null) { return(Ok(ResponseDTO.BadRequest("Invalid customer's username."))); } // Get orders var orders = customer.Orders; var listResults = new List <ClientOrderResponseDTO>(); foreach (var order in orders) { // Get address var sendAddress = await _context.Addresses.FirstOrDefaultAsync(c => c.Id == (order.AddressId ?? 0)); if (sendAddress == null) { // return Ok(ResponseDTO.BadRequest("Invalid addrss for current order.")); continue; } // Response var orderItems = order.OrderItems; List <ClientOrder_CartItemDTO> cartItemDTOList = new List <ClientOrder_CartItemDTO>() { }; foreach (var item in orderItems) { var stock = await _context.Stocks.FirstOrDefaultAsync(s => s.Id == item.StockId); var shoes = await _context.Shoes.FirstOrDefaultAsync(s => s.Id == stock.ShoesId); var image = await _context.ShoesImages.FirstOrDefaultAsync(i => i.ShoesId == item.Stock.ShoesId); var size = await _context.Sizes.FirstOrDefaultAsync(s => s.Id == stock.SizeId); var cart = new ClientOrder_CartItemDTO { stockId = item.Id, shoesId = shoes.Id, name = shoes.Name, sizeName = size.Name, quantity = item.Amount, price = item.Total, image = image != null ? image.ImagePath : "" }; cartItemDTOList.Add(cart); } var responseDTO = new ClientOrderResponseDTO() { id = order.Id, customerID = customer.Id, saleID = 0, city = sendAddress.City, orderDate = order.OrderDate, confirmDate = order.ConfirmDate, deliveryDate = order.DeliveryDate, total = order.Total, status = order.Status, paymentStatus = order.DeliveryDate.HasValue ? (int)PaymentStatus.Paid : (int)PaymentStatus.NotYet, deliveryAddress = order.DeliverAddress, recipientName = sendAddress.RecipientName, recipientPhoneNumber = sendAddress.RecipientPhoneNumber, cartItemDTOList = cartItemDTOList // cartItemDTOList = orderItems.Select(c => new ClientOrder_CartItemDTO // { // stockId = c.StockId, // shoesId = c.Stock.ShoesId, // name = c.Stock.Shoes.Name, // sizeName = c.Stock.Size.Name, // quantity = c.Amount, // price = c.Total, // image = c.Stock.Shoes.ShoesImages.FirstOrDefault().ImagePath // }).ToArray().ToList() }; listResults.Add(responseDTO); } return(Ok(ResponseDTO.Ok(listResults))); }
public async Task <IActionResult> ClientProcessOrder([FromQuery(Name = "addressId")] int addressId) { // Get customer var customer = GetCustomer(); if (customer == null) { return(BadRequest(ResponseDTO.BadRequest("Invalid customer's username."))); } // Check addressId var sendAddress = customer.Addresses.FirstOrDefault(o => o.Id == addressId); if (sendAddress == null || string.IsNullOrEmpty(sendAddress.RecipientName) || string.IsNullOrEmpty(sendAddress.RecipientPhoneNumber) ) { return(BadRequest(ResponseDTO.BadRequest($"Invalid address for current customer: {customer.Username}."))); } // Check cart var cartItems = customer.Cart.CartItems; if (customer.Cart.CartItems.Count == 0) { return(BadRequest(ResponseDTO.BadRequest($"No items in cart for current customer: {customer.Username}"))); } // Convert cart items to order items // 1: Create order var newOrder = new Order() { OrderDate = DateTime.Now, Total = 0, Status = (int)OrderStatus.Waiting, DeliverAddress = sendAddress.ToString(), ConfirmDate = null, CancelDate = null, BeginDelivery = null, DeliveryDate = null, Note = "", RecipientName = sendAddress.RecipientName, RecipientPhoneNumber = sendAddress.RecipientPhoneNumber, CustomerId = customer.Id, OrderItems = new List <OrderItem>(), AddressId = addressId }; newOrder = await _repository.Add(newOrder); // 2: Create order items var orderItems = new List <OrderItem>(); float orderTotal = 0; foreach (var ci in cartItems) { var item = new OrderItem() { Amount = ci.Amount, PricePerUnit = ci.Stock.Shoes.Price, OrderId = newOrder.Id, StockId = ci.StockId, Total = 0 }; var priceWithSale = item.PricePerUnit; var productSale = await _context.SaleProducts .Include(c => c.Sale) .FirstOrDefaultAsync(c => c.Shoes.Id == ci.Stock.Shoes.Id); if (productSale != null && productSale.Sale.Status != 0) { var sale = productSale.Sale; priceWithSale -= sale.SaleType == 1 ? priceWithSale * (float)((float)sale.Amount / 100.0) : sale.Amount; } item.Total = item.Amount * priceWithSale; orderTotal += item.Total; // Update stock var stock = _context.Stocks.FirstOrDefault(c => c.Id == item.StockId); if (stock != null) { // TODO: Check stock.Instock -= item.Amount; } // Update cartItems in database _context.CartItems.Remove(ci); orderItems.Add(item); } newOrder.OrderItems = orderItems; newOrder.Total = orderTotal; await _context.SaveChangesAsync(); // Response var responseDTO = new ClientOrderResponseDTO() { id = newOrder.Id, customerID = customer.Id, saleID = 0, city = sendAddress.City, orderDate = newOrder.OrderDate, confirmDate = newOrder.ConfirmDate, deliveryDate = newOrder.DeliveryDate, total = newOrder.Total, status = newOrder.Status, paymentStatus = newOrder.DeliveryDate.HasValue ? (int)PaymentStatus.Paid : (int)PaymentStatus.NotYet, deliveryAddress = newOrder.DeliverAddress, recipientName = sendAddress.RecipientName, recipientPhoneNumber = sendAddress.RecipientPhoneNumber, cartItemDTOList = orderItems.Select(c => new ClientOrder_CartItemDTO { stockId = c.StockId, shoesId = c.Stock.ShoesId, name = c.Stock.Shoes.Name, sizeName = c.Stock.Size.Name, quantity = c.Amount, price = c.Total, image = c.Stock.Shoes.ShoesImages.FirstOrDefault().ImagePath }).ToList() }; return(Ok(ResponseDTO.Ok(responseDTO))); }
public async Task<IActionResult> ClientCartSync([FromBody] List<BodyCartDTO> syncList) { var customer = await GetCustomerFromSession(); if (customer == null) { return Ok(ResponseDTO.BadRequest()); } var cart = await _context.Carts.FirstOrDefaultAsync(o => o.CustomerId == customer.Id); if (cart == null) { // Create cart var newCart = new Cart { CustomerId = customer.Id }; _context.Carts.Add(newCart); await _context.SaveChangesAsync(); cart = newCart; } var cartItems = _context.CartItems.Where(o => o.CartId == cart.Id); _context.CartItems.RemoveRange(cartItems); // Filter syncList syncList = syncList.Where(o => o.quantity > 0).ToList(); // New list var newItems = new List<CartItem>(); foreach (var detail in syncList) { if (await _context.Stocks.AnyAsync(s => s.Id == detail.stockId)) { var item = new CartItem { CartId = cart.Id, Amount = detail.quantity, StockId = detail.stockId }; newItems.Add(item); } } _context.CartItems.AddRange(newItems); await _context.SaveChangesAsync(); // Load references newItems = _context.CartItems .Include(c => c.Stock).ThenInclude(o => o.Shoes).ThenInclude(o => o.ShoesImages) .Include(c => c.Stock).ThenInclude(o => o.Size) .Where(c => c.CartId == cart.Id) .ToList(); // Parse responses var items = new List<dynamic>(); foreach (var item in cartItems) { items.Add(new { stockId = item.Stock.Id, shoesId = item.Stock.ShoesId, name = item.Stock.Shoes.Name, sizeName = item.Stock.Size.Name, quantity = item.Amount, price = item.Stock.Shoes.Price, image = item.Stock.Shoes.ShoesImages.FirstOrDefault().ImagePath }); } return Ok(ResponseDTO.Ok(items, items.Count)); }
public async Task<IActionResult> ClientCartAddNewItem([FromBody] BodyCartDTO itemAdded) { var customer = await GetCustomerFromSession(); if (customer == null || itemAdded.quantity <= 0) { return Ok(ResponseDTO.BadRequest()); } Cart cart = await _context.Carts.FirstOrDefaultAsync(o => o.CustomerId == customer.Id); if (cart == null) { // Create cart var newCart = new Cart { CustomerId = customer.Id }; _context.Carts.Add(newCart); await _context.SaveChangesAsync(); cart = newCart; } // get stock var stock = _context.Stocks .Include(s => s.Shoes).ThenInclude(s => s.ShoesImages) .Include(s => s.Size) .FirstOrDefault(s => s.Id == itemAdded.stockId); if (stock == null) { return Ok(ResponseDTO.BadRequest("StockId is invalid.")); } var cartItems = _context.CartItems.Where(o => o.CartId == cart.Id); var existedItem = cartItems.FirstOrDefault(c => c.StockId == stock.Id); if (existedItem != null) { existedItem.Amount += itemAdded.quantity; _context.SaveChanges(); } else { // new item cart var itemCart = new CartItem { CartId = cart.Id, Amount = itemAdded.quantity, StockId = stock.Id }; _context.CartItems.Add(itemCart); _context.SaveChanges(); existedItem = itemCart; } var responseItem = new { stockId = stock.Id, shoesId = stock.ShoesId, name = stock.Shoes.Name, sizeName = stock.Size.Name, quantity = existedItem.Amount, price = stock.Shoes.Price, image = stock.Shoes.ShoesImages.FirstOrDefault().ImagePath }; return Ok(ResponseDTO.Ok(responseItem)); }