public async Task <IActionResult> AllOfficial(int selectedPage, int maxNumberPerItemsPage, string searchValue = "", string filterStatus = CoreConst.GetAllRecords, bool isSortAsce = false, string sortName = "Date", string disputeFilter = CoreConst.GetAllRecords) => await AllOrder(AppFunc.GetUserId(User), selectedPage, maxNumberPerItemsPage, searchValue, filterStatus, isSortAsce, sortName, disputeFilter).ConfigureAwait(false);
public async Task <IActionResult> DownloadData([FromBody] string currentPassword) { try { User user = await _DbContext.Users .Include(u => u.Role) .Include(u => u.RegistrationMethod) .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)).ConfigureAwait(false); if (user.RegistrationMethod.Type == RegistrationTypes.Application && !await _UserManager.CheckPasswordAsync(user, currentPassword).ConfigureAwait(false)) { CoreFunc.Error(ref ErrorsList, "Current Password is incorrect."); return(StatusCode(412, ErrorsList)); } List <Order> orders = await _DbContext.Orders .Include(o => o.User) .Include(o => o.OrderItems) .Include(o => o.Dispute) .ThenInclude(c => c.Messages) .Include(o => o.Payment) .Include(o => o.Coupon) .Where(u => u.User.Id == AppFunc.GetUserId(User)).ToListAsync().ConfigureAwait(false); List <Communication> questions = await _DbContext.Communications .Include(c => c.Messages) .Where(c => c.Email.ToUpper() == user.NormalizedEmail).ToListAsync().ConfigureAwait(false); List <Comment> comments = await _DbContext.Comments .Include(c => c.User) .Where(c => c.User.Id == user.Id).ToListAsync().ConfigureAwait(false); List <Address> addresses = await _DbContext.Addresses .Include(c => c.User) .Where(c => c.User.Id == user.Id).ToListAsync().ConfigureAwait(false); dynamic userData = new { userInfo = user, orders, questions, comments, addresses }; return(Ok(JsonConvert.SerializeObject(userData, Formatting.Indented, new JsonSerializerSettings { Converters = new List <JsonConverter> { new StringEnumConverter(), new DecimalFormatConverter() }, ContractResolver = new DynamicContractResolver("Id", "Password", "AccessClaim", "OrderLength", "HasOrder" , "DeliveryOption", "Order_Id", "captchaToken", "AddressId", "UserId", "ProductId", "ImagePath", "ExternalLinkedId") }))); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
[Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test public async Task <IActionResult> All() { try { return(Ok(await _DbContext.Addresses. Where(t => t.User.Id == AppFunc.GetUserId(User)).ToListAsync())); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> PostQuestion([FromBody] Communication newContact) { try { if (!ReCaptchaPassed(newContact.captchaToken)) { CoreFunc.Error(ref ErrorsList, "Captcha validation failed"); return(StatusCode(412, ErrorsList)); } if (string.IsNullOrWhiteSpace(newContact.Messages.FirstOrDefault().Body)) { CoreFunc.Error(ref ErrorsList, "Message is required."); return(StatusCode(412, ErrorsList)); } if (AppFunc.GetUserId(User) != 0) { var user = await _DbContext.Users.SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)); newContact.Email = user.Email; newContact.FullName = $"{user.FirstName} {user.Surname}"; } newContact.Status = true; newContact.Type = ContactType.Message; newContact.Messages[0].IsCustomer = true; ModelState.Clear(); TryValidateModel(newContact); if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } await _DbContext.Communications.AddAsync(newContact).ConfigureAwait(false); await _DbContext.SaveChangesAsync().ConfigureAwait(false); // await _EmailService.EmailConfirmationAsync(orderData).ConfigureAwait(false); return(Created("", $"Thank you for contacting us. We will contact you as soon as possible. ")); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Silence() { try { User user = new User(); bool isAuthenticated = false; if (_SignInManager.IsSignedIn(User)) { foreach (string policy in AppFunc.GetCurrentRequestPolicies(Request)) { AuthorizationResult authResult = await _AuthService.AuthorizeAsync(User, policy).ConfigureAwait(false); if (authResult.Succeeded) { user = await _DbContext.Users .Include(u => u.Role) .Include(u => u.RegistrationMethod) .FirstOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)) .ConfigureAwait(false); isAuthenticated = true; break; } } } SetAntiforgeryCookie(); bool isUserAllowedInMaintenance = false; Request.Headers.TryGetValue("Origin", out StringValues OriginValue); if ((user.Role != null && (user.Role.AccessClaim == AppConst.AccessClaims.Admin || user.Role.AccessClaim == AppConst.AccessClaims.Manager)) || AppConst.Settings.AppDomains.AdminApp.EqualCurrentCultureIgnoreCase(OriginValue)) { isUserAllowedInMaintenance = true; } return(Ok(new MultiResult <User, bool, bool, bool> (user, isAuthenticated, AppConst.Settings.MaintenanceModeStatus, isUserAllowedInMaintenance , CoreFunc.GetCustomAttributeTypedArgument(ControllerContext)))); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
[Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test public async Task <IActionResult> SetDefault([FromBody] int addressId) { try { List <Address> addresses = await _DbContext.Addresses.AsTracking() .Include(a => a.User) .ThenInclude(u => u.Role) .Include(a => a.User) .ThenInclude(u => u.RegistrationMethod) .Where(a => a.User.Id == AppFunc.GetUserId(User)).ToListAsync(); if (addresses.SingleOrDefault(a => a.Id == addressId) != null) { foreach (var address in addresses) { if (address.Id == addressId) { address.IsDefault = true; } else { address.IsDefault = false; } } } _DbContext.Addresses.UpdateRange(addresses); await _DbContext.SaveChangesAsync().ConfigureAwait(false); return(NoContent()); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
[Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test public async Task <IActionResult> Post([FromBody] Address newAddress) { try { //if (newAddress is null) // return checkObjectIsNull(newAddress); if (newAddress != null) { newAddress.User = await _DbContext.Users.AsTracking().Include(u => u.Role) .Include(u => u.RegistrationMethod) .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)); } ModelState.Clear(); if (!TryValidateModel(newAddress)) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } if (!await _DbContext.Addresses.AnyAsync(a => a.User.Id == AppFunc.GetUserId(User))) { newAddress.IsDefault = true; } await _DbContext.Addresses.AddAsync(newAddress).ConfigureAwait(false); await _DbContext.SaveChangesAsync().ConfigureAwait(false); return(Created("Success", newAddress)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Get(int productId, int selectedPage = 1, int maxItemsPerPage = 5) { try { if (selectedPage == 0) { selectedPage = 1; } if (maxItemsPerPage == 0) { maxItemsPerPage = 5; } int totalCount = await _DbContext.Comments .CountAsync(c => c.Product.Id == productId) .ConfigureAwait(false); List <Comment> list = await _DbContext.Comments .Include(c => c.User) .Include(c => c.Product) .Where(c => c.Product.Id == productId) .OrderBy(c => c.Date) .Skip((selectedPage - 1) * maxItemsPerPage) .Take(maxItemsPerPage) .ToListAsync() .ConfigureAwait(false); Comment selectComment = null; if (AppFunc.GetUserId(User) != 0) { User user = await _DbContext.Users.Include(u => u.Orders) .ThenInclude(o => o.OrderItems).SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)).ConfigureAwait(false); if (user.Orders.Any(o => o.Status == OrderStatusType.Delivered && o.OrderItems.Any(oi => oi.ProductId == productId))) { selectComment = await _DbContext.Comments.Include(c => c.User) .SingleOrDefaultAsync(c => c.Product.Id == productId && c.User.Id == AppFunc.GetUserId(User)); if (selectComment == null) { selectComment = new Comment() { Id = 0, Product = await _DbContext.Products.SingleOrDefaultAsync(p => p.Id == productId), User = user } } ; } } return(Ok(new MultiResult <List <Comment>, Comment, int>(list, selectComment, totalCount, CoreFunc.GetCustomAttributeTypedArgument(ControllerContext)))); } catch (Exception ex) { /// in the case any exceptions return the following error CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Put([FromBody] Comment modifiedComment) { try { ModelState.Clear(); TryValidateModel(modifiedComment); foreach (var key in ModelState.Keys) { if (key.StartsWith("User") || key.StartsWith("Product")) { ModelState.Remove(key); } } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } Comment comment = await _DbContext.Comments .Include(c => c.User) .SingleOrDefaultAsync(c => c.Id == modifiedComment.Id && c.User.Id == AppFunc.GetUserId(User)).ConfigureAwait(false); if (comment == null) { CoreFunc.Error(ref ErrorsList, "Comment not exist."); return(StatusCode(412, ErrorsList)); } comment.Description = modifiedComment.Description; comment.Rate = modifiedComment.Rate; await comment.CencoredDescription(); _DbContext.Comments.Update(comment); await _DbContext.SaveChangesAsync().ConfigureAwait(false); return(Ok(comment)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Put([FromBody] Address modifiedAddress) { try { if (modifiedAddress != null) { modifiedAddress.User = await _DbContext.Users.AsTracking().Include(u => u.Role) .Include(u => u.RegistrationMethod).SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)); } ModelState.Clear(); if (!TryValidateModel(modifiedAddress)) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } _DbContext.Addresses.Update(modifiedAddress); await _DbContext.SaveChangesAsync().ConfigureAwait(false); return(Ok(modifiedAddress)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> PostDispute([FromBody] Communication newDispute) { try { if (string.IsNullOrWhiteSpace(newDispute.Messages.FirstOrDefault().Body)) { CoreFunc.Error(ref ErrorsList, "Message is required."); return(StatusCode(412, ErrorsList)); } if (!string.IsNullOrEmpty(newDispute.Order_Id) && (await _DbContext.Orders.SingleOrDefaultAsync(o => o.Id == newDispute.Order_Id) == null)) { CoreFunc.Error(ref ErrorsList, "Cannot find your order."); return(UnprocessableEntity(ErrorsList)); } User user = await _DbContext.Users.SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)); newDispute.Email = user.Email; newDispute.FullName = $"{user.FirstName} {user.Surname}"; newDispute.Status = true; newDispute.Order = await _DbContext.Orders .Include(o => o.Payment) .Include(o => o.User) .SingleOrDefaultAsync(o => o.Id == newDispute.Order_Id); newDispute.Type = ContactType.Dispute; newDispute.Messages[0].IsCustomer = true; TryValidateModel(newDispute); foreach (var key in ModelState.Keys) { if (key.StartsWith("User") || key.StartsWith("Order") || key.StartsWith("OrderItem")) { ModelState.Remove(key); } } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } await _DbContext.Communications.AddAsync(newDispute).ConfigureAwait(false); _DbContext.Entry(newDispute.Order).State = EntityState.Unchanged; _DbContext.Entry(newDispute.Order.User).State = EntityState.Unchanged; _DbContext.Entry(newDispute.Order.Payment).State = EntityState.Unchanged; await _DbContext.SaveChangesAsync().ConfigureAwait(false); await _EmailService.OrderDisputeAsync(newDispute.Order, newDispute).ConfigureAwait(false); return(Created("", newDispute)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> GetDispute(string disputeKey) { try { Communication dispute = await _DbContext.Communications .Include(c => c.Order) .ThenInclude(o => o.User) .Include(c => c.Order) .ThenInclude(o => o.OrderItems) .Include(c => c.Messages) .SingleOrDefaultAsync(c => c.Type == ContactType.Dispute && c.Id == disputeKey && c.Order.User.Id == AppFunc.GetUserId(User)) .ConfigureAwait(false); if (dispute is null) { CoreFunc.Error(ref ErrorsList, "Dispute Not Found."); return(StatusCode(412, ErrorsList)); } return(Ok(dispute)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Post([FromBody] Comment newComment) { try { User user = await _DbContext.Users .Include(u => u.Orders) .ThenInclude(o => o.OrderItems) .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)) .ConfigureAwait(false); if (user.Orders.Any(o => o.Status == OrderStatusType.Delivered && o.OrderItems.Any(oi => oi.ProductId == newComment.Product.Id))) { Comment selectComment = await _DbContext.Comments .Include(c => c.User) .SingleOrDefaultAsync(c => c.Product.Id == newComment.Product.Id && c.User.Id == AppFunc.GetUserId(User)); if (selectComment != null) { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { message = $"Try to add duplicate comment.", newContact = newComment }, User); CoreFunc.Error(ref ErrorsList, "You Can't add review for this product.Try again or Contact Admin."); return(StatusCode(412, ErrorsList)); } } else { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { message = $"Try to add comment without order.", newContact = newComment }, User); CoreFunc.Error(ref ErrorsList, "You Can't add review for this product.Try again or Contact Admin."); return(StatusCode(412, ErrorsList)); } newComment.User = user; newComment.User.Orders = null; ModelState.Clear(); TryValidateModel(newComment); foreach (var key in ModelState.Keys) { if (key.StartsWith("User") || key.StartsWith("Product")) { ModelState.Remove(key); } } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } await _DbContext.Comments.AddAsync(newComment).ConfigureAwait(false); _DbContext.Entry(newComment.User).State = EntityState.Unchanged; _DbContext.Entry(newComment.Product).State = EntityState.Unchanged; await _DbContext.SaveChangesAsync().ConfigureAwait(false); return(Created("", newComment)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
private async Task <Order> CheckOrderDetail(Order orderData) { Address currentAddress = await _DbContext.Addresses.Include(a => a.User) .SingleOrDefaultAsync(a => a.Id == orderData.AddressId && a.User.Id == AppFunc.GetUserId(User)); if (currentAddress != null) { orderData.UpdateAddress(currentAddress); } orderData.DeliveryOption = await _DbContext.DeliveryOptions.AsTracking() .SingleOrDefaultAsync(a => a.Id == orderData.DeliveryOption.Id) .ConfigureAwait(false); ModelState.Clear(); TryValidateModel(orderData); foreach (var key in ModelState.Keys) { if ( (key.StartsWith("Payment") || key.StartsWith("Coupon") || key.StartsWith("OrderItems") || key.StartsWith("User")) || (AppFunc.GetUserId(User) == 0 && currentAddress == null && (key.StartsWith("Name") || key.StartsWith("City") || key.StartsWith("Postcode") || key.StartsWith("FirstLine"))) ) { ModelState.Remove(key); } } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(null); } List <Product> productList = await _DbContext.Products.AsTracking() .Include(p => p.Category) .Where(p => orderData.OrderItems.Select(t => t.ProductId).ToList().Contains(p.Id)) .ToListAsync() .ConfigureAwait(false); Product originalProduct; List <OrderItem> CheckedOrderItems = new List <OrderItem>(); orderData.TotalItemPrice = 0; foreach (var orderItem in orderData.OrderItems) { originalProduct = productList.SingleOrDefault(t => t.Id == orderItem.ProductId); if (originalProduct == null || !originalProduct.Status) { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { message = $"Product ({orderItem.Name}) Unavailable.", order = orderData }, User); CoreFunc.Error(ref ErrorsList, $"Product ({orderItem.Name}) Unavailable."); return(null); } if (orderItem.Price != originalProduct.Price) { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { message = "Product Price mismatch.", order = orderData }, User); CoreFunc.Error(ref ErrorsList, "Product Price mismatch"); return(null); } if (orderItem.Quantity > originalProduct.StockQuantity) { CoreFunc.Error(ref ErrorsList, $"Product '{orderItem.Name}' is out of stock"); return(null); } if (orderItem.Quantity == 0) { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { message = "Product quantity can't be zero.", order = orderData }, User); CoreFunc.Error(ref ErrorsList, $"Product quantity can't be zero."); return(null); } orderData.TotalItemPrice += (orderItem.Quantity * originalProduct.Price ?? 0); originalProduct.StockQuantity -= orderItem.Quantity; CheckedOrderItems.Add(new OrderItem(originalProduct, orderItem.Quantity)); } if (orderData.DeliveryOption.Price == 0 && orderData.DeliveryOption.MinimumOrderTotal > orderData.TotalItemPrice && orderData.DeliveryOption.IsPremitive) { CoreFunc.Error(ref ErrorsList, $"You do not meet the free delivery requirement of £{orderData.DeliveryOption.MinimumOrderTotal}"); return(null); } //Check coupon if (orderData.Coupon != null && !string.IsNullOrEmpty(orderData.Coupon.Code)) { Coupon currentCoupon = await _DbContext.Coupons.AsTracking() .SingleOrDefaultAsync(c => c.Code == orderData.Coupon.Code) .ConfigureAwait(false); if (currentCoupon == null || currentCoupon.MaxUseQuantity < 1 || currentCoupon.ExpiryDate < DateTime.UtcNow || orderData.TotalItemPrice < currentCoupon.MinimumOrderPrice) { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { message = "Coupon Invalid", order = orderData }, User); CoreFunc.Error(ref ErrorsList, $"'{orderData.Coupon.Code}' is invalid"); return(null); } else { orderData.Coupon = currentCoupon; } } orderData.CalculateTotalPrice(); return(orderData); }