diff --git a/Controllers/Controllers/AccountController.cs b/Controllers/Controllers/AccountController.cs new file mode 100644 index 0000000..98f618b --- /dev/null +++ b/Controllers/Controllers/AccountController.cs @@ -0,0 +1,212 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Project.Models; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + + //Pasar en los redirect to Login la razon por la que tiene que + public class AccountController : Controller + { + private readonly UserManager userManager; + private readonly SignInManager signInManager; + private readonly IShoppingCartRepository shoppingCartRepository; + + public ILogger logger { get; } + + public AccountController(UserManager userManager, SignInManager signInManager,ILogger logger, IShoppingCartRepository shoppingCartRepository) + { + this.userManager = userManager; + this.signInManager = signInManager; + this.logger = logger; + this.shoppingCartRepository = shoppingCartRepository; + } + + public ViewResult AccessDenied() + { + return View(); + } + + [AllowAnonymous] + public async Task ConfirmEmail(string userId, string token) + { + if (userId == null || token == null) + return RedirectToAction("Index", "Home"); + + var user = await userManager.FindByIdAsync(userId); + if (user == null) + { + ViewBag.UserName = $"The user ID {userId} is invalid"; + return View("Not found"); + } + + var result = await userManager.ConfirmEmailAsync(user, token); + + if (result.Succeeded) + { + ViewBag.Text = "You have been successfully registered"; + return View(); + } + ViewBag.Text = "Email cannot be confirmed"; + return View(); + } + + [HttpGet] + [AllowAnonymous] + public ViewResult Register() + { + return View(); + } + + [HttpPost] + [AllowAnonymous] + public async Task Register(RegisterViewModel model) + { + if (ModelState.IsValid) + { + var u = await userManager.FindByNameAsync(model.UserName); + if (!(u is null)) + { + ViewBag.UserName = $"Username {model.UserName} already in use"; + return View(); + } + u = await userManager.FindByEmailAsync(model.Email); + if (!(u is null)) + { + ViewBag.Email = $"Email {model.Email} already in use"; + return View(); + } + + ShoppingCart shoppingCart = new ShoppingCart(); + shoppingCartRepository.AddEntity(shoppingCart); + + var user = new User { + UserName = model.UserName, + Email = model.Email, + Name = model.Name, + LastName = model.LastName, + Info = model.Info, + ShoppingCartId = shoppingCart.Id, + Active = true + }; + var result = await userManager.CreateAsync(user, model.Password); + + if (result.Succeeded) + { + /*Para el login con email + var token = await userManager.GenerateEmailConfirmationTokenAsync(user); + var confirmationLink = Url.Action("ConfirmEmail", "Account", + new { userId = user.Id, token = token }, Request.Scheme); + logger.Log(LogLevel.Warning, confirmationLink); + return View("RegistrationSuccessfulView"); + //*/ + + await signInManager.SignInAsync(user, isPersistent: false); + return RedirectToAction("index", "home"); + } + else + { + foreach (var error in result.Errors) + { + ModelState.AddModelError("", errorMessage: error.Description); + } + } + } + return View(model); + } + [HttpGet] + public async Task Logout_Get() + { + await signInManager.SignOutAsync(); + return RedirectToAction("index", "home"); + } + + public async Task Logout() + { + await signInManager.SignOutAsync(); + return RedirectToAction("index", "home"); + } + + [HttpGet] + [AllowAnonymous] + public ViewResult Login() + { + return View(); + } + + [HttpPost] + [AllowAnonymous] + public async Task Login(LoginViewModel model, string ReturnUrl) + { + if (ModelState.IsValid) + { + //var x = await userManager.FindByNameAsync(model.UserName); + //Arreglar para hacer el RememberMe + var result = await signInManager.PasswordSignInAsync(model.UserName, + model.Password, true, false); + if (result.Succeeded) + { + if (string.IsNullOrEmpty(ReturnUrl)) + { + return RedirectToAction("Index", "Home"); + } + return Redirect(ReturnUrl); + } + ModelState.AddModelError("", errorMessage: "Invalid Login Attempt"); + } + return View(model); + } + + [HttpPost] + [HttpGet] + public async Task IsUserNameInUsed(string username) + { + var user = await userManager.FindByNameAsync(username); + if (user is null) + { + return Json(true); + } + else + { + return Json($"Username {username} already in use"); + } + } + + public IActionResult ChangePassword() + { + return View(); + } + + [HttpPost] + public async Task ChangePassword(ChangePasswordViewModel model) + { + if(ModelState.IsValid) + { + var user = await userManager.GetUserAsync(User); + if (user == null) + return RedirectToAction("Login"); + + var result = await userManager.ChangePasswordAsync + (user, model.CurrentPassword, model.NewPassword); + + if(!result.Succeeded) + { + foreach(var error in result.Errors) + ModelState.AddModelError(string.Empty, error.Description); + return View(); + } + + await signInManager.RefreshSignInAsync(user); + return View("ChangePasswordConfirmation"); + } + return View(model); + } + } +} diff --git a/Controllers/Controllers/AdministrationController.cs b/Controllers/Controllers/AdministrationController.cs new file mode 100644 index 0000000..76a8c0b --- /dev/null +++ b/Controllers/Controllers/AdministrationController.cs @@ -0,0 +1,443 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Project.Models; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + //[Authorize(Policy = "AdminRolePolicy")] + [AllowAnonymous] + public class AdministrationController : Controller + { + private readonly RoleManager roleManager; + private readonly UserManager userManager; + private readonly IUserRepository repository; + + public AdministrationController(RoleManager roleManager, UserManager userManager, IUserRepository repository) + { + this.roleManager = roleManager; + this.userManager = userManager; + this.repository = repository; + } + + [HttpGet] + [Authorize(Policy = "ManageRolesAndClaimsPolicy")] + public async Task ManageUserRoles(string Id) + { + ViewBag.userId = Id; + + var user = await userManager.FindByIdAsync(Id); + + if(user == null) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = $"User id {Id} not found"; + mo.ErrorMessage = $"Introduce a new user"; + return View("Error", mo); + } + + var model = new List(); + foreach(var role in roleManager.Roles) + { + var userRolesViewModel = new UserRolesViewModel + { + RoleId = role.Id, + RoleName = role.Name + }; + + if (await userManager.IsInRoleAsync(user, role.Name)) + userRolesViewModel.IsSelected = true; + else + userRolesViewModel.IsSelected = false; + model.Add(userRolesViewModel); + } + return View(model); + } + + [HttpPost] + [Authorize(Policy = "ManageRolesAndClaimsPolicy")] + public async Task ManageUserRoles(List model, string Id) + { + var user = await userManager.FindByIdAsync(Id); + + if (user == null) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = $"User id {Id} not found"; + mo.ErrorMessage = $"Introduce a new user"; + return View("Error", mo); + } + + var roles = await userManager.GetRolesAsync(user); + var result = await userManager.RemoveFromRolesAsync(user, roles); + + if(!result.Succeeded) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = ""; + mo.ErrorMessage = "Cannot remove user existing roles"; + return View("Error", mo); + } + + result = await userManager.AddToRolesAsync(user, + model.Where(x => x.IsSelected).Select(y => y.RoleName)); + + if (!result.Succeeded) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = ""; + mo.ErrorMessage = "Cannot add roles to user"; + return View("Error", mo); + } + + return RedirectToAction("EditUser", new { Id = Id }); + } + + [HttpGet] + [Authorize(Policy = "ManageRolesAndClaimsPolicy")] + public async Task ManageUserClaims(string Id) + { + ViewBag.userId = Id; + + var user = await userManager.FindByIdAsync(Id); + + if (user == null) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = $"User id {Id} not found"; + mo.ErrorMessage = $"Introduce a new user"; + return View("Error", mo); + } + + var existingUserClaims = await userManager.GetClaimsAsync(user); + var model = new List(); + + foreach(Claim claim in ClaimsStore.AllClaims) + { + UserClaimsViewModel userClaim = new UserClaimsViewModel + { + ClaimType = claim.Type + }; + if (existingUserClaims.Any(x => x.Type == claim.Type && x.Value == "true")) + userClaim.IsSelected = true; + + model.Add(userClaim); + } + return View(model); + } + + [HttpPost] + [Authorize(Policy = "ManageRolesAndClaimsPolicy")] + public async Task ManageUserClaims(List model, string Id) + { + var user = await userManager.FindByIdAsync(Id); + + if (user == null) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = $"User id {Id} not found"; + mo.ErrorMessage = $"Introduce a new user"; + return View("Error", mo); + } + + var claims = await userManager.GetClaimsAsync(user); + var result = await userManager.RemoveClaimsAsync(user, claims); + + if (!result.Succeeded) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = ""; + mo.ErrorMessage = "Cannot remove user existing claims"; + return View("Error", mo); + } + + result = await userManager.AddClaimsAsync(user, + model.Select(x => new Claim(x.ClaimType, x.IsSelected ? "true" : "false"))); + + if (!result.Succeeded) + { + ErrorViewModel mo = new ErrorViewModel(); + mo.ErrorTitle = ""; + mo.ErrorMessage = "Cannot add selected claims to user"; + return View("Error", mo); + } + return RedirectToAction("EditUser", new { Id = Id }); + } + + [HttpGet] + [Authorize(Policy = "CreateRolePolicy")] + public IActionResult CreateRole() + { + return View(); + } + + [HttpPost] + [Authorize(Policy = "DeleteRolePolicy")] + public async Task DeleteRole(string id) + { + var role = await roleManager.FindByIdAsync(id); + if (role is null) + return RedirectToAction("AllRoles "); + + try + { + var result = await roleManager.DeleteAsync(role); + if (result.Succeeded) + { + return RedirectToAction("AllRoles"); + } + foreach (var e in result.Errors) + { + ModelState.AddModelError("", e.Description); + } + return RedirectToAction("AllRoles"); + } + catch (DbUpdateException) + { + ErrorViewModel model = new ErrorViewModel(); + model.ErrorTitle = $"{role.Name} is in use"; + model.ErrorMessage = $"There are users using this role, you should delete them first"; + return View("Error", model); + } + } + + [HttpPost] + [Authorize(Policy = "CreateRolePolicy")] + public async Task CreateRole(CreateRoleViewModel model) + { + if (ModelState.IsValid) + { + var r = await roleManager.FindByNameAsync(model.RoleName); + + if (r is null) + { + ViewBag.RoleName = $"Role name {model.RoleName} is already in use"; + } + + IdentityRole role = new IdentityRole + { + Name = model.RoleName + }; + + IdentityResult result = await roleManager.CreateAsync(role); + + if (result.Succeeded) + { + return RedirectToAction("AllRoles", "Administration"); + } + + foreach (var error in result.Errors) + { + ModelState.AddModelError("", error.Description); + } + } + return View(); + } + + public IActionResult AllRoles() + { + var roles = roleManager.Roles; + return View(roles); + } + + [HttpGet] + [Authorize(Policy = "EditRolePolicy")] + public async Task EditRole(string id) + { + var role = await roleManager.FindByIdAsync(id); + if (role is null) + return RedirectToAction("Index", "Home"); + + var model = new EditRoleViewModel + { + Id = role.Id, + RoleName = role.Name + }; + + foreach (var user in userManager.Users) + { + if (await userManager.IsInRoleAsync(user, role.Name)) + { + model.Users.Add(user.UserName); + } + } + return View(model); + } + + [HttpPost] + [Authorize(Policy = "EditRolePolicy")] + public async Task EditRole(EditRoleViewModel model) + { + var role = await roleManager.FindByIdAsync(model.Id); + if (role is null) + return RedirectToAction("Index", "Home"); + role.Name = model.RoleName; + var result = await roleManager.UpdateAsync(role); + + if (!result.Succeeded) + { + foreach (var error in result.Errors) + ModelState.AddModelError("", error.Description); + return View(); + } + return RedirectToAction("AllRoles", "Administration"); + } + + [HttpGet] + public async Task EditUsersInRole(string id) + { + ViewBag.RoleId = id; + + var role = await roleManager.FindByIdAsync(id); + + if (role is null) + //Poner pagina o mesnsaje para mostrar los errores + return RedirectToAction("AllRoles", "Administration"); + + var model = new List(); + + foreach (var user in userManager.Users) + { + if (!user.Active) continue; + var userrole = new UserRoleViewModel + { + UserId = user.Id, + UserName = user.UserName + }; + + if (await userManager.IsInRoleAsync(user, role.Name)) + userrole.IsSelected = true; + else + userrole.IsSelected = false; + model.Add(userrole); + } + return View(model); + } + + [HttpPost] + public async Task EditUsersInRole(List model, string id) + { + var role = await roleManager.FindByIdAsync(id); + + if (role is null) + //Poner pagina o mesnsaje para mostrar los errores + return RedirectToAction("AllRoles", "Administration"); + + for (int i = 0; i < model.Count; i++) + { + var user = await userManager.FindByIdAsync(model[i].UserId); + IdentityResult result = null; + + if (model[i].IsSelected && !(await userManager.IsInRoleAsync(user, role.Name))) + { + result = await userManager.AddToRoleAsync(user, role.Name); + } + else if (!model[i].IsSelected && await userManager.IsInRoleAsync(user, role.Name)) + { + result = await userManager.RemoveFromRoleAsync(user, role.Name); + } + else + continue; + + if (result.Succeeded && i == model.Count - 1) + { + return RedirectToAction("EditRole", new { Id = id }); + } + } + return RedirectToAction("EditRole", new { Id = id }); + } + + [HttpGet] + public IActionResult Users() + { + var users = userManager.Users; + return View(users); + } + + [HttpGet] + public async Task EditUser(string id) + { + var user = await userManager.FindByIdAsync(id); + if(user is null) + return RedirectToAction("Users"); + + var userClaims = await userManager.GetClaimsAsync(user); + var userRoles = await userManager.GetRolesAsync(user); + + + var model = new EditUserViewModel + { + + Id = user.Id, + Name = user.Name, + LastName = user.LastName, + Email = user.Email, + Claims = userClaims.Select(c => c.Type + ": " + c.Value).ToList(), + Roles = userRoles.ToList(), + City = user.City, + Info = user.Info, + UserName = user.UserName, + Telephone = user.PhoneNumber + }; + + return View(model); + + } + + + [HttpPost] + public async Task EditUser(EditUserViewModel model) + { + var user = await userManager.FindByIdAsync(model.Id); + if (user is null) + return RedirectToAction("Users"); + + user.Email = model.Email; + user.UserName = model.UserName; + user.Name = model.Name; + user.LastName = model.LastName; + user.PhoneNumber = model.Telephone; + user.City = model.City; + + var result = await userManager.UpdateAsync(user); + if (result.Succeeded) + { + return RedirectToAction("Users"); + } + foreach(var e in result.Errors) + { + ModelState.AddModelError("", e.Description); + } + return View(model); + } + + [HttpPost] + public async Task DeleteUser(string id) + { + var user = await userManager.FindByIdAsync(id); + if (user is null) + return RedirectToAction("Users"); + + repository.Delete(id); + + //var result = await userManager.Users.First(x => x.Id == Id) + //if (result.Succeeded) + //{ + // return RedirectToAction("Users"); + //} + //foreach (var e in result.Errors) + //{ + // ModelState.AddModelError("", e.Description); + //} + return RedirectToAction("Users"); + } + + } +} diff --git a/Controllers/Controllers/AuctionController.cs b/Controllers/Controllers/AuctionController.cs new file mode 100644 index 0000000..763491f --- /dev/null +++ b/Controllers/Controllers/AuctionController.cs @@ -0,0 +1,326 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Rendering; +using Project.Models; +using Project.Models.Repository.Interfaces; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class AuctionController : Controller + { + public readonly IAuctionRepository repository; + private readonly IProductRepository productRepository; + private readonly IUserRepository userRepository; + private readonly IUserInAuctionRepository userInAuctionRepository; + private readonly INotificationRepository notificationRepository; + private readonly IBankAccountRepository bankAccountRepository; + private List selectListItemsCategory; + private List selectListItemsFilters; + + public AuctionController(IAuctionRepository repository, IProductRepository productRepository, IUserRepository userRepository, + IUserInAuctionRepository userInAuctionRepository, INotificationRepository notificationRepository,IBankAccountRepository bankAccountRepository) + { + this.repository = repository; + this.productRepository = productRepository; + this.userRepository = userRepository; + this.userInAuctionRepository = userInAuctionRepository; + this.notificationRepository = notificationRepository; + this.bankAccountRepository = bankAccountRepository; + SelectList(); + + } + + private void SelectList() + { + int count = 0; + string[] array = { "None", "Price Down", "Price Up", "Rating Down", "Rating Up", "Name Down", "Name Up" }; + selectListItemsFilters = new List(); + selectListItemsCategory = new List(); + + foreach (var item in Enum.GetNames(typeof(Filters))) + { + selectListItemsFilters.Add(new SelectListItem(array[count], item)); + ++count; + } + foreach (var item in Enum.GetNames(typeof(Category))) + { + selectListItemsCategory.Add(new SelectListItem(item, item)); + } + } + + [AllowAnonymous] + public ViewResult All() + { + var list = repository.GetAll().Where(x => x.Active); + var to_update = new List(); + + List usersToPay = new List(); + List moneyToPay = new List(); + + foreach (var item in list) + { + + item.Product = productRepository.GetById(item.ProductId); + if (item.Date <= DateTime.Now && item.Active) + { + item.Active = false; + if (item.ActualUser == null) continue; + to_update.Add(item); + + //Money Transfer + usersToPay.Add(bankAccountRepository.GetByUserId(item.User_Sale_ID).First()); + moneyToPay.Add(item.Ammount * (float)item.ActualPrice); + usersToPay.Add(bankAccountRepository.GetByTitular("Shoppify")); + moneyToPay.Add((moneyToPay.Sum() * 2) / 100); + var temp = bankAccountRepository.GetByUserId(item.ActualUser); + if (temp.Count() == 0) continue; + var userpay = bankAccountRepository.GetByUserId(item.ActualUser).First(); + if (!Bank.Deposit(userpay, usersToPay, moneyToPay)) + { + var productname = productRepository.GetById(item.ProductId).Name; + Notification notification = new Notification(NotificationType.BadAuctionSale, item.User_Sale_ID, productname); + Notification notification1 = new Notification(NotificationType.BadAuctionBuy, item.ActualUser, productname); + notificationRepository.AddEntity(notification); + notificationRepository.AddEntity(notification1); + } + usersToPay.Clear(); + moneyToPay.Clear(); + } + + } + + foreach (var item in to_update) + { + repository.Update(item); + } + AllAuctionViewModel viewModel = new AllAuctionViewModel() + { + Auctions = list, + FirstPage = 1, + Page = 1, + selectListCategory = selectListItemsCategory, + selectListFilter = selectListItemsFilters + }; + return View(viewModel); + } + + [HttpPost] + public ViewResult All(AllAuctionViewModel viewModel) + { + + var page = viewModel.Page; + if (page <= 0) page = 1; + if (page % 3 == 0) + viewModel.FirstPage = page - 2; + else + viewModel.FirstPage = page / 3 > 0 ? page / 3 * 3 + 1 : 1; + if (viewModel.FirstPage <= 0) viewModel.FirstPage = 1; + + + var s = viewModel.Filter; + var categ = viewModel.Category; + int count = 0; + string[] array = { "None", "Price Down", "Price Up", "Rating Down", "Rating Up", "Name Down", "Name Up" }; + + viewModel.selectListFilter = new List(); + viewModel.selectListCategory = new List(); + + foreach (var item in Enum.GetNames(typeof(Filters))) + { + if (s.ToString() == item) + { + viewModel.selectListFilter.Add(new SelectListItem(array[count], item, true)); + } + else + { + viewModel.selectListFilter.Add(new SelectListItem(array[count], item)); + } + ++count; + } + + foreach (var item in Enum.GetNames(typeof(Category))) + { + if (categ.ToString() == item) + { + viewModel.selectListCategory.Add(new SelectListItem(item, item, true)); + } + else + { + viewModel.selectListCategory.Add(new SelectListItem(item, item)); + } + } + switch (s) + { + case Filters.None: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active & (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).ToList(); + break; + case Filters.PriceDown: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active & (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).OrderByDescending(x => x.ActualPrice).ToList(); + break; + case Filters.PriceUp: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active & (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).OrderBy(x => x.ActualPrice).ToList(); + break; + case Filters.RatingDown: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active & (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).OrderByDescending(x => productRepository.GetById(x.ProductId).Rating).ToList(); + break; + case Filters.RatingUp: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active & (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).OrderBy(x => productRepository.GetById(x.ProductId).Rating).ToList(); + break; + case Filters.NameDown: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active & (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).OrderByDescending(x => productRepository.GetById(x.ProductId).Name).ToList(); + break; + case Filters.NameUp: + viewModel.Auctions = repository.GetAll().Skip((page - 1) * 9).Where(x => x.Active && (categ == Category.All + | categ == productRepository.GetById(x.ProductId).Category)).OrderBy(x => productRepository.GetById(x.ProductId).Name).ToList(); + break; + default: + break; + } + return View(viewModel); + } + + [HttpGet] + public ViewResult Add(long id) + { + Auction auction = new Auction() + { + Product = productRepository.GetById(id) + }; + return View(auction); + } + + [HttpPost] + public IActionResult Add(Auction auction) + { + auction.Id = 0; + auction.Product = productRepository.GetById(auction.ProductId); + if (!ModelState.IsValid) + { + + if (auction.Ammount == 0 || auction.Ammount > auction.Product.Ammount) ViewBag.AmmountError = "The product ammount for the auction is not valid."; + if (auction.InitialPrice.Equals(0) ) ViewBag.PriceError = "The product initial price is not valid."; + return View(auction); + } + + if (auction.Ammount > auction.Product.Ammount) + { + ViewBag.AmmountError = "The product ammount for the auction is not valid."; + return View(auction); + } + + auction.InitialTime = DateTime.Now; + auction.User_Sale = userRepository.GetByUsername(User.Identity.Name); + auction.ProductId = auction.Product.Id; + auction.ActualPrice = auction.InitialPrice; + auction.Active = true; + repository.AddEntity(auction); + return RedirectToAction("All"); + } + public IActionResult Delete(long Id) + { + repository.Delete(Id); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long Id) + { + var item = repository.GetById(Id); + return View(item); + } + [HttpPost] + public IActionResult Update(Auction item) + { + repository.Update(item); + return RedirectToAction("All"); + } + + public IActionResult Auction(long id) + { + User user = userRepository.GetByUsername(User.Identity.Name); + Auction auction = repository.GetAuction(id); + + ViewBag.BidError = TempData["BidError"]; + ViewBag.ReviewError = TempData["ReviewError"]; + if (user.Id != auction.User_Sale_ID && userInAuctionRepository.GetById(new Tuple(auction.Id,user.Id)) == null ) + { + Notification notification = new Notification(NotificationType.NewUserInAuction, auction.User_Sale_ID, user.Name, auction.Product.Name, auction.Product.Price); + notification.AuctionId = auction.Id; + notificationRepository.AddEntity(notification); + userInAuctionRepository.AddEntity(new UserInAuction() { + AuctionId = auction.Id, + UserId = user.Id, + LastActionDate = DateTime.Now, + LastAction = "Join the auction" + }); + } + + AuctionViewModel viewModel = new AuctionViewModel() + { + ActualPrice = auction.ActualPrice, + ActualUser = auction.ActualUser, + Ammount = auction.Ammount, + Date = auction.Date, + Import = auction.ActualPrice * auction.Ammount, + InitialPrice = auction.InitialPrice, + InitialTime = auction.InitialTime, + Product = auction.Product, + ProductId = auction.ProductId, + User_Buy = auction.User_Buy, + User_Buy_ID = auction.User_Buy_ID, + User_Sale = auction.User_Sale, + User_Sale_ID = auction.User_Sale_ID, + Id = auction.Id, + Notifications = notificationRepository.AuctionNotification(auction.Id).ToList(), + Review = productRepository.Reviews(auction.ProductId) + }; + foreach (var item in auction.UsersInAuctions) + { + item.User = userRepository.GetById(item.UserId); + } + viewModel.UsersInAuctions = auction.UsersInAuctions; + viewModel.UsersInAuctions = viewModel.UsersInAuctions.OrderByDescending(x => x.LastActionDate).ToList(); + return View(viewModel); + } + + public IActionResult Bid(AuctionViewModel viewModel) + { + var user = userRepository.GetByUsername(User.Identity.Name); + if (user.Id == viewModel.User_Sale_ID) + { + TempData["BidError"] = "Error! You can not bid your own product"; + return RedirectToAction("Auction", viewModel); + } + + Auction auction = repository.GetById(viewModel.Id); + if(viewModel.ActualPrice > auction.ActualPrice) + { + Notification notification = new Notification(NotificationType.RaisePrice, viewModel.User_Sale_ID, user.UserName, viewModel.ProductName, viewModel.ActualPrice); + notification.AuctionId = auction.Id; + notificationRepository.AddEntity(notification); + auction.ActualPrice = viewModel.ActualPrice; + auction.ActualUser = user.Id; + repository.Update(auction); + var userInAuction = userInAuctionRepository.GetById(new Tuple(auction.Id, auction.ActualUser)); + userInAuction.LastActionDate = DateTime.Now; + userInAuction.LastAction = $"Raise the price to {viewModel.ActualPrice}"; + userInAuctionRepository.Update(userInAuction); + return RedirectToAction("Auction", viewModel); + } + TempData["BidError"] = "Invalid ammount."; + return RedirectToAction("Auction", viewModel); + } + + } +} diff --git a/Controllers/Controllers/Bank.cs b/Controllers/Controllers/Bank.cs new file mode 100644 index 0000000..3b706c6 --- /dev/null +++ b/Controllers/Controllers/Bank.cs @@ -0,0 +1,23 @@ +using Project.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project +{ + public static class Bank + { + public static bool Deposit(BankAccount UserPay, IEnumerable UsersToPay, IEnumerable MoneyToPay) + { + float total = MoneyToPay.Sum(); + if (UserPay.Ammount < total) return false; + foreach (var item in UsersToPay.Zip(MoneyToPay)) + { + UserPay.Ammount -= item.Second; + item.First.Ammount += item.Second; + } + return true; + } + } +} diff --git a/Controllers/Controllers/BankAccountController.cs b/Controllers/Controllers/BankAccountController.cs new file mode 100644 index 0000000..5a9b489 --- /dev/null +++ b/Controllers/Controllers/BankAccountController.cs @@ -0,0 +1,111 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class BankAccountController : Controller + { + public readonly IBankAccountRepository repository; + private readonly IUserRepository userRepository; + + public BankAccountController(IBankAccountRepository repository, IUserRepository userRepository) + { + this.repository = repository; + this.userRepository = userRepository; + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(AddBankAccountViewModel accountViewModel) + { + if (!ModelState.IsValid) + return View(); + + User user = userRepository.GetByUsername(User.Identity.Name); + + BankAccount bankAccount = new BankAccount() + { + AccountId = accountViewModel.AccountId, + Titular = accountViewModel.Titular, + UserId = user.Id + }; + repository.AddEntity(bankAccount); + + User newUser = new User() + { + AccountID = bankAccount.Id, + Active = true, + Name = user.Name, + City = accountViewModel.City, + Email = user.Email, + Id = user.Id, + Info = user.Info, + LastName = user.LastName, + PhoneNumber = accountViewModel.Telephone, + UserName = user.UserName + }; + userRepository.Update(newUser); + + return RedirectToAction("Index","Home"); + } + public IActionResult Delete(long Id) + { + repository.Delete(Id); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long Id) + { + var item = repository.GetById(Id); + return View(item); + } + [HttpPost] + public IActionResult Update(BankAccount item) + { + repository.Update(item); + return RedirectToAction("All"); + } + + + [HttpGet] + public IActionResult AddNewAccount() + { + return View(); + } + + [HttpPost] + public IActionResult AddNewAccount(AddNewBankAccountViewModel viewModel) + { + if (!ModelState.IsValid) + { + return View(); + } + User user = userRepository.GetByUsername(User.Identity.Name); + BankAccount bankAccount = new BankAccount() + { + AccountId = viewModel.AccountId, + Titular = viewModel.Titular, + UserId = user.Id + }; + repository.AddEntity(bankAccount); + return RedirectToAction("MyUser", "User"); + } + + } +} diff --git a/Controllers/Controllers/ErrorController.cs b/Controllers/Controllers/ErrorController.cs new file mode 100644 index 0000000..ff55c8c --- /dev/null +++ b/Controllers/Controllers/ErrorController.cs @@ -0,0 +1,46 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class ErrorController : Controller + { + [Route("Error/{statuscode}")] + public IActionResult HttpStatusCodeHandler(int statuscode) + { + var statusCodeResult = HttpContext.Features.Get(); + ErrorViewModel viewModel = new ErrorViewModel(); + switch (statuscode) + { + case 404: + viewModel.ErrorTitle = "Oops! Page not found."; + viewModel.ErrorMessage = "We could not find the page you were looking for."; + viewModel.Path = statusCodeResult.OriginalPath; + viewModel.QueryString = statusCodeResult.OriginalQueryString; + break; + } + return View("NotFound",viewModel); + } + + [AllowAnonymous] + [Route("Error")] + public IActionResult Error() + { + var exceptionDetails = HttpContext.Features.Get(); + ErrorViewModel viewModel = new ErrorViewModel + { + ErrorTitle = "Error!", + ErrorMessage = exceptionDetails.Error.Message, + Path = exceptionDetails.Path, + StackTrace = exceptionDetails.Error.StackTrace + }; + return View("Error",viewModel); + } + } +} diff --git a/Controllers/Controllers/HomeController.cs b/Controllers/Controllers/HomeController.cs new file mode 100644 index 0000000..97f1302 --- /dev/null +++ b/Controllers/Controllers/HomeController.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Project.Models; +using Project.Models.Repository.Interfaces; +using Project.ViewModels; + +namespace Project.Controllers +{ + [AllowAnonymous] + public class HomeController : Controller + { + private readonly ILogger _logger; + IProductRepository productRepository; + private readonly IUserRepository userRepository; + private readonly IAuctionRepository auctionRepository; + + public HomeController(ILogger logger, IProductRepository productRepository,IUserRepository userRepository, IAuctionRepository auctionRepository) + { + this.productRepository = productRepository; + this.userRepository = userRepository; + this.auctionRepository = auctionRepository; + _logger = logger; + } + + + public IActionResult Index() + { + IndexViewModel indexViewModel = new IndexViewModel() + { + Banner = productRepository.Banner().ToList(), + Auction = auctionRepository.MostPopularAuction(6).ToList(), + Favorites = productRepository.Favorites().Take(3).ToList(), + New = productRepository.New(), + MoneyAuctions = auctionRepository.MostMoneyAuction(6).ToList() + }; + foreach (var item in indexViewModel.Auction) + { + item.Product = productRepository.GetById(item.ProductId); + } + foreach (var item in indexViewModel.MoneyAuctions) + { + item.Product = productRepository.GetById(item.ProductId); + } + return View(indexViewModel); + } + + public IActionResult Privacy() + { + return View(); + } + + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] + public IActionResult Error() + { + return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); + } + + public ViewResult AboutUs() + { + return View(); + } + + [HttpGet] + public ViewResult FAQ() + { + return View(); + } + } +} diff --git a/Controllers/Controllers/LoginController.cs b/Controllers/Controllers/LoginController.cs new file mode 100644 index 0000000..cfe1a59 --- /dev/null +++ b/Controllers/Controllers/LoginController.cs @@ -0,0 +1,92 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class LoginController : Controller + { + private readonly UserManager userManager; + private readonly SignInManager signInManager; + private readonly RoleManager roleManager; + + public LoginController(UserManager userManager, SignInManager signInManager,RoleManager roleManager) + { + this.userManager = userManager; + this.signInManager = signInManager; + this.roleManager = roleManager; + } + + + [HttpGet] + public ViewResult Register() + { + return View(); + } + + [HttpPost] + public async Task Register(RegisterViewModel model) + { + if (ModelState.IsValid) + { + var user = new User { UserName = model.UserName, Email = model.Email, }; + var result = await userManager.CreateAsync(user, model.Password); + + if (result.Succeeded) + { + await signInManager.SignInAsync(user, isPersistent: false); + return RedirectToAction("index", "home"); + } + else + { + foreach (var error in result.Errors) + { + ModelState.AddModelError("", errorMessage: error.Description); + } + } + } + return View(model); + } + + + [HttpPost] + public async Task Logout() + { + await signInManager.SignOutAsync(); + return RedirectToAction("index", "home"); + } + + [HttpGet] + public ViewResult Login() + { + return View(); + } + + [HttpPost] + public async Task Login(LoginViewModel model,string returnUrl) + { + if (ModelState.IsValid) + { + var x = await userManager.FindByNameAsync(model.UserName); + //Arreglar para hacer el RememberMe + var result = await signInManager.PasswordSignInAsync(model.UserName, model.Password,true,false); + + if (result.Succeeded) + { + if (string.IsNullOrEmpty(returnUrl)) + { + return RedirectToAction("Index", "Home"); + } + return Redirect(returnUrl); + } + ModelState.AddModelError("", errorMessage: "InvalidLoginAttempt"); + } + return View(model); + } + } +} diff --git a/Controllers/Controllers/NotificationController.cs b/Controllers/Controllers/NotificationController.cs new file mode 100644 index 0000000..55c2bb2 --- /dev/null +++ b/Controllers/Controllers/NotificationController.cs @@ -0,0 +1,96 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using Project.Models.Repository.Interfaces; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class NotificationController :Controller + { + public readonly INotificationRepository repository; + private readonly IProductRepository productRepository; + private readonly IUserRepository userRepository; + + public NotificationController(INotificationRepository repository, IProductRepository productRepository, IUserRepository userRepository) + { + this.repository = repository; + this.productRepository = productRepository; + this.userRepository = userRepository; + } + + public ViewResult All() + { + string username = User.Identity.Name; + User user = userRepository.GetByUsername(username); + IEnumerable list = repository.GetAll().Where(x => x.UserId == user.Id); + AllNotificationViewModel viewModel = new AllNotificationViewModel(list); + return View(viewModel); + } + + [HttpPost] + public ViewResult All(AllNotificationViewModel viewModel) + { + string username = User.Identity.Name; + User user = userRepository.GetByUsername(username); + DateTime default_date = new DateTime(); + viewModel.Text_Search = viewModel.Text_Search == null ? "" : viewModel.Text_Search; + if (viewModel.Date_Search == default_date) + viewModel.Notifications = repository.GetAll().Where(x => x.UserId == user.Id && (viewModel.Text_Search == "" || x.Text.Contains(viewModel.Text_Search))); + else + viewModel.Notifications = repository.GetAll().Where(x => (x.UserId == user.Id && (viewModel.Text_Search == "" || x.Text.Contains(viewModel.Text_Search))) && x.Date == viewModel.Date_Search); + return View(viewModel); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(Notification position) + { + if (!ModelState.IsValid) + return View(); + repository.AddEntity(position); + return RedirectToAction("All"); + } + + [HttpPost] + public IActionResult AddIlicit(IlicitProductViewModel model) + { + if (!ModelState.IsValid) + return RedirectToAction("IlicitProduct", "Product"); + + Notification notification = new Notification() + { + Text = $"Your announcement {model.ProductName} has ilicit content on in. It was removed from our site. ", + UserId = model.UserId + }; + productRepository.Delete(model.ProductId); + repository.AddEntity(notification); + return RedirectToAction("IlicitProduct","Product"); + } + public IActionResult Delete(long Id) + { + repository.Delete(Id); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long Id) + { + var item = repository.GetById(Id); + return View(item); + } + [HttpPost] + public IActionResult Update(Notification item) + { + repository.Update(item); + return RedirectToAction("All"); + } + } +} diff --git a/Controllers/Controllers/ProductController.cs b/Controllers/Controllers/ProductController.cs new file mode 100644 index 0000000..a4e9c75 --- /dev/null +++ b/Controllers/Controllers/ProductController.cs @@ -0,0 +1,431 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.Extensions.Logging; +using Project.Models; +using Project.ViewModels; + +namespace Project.Controllers +{ + public class ProductController : Controller + { + public readonly IProductRepository repository; + private readonly IHostingEnvironment hostingEnvironment; + private readonly IUserRepository userRepository; + + public ProductController(IProductRepository repository, IHostingEnvironment hostingEnvironment, IUserRepository userRepository) + { + this.repository = repository; + this.hostingEnvironment = hostingEnvironment; + this.userRepository = userRepository; + } + + [HttpGet] + [AllowAnonymous] + public IActionResult All(string filter = "", int page = 1) + { + if (TempData != null) + { + if (TempData.Keys.Contains("AmmountError") && TempData["AmmountError"] != null) + { + ViewBag.ProductId = TempData["ProductId"]; + ViewBag.AmmountError = TempData["AmmountError"]; + } + if (TempData.Keys.Contains("UserError") && TempData["UserError"] != null) + { + ViewBag.ProductId = TempData["ProductId"]; + ViewBag.AmmountError = "You own this."; + } + } + if (page <= 0) page = 1; + AllProductsViewModel model = new AllProductsViewModel(); + if (page % 3 == 0) + model.FirstPage = page - 2 ; + else + model.FirstPage = page / 3 > 0 ? page / 3 * 3 + 1: 1; + if (model.FirstPage <= 0) model.FirstPage = 1; + model.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => filter == "" || x.Category.ToString() == filter || filter == "All").Take(9).ToList(); + model.Page = page; + model.selectListItems = new List(); + string[] array = { "None", "Price Down", "Price Up", "Rating Down", "Rating Up", "Name Down", "Name Up" }; + int count = 0; + foreach (var item in Enum.GetNames(typeof(Filters))) + { + model.selectListItems.Add(new SelectListItem(array[count],item)); + ++count; + } + model.selectListCategory = new List(); + foreach (var item in Enum.GetNames(typeof(Category))) + { + model.selectListCategory.Add(new SelectListItem(item, item)); + } + return View(model); + } + + [HttpPost] + public ViewResult AllFilter(AllProductsViewModel viewModel) + { + + var s = viewModel.Filter; + var categ = viewModel.Category; + int count = 0; + string[] array = { "None", "Price Down", "Price Up", "Rating Down", "Rating Up", "Name Down", "Name Up" }; + int page = viewModel.Page; + + foreach (var item in Enum.GetNames(typeof(Filters))) + { + if(s.ToString() == item) + { + viewModel.selectListItems.Add(new SelectListItem(array[count], item,true)); + } + else + { + viewModel.selectListItems.Add(new SelectListItem(array[count], item)); + } + ++count; + } + + foreach (var item in Enum.GetNames(typeof(Category))) + { + if (categ.ToString() == item) + { + viewModel.selectListCategory.Add(new SelectListItem(item, item, true)); + } + else + { + viewModel.selectListCategory.Add(new SelectListItem(item, item)); + } + } + switch (s) + { + case Filters.None: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).Take(9).ToList(); + break; + case Filters.PriceDown: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).OrderByDescending(x =>x.Price).Take(9).ToList(); + break; + case Filters.PriceUp: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).OrderBy(x => x.Price).Take(9).ToList(); + break; + case Filters.RatingDown: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).OrderByDescending(x => x.Rating).Take(9).ToList(); + break; + case Filters.RatingUp: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).OrderBy(x => x.Rating).Take(9).ToList(); + break; + case Filters.NameDown: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).OrderByDescending(x => x.Name).Take(9).ToList(); + break; + case Filters.NameUp: + viewModel.Products = repository.GetAll().Skip((page - 1) * 9).Where(x => categ == Category.All || categ == x.Category).OrderBy(x => x.Name).Take(9).ToList(); + break; + default: + break; + } + + return View("All",viewModel); + } + + public IActionResult Add() + { + var UserId = userRepository.GetByUsername(User.Identity.Name).Id; + + if (!userRepository.HasAccounts(UserId)) + { + return RedirectToAction("Add", "BankAccount"); + } + + return View(); + } + + [HttpPost] + public IActionResult Add(ProductCreateViewModel product) + { + var UserId = userRepository.GetByUsername(product.Username).Id; + + string uniquefilename = null; + if (!ModelState.IsValid) + return View(); + + + Product newproduct = new Product() + { + Name = product.Name, + Ammount = product.Ammount ?? 1, + Category = product.Category, + Description = product.Description, + Price = product.Price ?? 1, + UserId = UserId + }; + + repository.AddEntity(newproduct); + long id = newproduct.Id; + + string folder = Path.Combine(hostingEnvironment.WebRootPath, "images", id.ToString()); + if (!System.IO.File.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + if (product.Images != null && product.Images.Count > 0) + { + + foreach (var image in product.Images) + { + uniquefilename = Guid.NewGuid().ToString() + "_" + image.FileName; + string path = Path.Combine(folder, uniquefilename); + image.CopyTo(new FileStream(path, FileMode.Create)); + } + } + else + { + uniquefilename = "NoImage.png"; + string sourcePath = Path.Combine(hostingEnvironment.WebRootPath, "img",uniquefilename); + folder = Path.Combine(folder, uniquefilename); + System.IO.File.Copy(sourcePath, folder); + } + + newproduct.Images = uniquefilename; + repository.Update(newproduct); + + ProductViewModel productViewModel = new ProductViewModel(); + productViewModel.Product = repository.GetById(id); + productViewModel.Reviews = repository.Reviews(id).ToList(); + //productViewModel.Favorites = repository.Favorites().ToList(); + + //Hacer paginado para los reviews + ViewData["ReviewPages"] = 1; + //return RedirectToAction("product", newproduct.Id); + + return View("VisualizeProduct", productViewModel); + } + + public IActionResult Delete(long Id,string url) + { + repository.Delete(Id); + if(url == null) + return RedirectToAction("UserProduct"); + return RedirectToAction("MyUser", "User"); + } + + [HttpGet] + public ViewResult Update(long Id) + { + var item = repository.GetById(Id); + ProductCreateViewModel p = new ProductCreateViewModel() + { + Id = Id, + Ammount = item.Ammount, + Category = item.Category, + Description = item.Description, + Name = item.Name, + Price = item.Price, + Rating = item.Rating, + + }; + + string folder = Path.Combine(hostingEnvironment.WebRootPath, "images", item.Id.ToString()); + try + { + IEnumerable files = Directory.EnumerateFiles(folder); + p.img = new List(); + foreach (var img in files) + { + p.img.Add(img); + } + } + catch { } + + return View(p); + } + [HttpPost] + public IActionResult Update(ProductCreateViewModel item) + { + var user = userRepository.GetByUsername(User.Identity.Name); + Product p = new Product() + { + Id = item.Id, + Name = item.Name, + Category = item.Category, + Ammount = (int)item.Ammount, + Description = item.Description, + Price = (decimal)item.Price, + Rating = item.Rating, + Active = true, + User = user, + UserId = user.Id + }; + + string uniquefilename = null; + string folder = Path.Combine(hostingEnvironment.WebRootPath, "images", item.Id.ToString()); + if (!System.IO.File.Exists(folder)) + { + Directory.CreateDirectory(folder); + } + if (item.Images != null && item.Images.Count > 0) + { + foreach (var image in item.Images) + { + uniquefilename = Guid.NewGuid().ToString() + "_" + image.FileName; + string path = Path.Combine(folder, uniquefilename); + image.CopyTo(new FileStream(path, FileMode.Create)); + } + } + else + { + uniquefilename = "NoImage.png"; + string sourcePath = Path.Combine(hostingEnvironment.WebRootPath, "img", uniquefilename); + var file = Path.Combine(folder, uniquefilename); + try + { + System.IO.File.Copy(sourcePath, file); + } + catch { } + + + } + + IEnumerable files = Directory.EnumerateFiles(folder); + p.Images = uniquefilename; + repository.Update(p); + return RedirectToAction("UserProduct"); + } + [AllowAnonymous] + public ViewResult Product(long Id) + { + + ViewBag.ReviewError = TempData["ReviewError"]; + ViewBag.AmmountError = TempData["AmmountError"]; + ProductViewModel model = new ProductViewModel(); + model.Product = repository.GetById(Id); + model.Reviews = repository.Reviews(Id).ToList(); + model.Favorites = repository.Favorites().Take(9).ToList(); + model.Files = new DirectoryInfo($"wwwroot/images/{model.Product.Id}").GetFiles().Select(o => o.Name); + model.ReviewPage = 1; + model.ReviewFirstPage = 1; + + return View(model); + } + + [AllowAnonymous] + public ViewResult ProductReview(long Id, int page) + { + ProductViewModel viewModel = new ProductViewModel(); + if (page <= 0) page = 1; + if (page % 3 == 0) + viewModel.ReviewFirstPage = page - 2; + else + viewModel.ReviewFirstPage = page / 3 > 0 ? page / 3 * 3 + 1 : 1; + if (viewModel.ReviewFirstPage <= 0) viewModel.ReviewFirstPage = 1; + viewModel.ReviewPage = page; + viewModel.Product = repository.GetById(Id); + viewModel.Favorites = repository.Favorites().Take(9).ToList(); + viewModel.Files = new DirectoryInfo($"wwwroot/images/{viewModel.Product.Id}").GetFiles().Select(o => o.Name); + viewModel.Reviews = repository.Reviews(viewModel.ProductId).Skip((viewModel.ReviewPage - 1) * 3).ToList(); + return View("Product",viewModel); + } + + [HttpGet] + public IActionResult UserProduct() + { + AllProductsViewModel model = new AllProductsViewModel(); + model.FirstPage = 1; + string id = userRepository.GetByUsername(User.Identity.Name).Id; + model.Products = repository.GetUserProducts(id).Take(9).ToList(); + model.selectListItems = new List(); + string[] array = { "None", "Price Down", "Price Up", "Rating Down", "Rating Up", "Name Down", "Name Up" }; + int count = 0; + foreach (var item in Enum.GetNames(typeof(Filters))) + { + model.selectListItems.Add(new SelectListItem(array[count], item)); + ++count; + } + model.selectListCategory = new List(); + foreach (var item in Enum.GetNames(typeof(Category))) + { + model.selectListCategory.Add(new SelectListItem(item, item)); + } + return View(model); + } + + [HttpPost] + public IActionResult UserProduct(AllProductsViewModel viewModel) + { + int page = viewModel.Page; + string category = viewModel.Category.ToString(); + if (page <= 0) page = 1; + AllProductsViewModel model = new AllProductsViewModel(); + if (page % 3 == 0) + model.FirstPage = page - 2; + else + model.FirstPage = page / 3 > 0 ? page / 3 * 3 + 1 : 1; + if (model.FirstPage <= 0) model.FirstPage = 1; + string id = userRepository.GetByUsername(User.Identity.Name).Id; + model.Products = repository.GetUserProducts(id).Skip((page - 1) * 9).Where(x => category == "" || x.Category.ToString() == category || category == "All").ToList(); + model.selectListItems = new List(); + string[] array = { "None", "Price Down", "Price Up", "Rating Down", "Rating Up", "Name Down", "Name Up" }; + int count = 0; + foreach (var item in Enum.GetNames(typeof(Filters))) + { + model.selectListItems.Add(new SelectListItem(array[count], item)); + ++count; + } + model.selectListCategory = new List(); + foreach (var item in Enum.GetNames(typeof(Category))) + { + model.selectListCategory.Add(new SelectListItem(item, item)); + } + return View(model); + } + + [HttpGet] + public IActionResult VisualizeProduct(long id) + { + var p = repository.GetById(id); + ProductViewModel viewModel = new ProductViewModel() + { + Product = p, + Files = new DirectoryInfo($"wwwroot/images/{p.Id}").GetFiles().Select(o => o.Name) + }; + return View(viewModel); + } + + [HttpPost] + public IActionResult IlicitContent(ProductViewModel model) + { + var p = repository.GetById(model.Product.Id); + if (p.IlicitContent) + return RedirectToAction("Product", new { p.Id }); + p.IlicitContent = true; + repository.Update(p); + return RedirectToAction("Product", new { p.Id }); + } + + [HttpGet] + public IActionResult IlicitProduct() + { + var products = repository.IlicitProducts(); + IlicitProductViewModel viewModel = new IlicitProductViewModel() + { + Products = products + }; + return View(viewModel); + } + + public IActionResult RemoveIlicit(string id) + { + Product p = repository.GetById(id); + p.IlicitContent = false; + repository.Update(p); + return RedirectToAction("IlicitProduct"); + } + + } +} diff --git a/Controllers/Controllers/ProductInCartController.cs b/Controllers/Controllers/ProductInCartController.cs new file mode 100644 index 0000000..3475b3d --- /dev/null +++ b/Controllers/Controllers/ProductInCartController.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class ProductInCartController : Controller + { + public readonly IProductInCartRepository repository; + public ProductInCartController(IProductInCartRepository repository) + { + this.repository = repository; + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(ProductInCart position) + { + if (!ModelState.IsValid) + return View(); + repository.AddEntity(position); + return RedirectToAction("All"); + } + public IActionResult Delete(long ProductId, long ShoppingCartId) + { + repository.Delete(new Tuple(ProductId, ShoppingCartId)); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long ProductId, long ShoppingCartId) + { + var item = repository.GetById(new Tuple(ProductId, ShoppingCartId)); + return View(item); + } + [HttpPost] + public IActionResult Update(ProductInCart item) + { + repository.Update(item); + return RedirectToAction("All"); + } + } +} diff --git a/Controllers/Controllers/ReviewController.cs b/Controllers/Controllers/ReviewController.cs new file mode 100644 index 0000000..d78ca65 --- /dev/null +++ b/Controllers/Controllers/ReviewController.cs @@ -0,0 +1,124 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class ReviewController : Controller + { + public readonly IReviewRepository repository; + private readonly IUserRepository userRepository; + private readonly IProductRepository productRepository; + + public ReviewController(IReviewRepository repository, IUserRepository userRepository, IProductRepository productRepository) + { + this.repository = repository; + this.userRepository = userRepository; + this.productRepository = productRepository; + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(ProductViewModel model) + { + string id = userRepository.GetByUsername(model.Username).Id; + var Id = model.Review.ProductId; + if (!ModelState.IsValid || repository.Exists(id, (int)Id)) + { + TempData["ReviewError"] = "You have already inserted a review on this product."; + return RedirectToAction("Product", "Product", new { Id }); + } + + var productowner = productRepository.GetById(Id).UserId; + if(productowner == id) + { + TempData["ReviewError"] = "You can not add a review on your own product."; + return RedirectToAction("Product", "Product", new { Id }); + } + if (model.Rate == null) + { + TempData["ReviewError"] = "You must select a star value"; + return RedirectToAction("Auction", "Auction", new { Id }); + } + + Review r = new Review() + { + Date = DateTime.Now, + ProductId = Id, + Rating = int.Parse(model.Rate), + ReviewText = model.Review.ReviewText, + UserId = id + }; + + repository.AddEntity(r); + return RedirectToAction("Product", "Product",new { Id }); + } + + public IActionResult AddReviewInAuction(AuctionViewModel model) + { + string id = userRepository.GetByUsername(User.Identity.Name).Id; + var Id = model.WrittenReview.ProductId; + if (!ModelState.IsValid || repository.Exists(id, (int)Id)) + { + TempData["ReviewError"] = "You have already inserted a review on this product."; + return RedirectToAction("Auction", "Auction", new { model.Id }); + } + + var productowner = productRepository.GetById(Id).UserId; + if (productowner == id) + { + TempData["ReviewError"] = "You can not add a review on your own product."; + return RedirectToAction("Auction", "Auction", new { model.Id }); + } + if(model.Rate == null) + { + TempData["ReviewError"] = "You must select a star value"; + return RedirectToAction("Auction", "Auction", new { model.Id }); + } + + Review r = new Review() + { + Date = DateTime.Now, + ProductId = Id, + Rating = int.Parse(model.Rate), + ReviewText = model.WrittenReview.ReviewText, + UserId = id + }; + + repository.AddEntity(r); + return RedirectToAction("Auction", "Auction", new { model.Id }); + } + public IActionResult Delete(long ProductId, long UserId) + { + repository.Delete(new Tuple(ProductId, UserId)); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long ProductId, long UserId) + { + var item = repository.GetById(new Tuple(ProductId, UserId)); + return View(item); + } + [HttpPost] + public IActionResult Update(Review item) + { + repository.Update(item); + return RedirectToAction("All"); + } + } +} diff --git a/Controllers/Controllers/SaleController.cs b/Controllers/Controllers/SaleController.cs new file mode 100644 index 0000000..c08dc5e --- /dev/null +++ b/Controllers/Controllers/SaleController.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class SaleController : Controller + { + public readonly ISaleRepository repository; + public SaleController(ISaleRepository repository) + { + this.repository = repository; + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(Sale position) + { + if (!ModelState.IsValid) + return View(); + repository.AddEntity(position); + return RedirectToAction("All"); + } + public IActionResult Delete(long Id) + { + repository.Delete(Id); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long Id) + { + var item = repository.GetById(Id); + return View(item); + } + [HttpPost] + public IActionResult Update(Sale item) + { + repository.Update(item); + return RedirectToAction("All"); + } + } +} diff --git a/Controllers/Controllers/ShoppingCartController.cs b/Controllers/Controllers/ShoppingCartController.cs new file mode 100644 index 0000000..d6e7f36 --- /dev/null +++ b/Controllers/Controllers/ShoppingCartController.cs @@ -0,0 +1,343 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Rendering; +using Project.Models; +using Project.Models.Repository.Interfaces; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class ShoppingCartController : Controller + { + public readonly IShoppingCartRepository repository; + private readonly IUserRepository userRepository; + private readonly IProductInCartRepository productInCartRepository; + private readonly IProductRepository productRepository; + private readonly IBankAccountRepository bankAccountRepository; + private readonly INotificationRepository notificationRepository; + private readonly ISaleRepository saleRepository; + private User UserId; + + public ShoppingCartController(IShoppingCartRepository repository, IUserRepository userRepository, IProductInCartRepository productInCartRepository, + IProductRepository productRepository, IBankAccountRepository bankAccountRepository, INotificationRepository notificationRepository, + ISaleRepository saleRepository) + { + this.repository = repository; + this.userRepository = userRepository; + this.productInCartRepository = productInCartRepository; + this.productRepository = productRepository; + this.bankAccountRepository = bankAccountRepository; + this.notificationRepository = notificationRepository; + this.saleRepository = saleRepository; + } + + public void AddCarts() + { + for (int i = 0; i < 5; i++) + { + ShoppingCart cart = new ShoppingCart(); + repository.AddEntity(cart); + } + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(ShoppingCart position) + { + if (!ModelState.IsValid) + return View(); + repository.AddEntity(position); + return RedirectToAction("All"); + } + + public IActionResult Delete(long Id) + { + repository.Delete(Id); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long Id) + { + var item = repository.GetById(Id); + return View(item); + } + [HttpPost] + public IActionResult Update(ShoppingCart item) + { + repository.Update(item); + return RedirectToAction("All"); + } + + [HttpGet] + public IActionResult AddProductById(int id) + { + Product product = productRepository.GetById(id); + var user = userRepository.GetByUsername(User.Identity.Name); + var cart = repository.GetById(user.ShoppingCartId); + ProductInCart productInCart = new ProductInCart() + { + Ammount = 1, + ProductId = product.Id, + ShoppingCartId = cart.Id + }; + + var p = productInCartRepository.GetById(new Tuple(product.Id, cart.Id)); + if (p != null) + { + p.Ammount++; + productInCartRepository.Update(p); + } + else + { + productInCartRepository.AddEntity(productInCart); + } + return RedirectToAction("Index", "Home"); + + } + + + [HttpPost] + public IActionResult AddProduct(ProductViewModel entity) + { + UserId = userRepository.GetByUsername(User.Identity.Name); + var cart = repository.GetById(UserId.ShoppingCartId); + Product p = productRepository.GetById(entity.Product.Id); + + if(p.Ammount< entity.Product.Ammount) + { + TempData["AmmountError"]= "The ammount you requested is superior to the existing ammount of the product."; + return RedirectToAction("Product", "Product", new { id = p.Id }); + } + if (entity.Product.Ammount <= 0) + { + TempData["AmmountError"] = "The ammount you request must be bigger than zero."; + return RedirectToAction("Product", "Product", new { id = p.Id }); + } + ProductInCart product = new ProductInCart() + { + Ammount = entity.Product.Ammount, + ProductId = entity.Product.Id, + ShoppingCartId = cart.Id + }; + var temp = productInCartRepository.GetById(new Tuple(product.ProductId, product.ShoppingCartId)); + if(temp != null) + { + if(temp.Ammount + product.Ammount > p.Ammount) + { + TempData["AmmountError"] = "The ammount in your shopping cart requested is superior to the existing ammount of the product."; + return RedirectToAction("Product", "Product", new { id = p.Id }); + } + product.Ammount += temp.Ammount; + productInCartRepository.Delete(new Tuple(product.ProductId, product.ShoppingCartId)); + productInCartRepository.AddEntity(product); + } + else + productInCartRepository.AddEntity(product); + + return RedirectToAction("Product", "Product", new { id = p.Id }); + } + + [HttpPost] + public IActionResult AddProductById(AllProductsViewModel viewModel) + { + if (!ModelState.IsValid) + { + TempData["AmmountError"] = "Invalid"; + TempData["ProductId"] = viewModel.ProductId; + return RedirectToAction("All", "Product"); + } + + var user = userRepository.GetByUsername(User.Identity.Name); + var product = productRepository.GetById(viewModel.ProductId); + if(user.Id == product.UserId) + { + TempData["UserError"] = "Invalid"; + TempData["ProductId"] = viewModel.ProductId; + return RedirectToAction("All", "Product"); + } + + var cart = repository.GetById(user.ShoppingCartId); + ProductInCart productInCart = new ProductInCart() + { + Ammount = viewModel.Ammount, + ProductId = viewModel.ProductId, + ShoppingCartId = cart.Id + }; + + var p = productInCartRepository.GetById(new Tuple(viewModel.ProductId, cart.Id)); + if (p != null) + { + p.Ammount+=viewModel.Ammount; + productInCartRepository.Update(p); + } + else + { + productInCartRepository.AddEntity(productInCart); + } + return RedirectToAction("All", "Product"); + } + + [HttpGet] + public IActionResult DeleteProduct(int id) + { + UserId = userRepository.GetByUsername(User.Identity.Name); + productInCartRepository.Delete( new Tuple((long)id, UserId.ShoppingCartId)); + return RedirectToAction("ShoppingCart"); + } + + private IEnumerable Products() + { + UserId = userRepository.GetByUsername(User.Identity.Name); + IEnumerable products = productInCartRepository.GetByCartId(UserId.ShoppingCartId); + List list = new List(); + foreach (var item in products) + { + Product product = productRepository.GetById(item.ProductId); + if (!product.Active) continue; + Product p = new Product + { + Ammount = item.Ammount, + Price = product.Price, + Name = product.Name, + Images = product.Images, + Id = product.Id, + Description = product.Description, + UserId = UserId.Id + }; + list.Add(p); + } + return list; + } + + public IActionResult ShoppingCart() + { + var list = Products(); + return View(list); + } + + public IActionResult Checkout() + { + if (TempData["Error"] != null) + ViewBag.Error = TempData["Error"]; + UserId = userRepository.GetByUsername(User.Identity.Name); + var banks = bankAccountRepository.GetByUserId(UserId.Id); + List list = new List(); + foreach (var item in banks) + { + list.Add(new SelectListItem { Value = item.Id.ToString(), Text = (item.AccountId, item.Titular).ToString() }); + } + CheckoutViewModel viewModel = new CheckoutViewModel() + { + BankAccounts = banks, + Products = Products().ToList(), + ListItems = list + }; + return View(viewModel); + } + + [HttpPost] + public IActionResult Checkout(CheckoutViewModel viewModel) + { + if (!ModelState.IsValid) + return RedirectToAction("Checkout"); + + UserId = userRepository.GetByUsername(User.Identity.Name); + List UsersToPay = new List(); + List MoneyToPay = new List(); + //Se supone que se haga la transferencia bancaria y se compruebe que es valida + + foreach (var item in viewModel.Products) + { + //Encontrar el producto que se esta comprando + Product product = productRepository.GetById(item.Id); + if(product == null) + { + TempData["Error"] = $"The product {item.Name} is no longer available"; + return RedirectToAction("Checkout"); + } + if(item.Ammount > product.Ammount) + { + TempData["Error"] = $"Sorry! The product {item.Name} is out of order"; + return RedirectToAction("Checkout"); + } + + //Actualizar el producto y guardar las notificaciones + product.Ammount -= item.Ammount; + if (product.Ammount == 0) + { + product.Active = false; + Notification notification2 = new Notification(NotificationType.SaleCompleted, product.UserId, new object[] + { UserId.Name, item.Name, item.Price,item.Ammount,item.Price * item.Ammount }); + notificationRepository.AddEntity(notification2); + } + + + productRepository.Update(product); + Notification notification = new Notification(NotificationType.SaleProduct, product.UserId, UserId.Name, + item.Name, item.Price, item.Ammount, item.Price * item.Ammount); + + Notification notification1 = new Notification(NotificationType.BuyProduct, UserId.Id, UserId.Name, item.Name, item.Price, item.Ammount, item.Price * item.Ammount); + + notificationRepository.AddEntity(notification); + notificationRepository.AddEntity(notification1); + + //Insertar la venta + Sale sale = new Sale() + { + Ammount = item.Ammount, + Import = item.Price * item.Ammount, + Date = DateTime.Now, + ProductId = item.Id, + User_Buy_ID = UserId.Id, + User_Sale_ID = product.UserId, + Active = true + }; + saleRepository.AddEntity(sale); + if(bankAccountRepository.GetAll().Any(x => x.UserId == product.UserId)) + { + BankAccount account = bankAccountRepository.GetByUserId(product.UserId).First(); + UsersToPay.Add(account); + MoneyToPay.Add((float)item.Price * item.Ammount); + } + + } + + List productsInCart = productInCartRepository.GetByCartId(UserId.ShoppingCartId).ToList(); + List productsToDelete = new List(); + foreach (var item in productsInCart) + { + productsToDelete.Add(item); + } + foreach (var item in productsToDelete) + { + productInCartRepository.Delete(new Tuple(item.ProductId,item.ShoppingCartId)); + } + UsersToPay.Add(bankAccountRepository.GetByTitular("Shoppify")); + MoneyToPay.Add((MoneyToPay.Sum() * 2) / 100); + BankAccount userpay = bankAccountRepository.GetByUserId(UserId.Id).First(); + + bool deposit = Bank.Deposit(userpay, UsersToPay, MoneyToPay); + if (!deposit) + { + TempData["Error"] = "Error in the bank transfer."; + } + TempData["Error"] = "Succesfull checkout"; + return RedirectToAction("Checkout"); + } + } +} \ No newline at end of file diff --git a/Controllers/Controllers/UserController.cs b/Controllers/Controllers/UserController.cs new file mode 100644 index 0000000..78d825b --- /dev/null +++ b/Controllers/Controllers/UserController.cs @@ -0,0 +1,104 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using Project.Models.Repository.Interfaces; +using Project.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class UserController : Controller + { + public readonly IUserRepository repository; + private readonly IProductRepository productRepository; + private readonly IBankAccountRepository bankAccountRepository; + private readonly INotificationRepository notificationRepository; + + public UserController(IUserRepository repository, IProductRepository productRepository, IBankAccountRepository bankAccountRepository, + INotificationRepository notificationRepository) + { + this.repository = repository; + this.productRepository = productRepository; + this.bankAccountRepository = bankAccountRepository; + this.notificationRepository = notificationRepository; + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(User position) + { + if (!ModelState.IsValid) + return View(); + repository.AddEntity(position); + return RedirectToAction("All"); + } + public IActionResult Delete(long Id) + { + repository.Delete(Id); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(string Id) + { + var item = repository.GetById(Id); + RegisterViewModel viewModel = new RegisterViewModel() + { + Email = item.Email, + Info = item.Info, + LastName = item.LastName, + Name = item.Name, + UserName = item.UserName, + Telephone = item.PhoneNumber, + City = item.City + }; + return View(viewModel); + } + [HttpPost] + public IActionResult Update(RegisterViewModel item) + { + User user = new User() + { + Id = repository.GetByUsername(User.Identity.Name).Id, + Name = item.Name, + Email = item.Email, + City = item.City, + Info = item.Info, + LastName = item.LastName, + UserName = item.UserName, + PhoneNumber = item.Telephone + }; + repository.Update(user); + return RedirectToAction("MyUser"); + } + + [HttpGet] + public IActionResult MyUser() + { + User user = repository.GetByUsername(User.Identity.Name); + var products = productRepository.GetUserProducts(user.Id); + var account = bankAccountRepository.GetByUserId(user.Id); + var notifications = notificationRepository.UserNotifications(user.Id).OrderByDescending(x => x.Date).Take(10); + MyUserViewModel viewModel = new MyUserViewModel() + { + User = user, + Products = products, + BankAccounts = account, + Notifications = notifications + }; + return View(viewModel); + } + } +} diff --git a/Controllers/Controllers/UserInAuctionController.cs b/Controllers/Controllers/UserInAuctionController.cs new file mode 100644 index 0000000..b3aab3d --- /dev/null +++ b/Controllers/Controllers/UserInAuctionController.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Mvc; +using Project.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Controllers +{ + public class UserInAuctionController : Controller + { + public readonly IUserInAuctionRepository repository; + public UserInAuctionController(IUserInAuctionRepository repository) + { + this.repository = repository; + } + + public ViewResult All() + { + var list = repository.GetAll(); + return View(list.ToList()); + } + + public ViewResult Add() + { + return View(); + } + + [HttpPost] + public IActionResult Add(UserInAuction position) + { + if (!ModelState.IsValid) + return View(); + repository.AddEntity(position); + return RedirectToAction("All"); + } + public IActionResult Delete(long AuctionId, long UserId) + { + repository.Delete(new Tuple(AuctionId, UserId)); + return RedirectToAction("All"); + } + + [HttpGet] + public ViewResult Update(long AuctionId, long UserId) + { + var item = repository.GetById(new Tuple(AuctionId, UserId)); + return View(item); + } + [HttpPost] + public IActionResult Update(UserInAuction item) + { + repository.Update(item); + return RedirectToAction("All"); + } + } +} diff --git a/Migrations/20201112043607_Initial.Designer.cs b/Migrations/20201123042312_initial.Designer.cs similarity index 64% rename from Migrations/20201112043607_Initial.Designer.cs rename to Migrations/20201123042312_initial.Designer.cs index edb1bb5..7ae8596 100644 --- a/Migrations/20201112043607_Initial.Designer.cs +++ b/Migrations/20201123042312_initial.Designer.cs @@ -10,8 +10,8 @@ namespace Project.Migrations { [DbContext(typeof(ApplicationDBContext))] - [Migration("20201112043607_Initial")] - partial class Initial + [Migration("20201123042312_initial")] + partial class initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { @@ -247,15 +247,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); b.ToTable("BankAccounts"); - - b.HasData( - new - { - Id = 1L, - AccountId = "88888888", - Ammount = 0.1f, - Titular = "Shoppify" - }); }); modelBuilder.Entity("Project.Models.Notification", b => @@ -330,86 +321,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); b.ToTable("Products"); - - b.HasData( - new - { - Id = 1L, - Active = true, - Ammount = 5, - Category = 10, - IlicitContent = false, - Images = "main-product01.jpg", - Name = "Shoe", - Price = 34.5m, - Rating = 3, - UserId = "1" - }, - new - { - Id = 2L, - Active = true, - Ammount = 3, - Category = 1, - IlicitContent = false, - Images = "banner01.jpg", - Name = "Brown Bag", - Price = 20.5m, - Rating = 4, - UserId = "2" - }, - new - { - Id = 3L, - Active = true, - Ammount = 2, - Category = 1, - IlicitContent = false, - Images = "product03.jpg", - Name = "Wallet", - Price = 10.5m, - Rating = 5, - UserId = "3" - }, - new - { - Id = 4L, - Active = true, - Ammount = 8, - Category = 10, - IlicitContent = false, - Images = "product04.jpg", - Name = "Blue Shoe", - Price = 34.5m, - Rating = 3, - UserId = "1" - }, - new - { - Id = 5L, - Active = true, - Ammount = 1, - Category = 10, - IlicitContent = false, - Images = "product05.jpg", - Name = "Black Heels", - Price = 39.5m, - Rating = 4, - UserId = "2" - }, - new - { - Id = 6L, - Active = true, - Ammount = 4, - Category = 1, - IlicitContent = false, - Images = "product06.jpg", - Name = "Work Bag", - Price = 15m, - Rating = 5, - UserId = "3" - }); }); modelBuilder.Entity("Project.Models.ProductInCart", b => @@ -458,71 +369,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); b.ToTable("Reviews"); - - b.HasData( - new - { - ProductId = 2L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 3L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 13, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 4, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 2L, - UserId = "2", - Active = false, - Date = new DateTime(2020, 1, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 5, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 6L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 1, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 4L, - UserId = "2", - Active = false, - Date = new DateTime(2020, 2, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 2, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 1L, - UserId = "3", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 5L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }); }); modelBuilder.Entity("Project.Models.Sale", b => @@ -580,28 +426,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasKey("Id"); b.ToTable("ShoppingCarts"); - - b.HasData( - new - { - Id = 1L - }, - new - { - Id = 2L - }, - new - { - Id = 3L - }, - new - { - Id = 4L - }, - new - { - Id = 5L - }); }); modelBuilder.Entity("Project.Models.UserInAuction", b => @@ -660,71 +484,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasIndex("ShoppingCartId"); b.HasDiscriminator().HasValue("User"); - - b.HasData( - new - { - Id = "1", - AccessFailedCount = 0, - ConcurrencyStamp = "37d27f62-a90d-4e21-bbf0-542530b43346", - Email = "a.hernandez@mail.com", - EmailConfirmed = false, - LockoutEnabled = false, - PhoneNumber = "55123456", - PhoneNumberConfirmed = false, - SecurityStamp = "5e0d2604-bad3-46a2-a789-76940f1ad791", - TwoFactorEnabled = false, - UserName = "AHernandez", - AccountID = 0L, - Active = false, - City = "San Miguel, La Habana", - Info = "Los mejores productos", - LastName = "Hernandez", - Name = "Adrian", - ShoppingCartId = 1L - }, - new - { - Id = "2", - AccessFailedCount = 0, - ConcurrencyStamp = "af54c1ce-747b-40c1-b7bf-e622eb80b886", - Email = "c.olavarrieta@mail.com", - EmailConfirmed = false, - LockoutEnabled = false, - PhoneNumber = "54321678", - PhoneNumberConfirmed = false, - SecurityStamp = "afb475a3-7568-4f8d-b53e-1289d6230b4e", - TwoFactorEnabled = false, - UserName = "Claudita", - AccountID = 0L, - Active = false, - City = "Regla, La Habana", - Info = "Los mejores productos", - LastName = "Olavarrieta", - Name = "Claudia", - ShoppingCartId = 2L - }, - new - { - Id = "3", - AccessFailedCount = 0, - ConcurrencyStamp = "371a7def-4289-40c2-9579-0b16b6ed8a00", - Email = "m.valdivie@mail.com", - EmailConfirmed = false, - LockoutEnabled = false, - PhoneNumber = "54781698", - PhoneNumberConfirmed = false, - SecurityStamp = "8ae8f950-278c-438e-b523-86c8cfaa2599", - TwoFactorEnabled = false, - UserName = "marcOS", - AccountID = 0L, - Active = false, - City = "Cienfuegos", - Info = "Los mejores productos", - LastName = "Valdivie", - Name = "Marcos", - ShoppingCartId = 3L - }); }); modelBuilder.Entity("Project.Models.Auction", b => @@ -748,23 +507,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("datetime2"); b.HasDiscriminator().HasValue("Auction"); - - b.HasData( - new - { - Id = 1L, - Active = true, - Ammount = 1, - Date = new DateTime(2020, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), - Import = 0m, - ProductId = 6L, - User_Sale_ID = "3", - ActualPrice = 14m, - ActualUser = "2", - InitialPrice = 14m, - InitialTime = new DateTime(2020, 7, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), - TotalTime = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified) - }); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => diff --git a/Migrations/20201112043607_Initial.cs b/Migrations/20201123042312_initial.cs similarity index 74% rename from Migrations/20201112043607_Initial.cs rename to Migrations/20201123042312_initial.cs index 78ef868..b4b9cca 100644 --- a/Migrations/20201112043607_Initial.cs +++ b/Migrations/20201123042312_initial.cs @@ -3,7 +3,7 @@ namespace Project.Migrations { - public partial class Initial : Migration + public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { @@ -375,70 +375,6 @@ protected override void Up(MigrationBuilder migrationBuilder) onDelete: ReferentialAction.Restrict); }); - migrationBuilder.InsertData( - table: "BankAccounts", - columns: new[] { "Id", "AccountId", "Ammount", "Titular", "UserId" }, - values: new object[] { 1L, "88888888", 0.1f, "Shoppify", null }); - - migrationBuilder.InsertData( - table: "ShoppingCarts", - column: "Id", - values: new object[] - { - 1L, - 2L, - 3L, - 4L, - 5L - }); - - migrationBuilder.InsertData( - table: "AspNetUsers", - columns: new[] { "Id", "AccessFailedCount", "ConcurrencyStamp", "Discriminator", "Email", "EmailConfirmed", "LockoutEnabled", "LockoutEnd", "NormalizedEmail", "NormalizedUserName", "PasswordHash", "PhoneNumber", "PhoneNumberConfirmed", "SecurityStamp", "TwoFactorEnabled", "UserName", "AccountID", "Active", "City", "Info", "LastName", "Name", "ShoppingCartId" }, - values: new object[] { "1", 0, "37d27f62-a90d-4e21-bbf0-542530b43346", "User", "a.hernandez@mail.com", false, false, null, null, null, null, "55123456", false, "5e0d2604-bad3-46a2-a789-76940f1ad791", false, "AHernandez", 0L, false, "San Miguel, La Habana", "Los mejores productos", "Hernandez", "Adrian", 1L }); - - migrationBuilder.InsertData( - table: "AspNetUsers", - columns: new[] { "Id", "AccessFailedCount", "ConcurrencyStamp", "Discriminator", "Email", "EmailConfirmed", "LockoutEnabled", "LockoutEnd", "NormalizedEmail", "NormalizedUserName", "PasswordHash", "PhoneNumber", "PhoneNumberConfirmed", "SecurityStamp", "TwoFactorEnabled", "UserName", "AccountID", "Active", "City", "Info", "LastName", "Name", "ShoppingCartId" }, - values: new object[] { "2", 0, "af54c1ce-747b-40c1-b7bf-e622eb80b886", "User", "c.olavarrieta@mail.com", false, false, null, null, null, null, "54321678", false, "afb475a3-7568-4f8d-b53e-1289d6230b4e", false, "Claudita", 0L, false, "Regla, La Habana", "Los mejores productos", "Olavarrieta", "Claudia", 2L }); - - migrationBuilder.InsertData( - table: "AspNetUsers", - columns: new[] { "Id", "AccessFailedCount", "ConcurrencyStamp", "Discriminator", "Email", "EmailConfirmed", "LockoutEnabled", "LockoutEnd", "NormalizedEmail", "NormalizedUserName", "PasswordHash", "PhoneNumber", "PhoneNumberConfirmed", "SecurityStamp", "TwoFactorEnabled", "UserName", "AccountID", "Active", "City", "Info", "LastName", "Name", "ShoppingCartId" }, - values: new object[] { "3", 0, "371a7def-4289-40c2-9579-0b16b6ed8a00", "User", "m.valdivie@mail.com", false, false, null, null, null, null, "54781698", false, "8ae8f950-278c-438e-b523-86c8cfaa2599", false, "marcOS", 0L, false, "Cienfuegos", "Los mejores productos", "Valdivie", "Marcos", 3L }); - - migrationBuilder.InsertData( - table: "Products", - columns: new[] { "Id", "Active", "Ammount", "Category", "Description", "IlicitContent", "Images", "Name", "Price", "Rating", "UserId" }, - values: new object[,] - { - { 1L, true, 5, 10, null, false, "main-product01.jpg", "Shoe", 34.5m, 3, "1" }, - { 4L, true, 8, 10, null, false, "product04.jpg", "Blue Shoe", 34.5m, 3, "1" }, - { 2L, true, 3, 1, null, false, "banner01.jpg", "Brown Bag", 20.5m, 4, "2" }, - { 5L, true, 1, 10, null, false, "product05.jpg", "Black Heels", 39.5m, 4, "2" }, - { 3L, true, 2, 1, null, false, "product03.jpg", "Wallet", 10.5m, 5, "3" }, - { 6L, true, 4, 1, null, false, "product06.jpg", "Work Bag", 15m, 5, "3" } - }); - - migrationBuilder.InsertData( - table: "Reviews", - columns: new[] { "ProductId", "UserId", "Active", "Date", "Rating", "ReviewText" }, - values: new object[,] - { - { 1L, "3", false, new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), 3, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." }, - { 4L, "2", false, new DateTime(2020, 2, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), 2, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." }, - { 2L, "1", false, new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), 3, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." }, - { 2L, "2", false, new DateTime(2020, 1, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), 5, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." }, - { 5L, "1", false, new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), 3, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." }, - { 3L, "1", false, new DateTime(2019, 12, 13, 0, 0, 0, 0, DateTimeKind.Unspecified), 4, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." }, - { 6L, "1", false, new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), 1, "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." } - }); - - migrationBuilder.InsertData( - table: "Sales", - columns: new[] { "Id", "Active", "Ammount", "Date", "Discriminator", "Import", "ProductId", "User_Buy_ID", "User_Sale_ID", "ActualPrice", "ActualUser", "InitialPrice", "InitialTime", "TotalTime" }, - values: new object[] { 1L, true, 1, new DateTime(2020, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), "Auction", 0m, 6L, null, "3", 14m, "2", 14m, new DateTime(2020, 7, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified) }); - migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", diff --git a/Migrations/ApplicationDBContextModelSnapshot.cs b/Migrations/ApplicationDBContextModelSnapshot.cs index 2cb55ec..0ad3056 100644 --- a/Migrations/ApplicationDBContextModelSnapshot.cs +++ b/Migrations/ApplicationDBContextModelSnapshot.cs @@ -245,15 +245,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); b.ToTable("BankAccounts"); - - b.HasData( - new - { - Id = 1L, - AccountId = "88888888", - Ammount = 0.1f, - Titular = "Shoppify" - }); }); modelBuilder.Entity("Project.Models.Notification", b => @@ -328,86 +319,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); b.ToTable("Products"); - - b.HasData( - new - { - Id = 1L, - Active = true, - Ammount = 5, - Category = 10, - IlicitContent = false, - Images = "main-product01.jpg", - Name = "Shoe", - Price = 34.5m, - Rating = 3, - UserId = "1" - }, - new - { - Id = 2L, - Active = true, - Ammount = 3, - Category = 1, - IlicitContent = false, - Images = "banner01.jpg", - Name = "Brown Bag", - Price = 20.5m, - Rating = 4, - UserId = "2" - }, - new - { - Id = 3L, - Active = true, - Ammount = 2, - Category = 1, - IlicitContent = false, - Images = "product03.jpg", - Name = "Wallet", - Price = 10.5m, - Rating = 5, - UserId = "3" - }, - new - { - Id = 4L, - Active = true, - Ammount = 8, - Category = 10, - IlicitContent = false, - Images = "product04.jpg", - Name = "Blue Shoe", - Price = 34.5m, - Rating = 3, - UserId = "1" - }, - new - { - Id = 5L, - Active = true, - Ammount = 1, - Category = 10, - IlicitContent = false, - Images = "product05.jpg", - Name = "Black Heels", - Price = 39.5m, - Rating = 4, - UserId = "2" - }, - new - { - Id = 6L, - Active = true, - Ammount = 4, - Category = 1, - IlicitContent = false, - Images = "product06.jpg", - Name = "Work Bag", - Price = 15m, - Rating = 5, - UserId = "3" - }); }); modelBuilder.Entity("Project.Models.ProductInCart", b => @@ -456,71 +367,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("UserId"); b.ToTable("Reviews"); - - b.HasData( - new - { - ProductId = 2L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 3L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 13, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 4, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 2L, - UserId = "2", - Active = false, - Date = new DateTime(2020, 1, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 5, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 6L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 1, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 4L, - UserId = "2", - Active = false, - Date = new DateTime(2020, 2, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 2, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 1L, - UserId = "3", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }, - new - { - ProductId = 5L, - UserId = "1", - Active = false, - Date = new DateTime(2019, 12, 26, 0, 0, 0, 0, DateTimeKind.Unspecified), - Rating = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." - }); }); modelBuilder.Entity("Project.Models.Sale", b => @@ -578,28 +424,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); b.ToTable("ShoppingCarts"); - - b.HasData( - new - { - Id = 1L - }, - new - { - Id = 2L - }, - new - { - Id = 3L - }, - new - { - Id = 4L - }, - new - { - Id = 5L - }); }); modelBuilder.Entity("Project.Models.UserInAuction", b => @@ -658,71 +482,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("ShoppingCartId"); b.HasDiscriminator().HasValue("User"); - - b.HasData( - new - { - Id = "1", - AccessFailedCount = 0, - ConcurrencyStamp = "37d27f62-a90d-4e21-bbf0-542530b43346", - Email = "a.hernandez@mail.com", - EmailConfirmed = false, - LockoutEnabled = false, - PhoneNumber = "55123456", - PhoneNumberConfirmed = false, - SecurityStamp = "5e0d2604-bad3-46a2-a789-76940f1ad791", - TwoFactorEnabled = false, - UserName = "AHernandez", - AccountID = 0L, - Active = false, - City = "San Miguel, La Habana", - Info = "Los mejores productos", - LastName = "Hernandez", - Name = "Adrian", - ShoppingCartId = 1L - }, - new - { - Id = "2", - AccessFailedCount = 0, - ConcurrencyStamp = "af54c1ce-747b-40c1-b7bf-e622eb80b886", - Email = "c.olavarrieta@mail.com", - EmailConfirmed = false, - LockoutEnabled = false, - PhoneNumber = "54321678", - PhoneNumberConfirmed = false, - SecurityStamp = "afb475a3-7568-4f8d-b53e-1289d6230b4e", - TwoFactorEnabled = false, - UserName = "Claudita", - AccountID = 0L, - Active = false, - City = "Regla, La Habana", - Info = "Los mejores productos", - LastName = "Olavarrieta", - Name = "Claudia", - ShoppingCartId = 2L - }, - new - { - Id = "3", - AccessFailedCount = 0, - ConcurrencyStamp = "371a7def-4289-40c2-9579-0b16b6ed8a00", - Email = "m.valdivie@mail.com", - EmailConfirmed = false, - LockoutEnabled = false, - PhoneNumber = "54781698", - PhoneNumberConfirmed = false, - SecurityStamp = "8ae8f950-278c-438e-b523-86c8cfaa2599", - TwoFactorEnabled = false, - UserName = "marcOS", - AccountID = 0L, - Active = false, - City = "Cienfuegos", - Info = "Los mejores productos", - LastName = "Valdivie", - Name = "Marcos", - ShoppingCartId = 3L - }); }); modelBuilder.Entity("Project.Models.Auction", b => @@ -746,23 +505,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("datetime2"); b.HasDiscriminator().HasValue("Auction"); - - b.HasData( - new - { - Id = 1L, - Active = true, - Ammount = 1, - Date = new DateTime(2020, 12, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), - Import = 0m, - ProductId = 6L, - User_Sale_ID = "3", - ActualPrice = 14m, - ActualUser = "2", - InitialPrice = 14m, - InitialTime = new DateTime(2020, 7, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), - TotalTime = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified) - }); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => diff --git a/Models/ApplicationDbContext.cs b/Models/ApplicationDbContext.cs index a17648e..8ffaf51 100644 --- a/Models/ApplicationDbContext.cs +++ b/Models/ApplicationDbContext.cs @@ -77,242 +77,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithMany(r => r.UsersInAuctions) .HasForeignKey(pd => pd.AuctionId) .OnDelete(DeleteBehavior.Restrict); - - SeedData(modelBuilder); - - } - - private void SeedData(ModelBuilder modelBuilder) - { - modelBuilder.Entity().HasData( - new ShoppingCart { Id = 1 }, - new ShoppingCart { Id = 2 }, - new ShoppingCart { Id = 3 }, - new ShoppingCart { Id = 4 }, - new ShoppingCart { Id = 5 } - ); - - - - - modelBuilder.Entity().HasData( - new User - { - Id = "1", - Name = "Adrian", - LastName = "Hernandez", - UserName = "AHernandez", - Info = "Los mejores productos", - City = "San Miguel, La Habana", - PhoneNumber = "55123456", - Email = "a.hernandez@mail.com", - ShoppingCartId = 1 - - }, - new User - { - Id = "2", - Name = "Claudia", - LastName = "Olavarrieta", - UserName = "Claudita", - Info = "Los mejores productos", - City = "Regla, La Habana", - PhoneNumber = "54321678", - Email = "c.olavarrieta@mail.com", - ShoppingCartId = 2 - }, - new User - { - Id = "3", - Name = "Marcos", - LastName = "Valdivie", - UserName = "marcOS", - Info = "Los mejores productos", - City = "Cienfuegos", - PhoneNumber = "54781698", - Email = "m.valdivie@mail.com", - ShoppingCartId = 3 - } - ); - - modelBuilder.Entity().HasData( - new Product - { - Id = 1, - Name = "Shoe", - Price = 34.5M, - Images = "main-product01.jpg", - Rating = 3, - Ammount = 5, - Category = Category.Shoes, - UserId = "1", - Active = true - }, - new Product - { - Id = 2, - Name = "Brown Bag", - Price = 20.5M, - Images = "banner01.jpg", - Rating = 4, - Category = Category.Accesories, - UserId = "2", - Active = true, - Ammount = 3 - - }, - new Product - { - Id = 3, - Name = "Wallet", - Price = 10.5M, - Images = "product03.jpg", - Rating = 5, - Category = Category.Accesories, - UserId = "3", - Active = true, - Ammount = 2 - }, - new Product - { - Id = 4, - Name = "Blue Shoe", - Price = 34.5M, - Images = "product04.jpg", - Rating = 3, - Category = Category.Shoes, - UserId = "1", - Active = true, - Ammount = 8 - }, - new Product - { - Id = 5, - Name = "Black Heels", - Price = 39.5M, - Images = "product05.jpg", - Rating = 4, - Category = Category.Shoes, - UserId = "2", - Active = true, - Ammount = 1 - - }, - new Product - { - Id = 6, - Name = "Work Bag", - Price = 15M, - Images = "product06.jpg", - Rating = 5, - Category = Category.Accesories, - UserId = "3", - Active = true, - Ammount = 4 - - }); - modelBuilder.Entity().HasData( - new Review - { - UserId = "1", - ProductId = 2, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 3, - Date = new DateTime(2019, 12, 26) - - }, - new Review - { - UserId = "1", - ProductId = 3, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 4, - Date = new DateTime(2019, 12, 13) - }, - new Review - { - UserId = "2", - ProductId = 2, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 5, - Date = new DateTime(2020, 1, 7) - }, - new Review - { - UserId = "1", - ProductId = 6, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 1, - Date = new DateTime(2019, 12, 26) - }, - new Review - { - UserId = "2", - ProductId = 4, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 2, - Date = new DateTime(2020, 2, 10) - }, - new Review - { - UserId = "3", - ProductId = 1, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 3, - Date = new DateTime(2019, 12, 26) - }, new Review - { - UserId = "1", - ProductId = 5, - ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + - " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + - " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", - Rating = 3, - Date = new DateTime(2019, 12, 26) - } - - ); - - - modelBuilder.Entity().HasData( - new Auction - { - Active = true, - ActualPrice = 14, - ActualUser = "2", - Ammount = 1, - Date = new DateTime(2020, 12, 24), - Id = 1, - InitialPrice = 14, - InitialTime = new DateTime(2020, 07, 15), - ProductId = 6, - User_Sale_ID = "3", - }); - - var shoppifyBankAccount = new BankAccount() - { - Id = 1, - AccountId = "88888888", - Titular = "Shoppify", - Ammount = 0.1F - }; - - modelBuilder.Entity().HasData(shoppifyBankAccount); - - - } diff --git a/Models/Seed.cs b/Models/Seed.cs new file mode 100644 index 0000000..46ab32d --- /dev/null +++ b/Models/Seed.cs @@ -0,0 +1,284 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Project.Models +{ + static public class Seed + { + static public void AddData(ApplicationDBContext context, UserManager userManager, RoleManager roleManager) + { + if (context.Database.GetPendingMigrations().Any()) + context.Database.Migrate(); + else return; + + context.ShoppingCarts.Add(new ShoppingCart { }); + context.ShoppingCarts.Add(new ShoppingCart { }); + context.ShoppingCarts.Add(new ShoppingCart { }); + context.ShoppingCarts.Add(new ShoppingCart { }); + context.ShoppingCarts.Add(new ShoppingCart { }); + context.SaveChanges(); + List sh = context.ShoppingCarts.Select(p => p.Id).ToList(); + + context.Users.Add(new User + { + Id = "1", + Name = "Adrian", + LastName = "Hernandez", + UserName = "AHernandez", + Info = "Los mejores productos", + City = "San Miguel, La Habana", + PhoneNumber = "55123456", + Email = "a.hernandez@mail.com", + ShoppingCartId = sh[0] + }); + context.Users.Add(new User + { + Id = "2", + Name = "Claudia", + LastName = "Olavarrieta", + UserName = "Claudita", + Info = "Los mejores productos", + City = "Regla, La Habana", + PhoneNumber = "54321678", + Email = "c.olavarrieta@mail.com", + ShoppingCartId = sh[1] + }); + context.Users.Add(new User + { + Id = "3", + Name = "Marcos", + LastName = "Valdivie", + UserName = "marcOS", + Info = "Los mejores productos", + City = "Cienfuegos", + PhoneNumber = "54781698", + Email = "m.valdivie@mail.com", + ShoppingCartId = sh[2] + }); + var admin = new User + { + Active = true, + City = "Habana", + Email = "admin@mail.com", + Id = "4", + Info = "Administrator", + LastName = "Admin", + Name = "Admin", + NormalizedEmail = "ADMIN@MAIL.COM", + NormalizedUserName = "ADMIN", + PhoneNumber = "12345678", + UserName = "Admin", + SecurityStamp = Guid.NewGuid().ToString(), + LockoutEnabled = false, + ShoppingCartId = sh[3] + }; + userManager.CreateAsync(admin, "Password123!").Wait(); + var moderator = new User + { + Active = true, + City = "Habana", + Email = "moderator@mail.com", + Id = "5", + Info = "Moderator", + LastName = "Moderator", + Name = "Moderator", + NormalizedEmail = "MODERATOR@MAIL.COM", + NormalizedUserName = "MODERATOR", + PhoneNumber = "23456789", + UserName = "Moderator", + SecurityStamp = Guid.NewGuid().ToString(), + LockoutEnabled = false, + ShoppingCartId = sh[4] + }; + userManager.CreateAsync(moderator, "Password123!").Wait(); + + context.Products.Add(new Product + { + Name = "Shoe", + Price = 34.5M, + Images = "main-product01.jpg", + Rating = 3, + Ammount = 5, + Category = Category.Shoes, + UserId = "1", + Active = true + }); + context.SaveChanges(); + context.Products.Add(new Product + { + Name = "Brown Bag", + Price = 20.5M, + Images = "banner01.jpg", + Rating = 4, + Category = Category.Accesories, + UserId = "2", + Active = true, + Ammount = 3 + }); + context.SaveChanges(); + context.Products.Add(new Product + { + Name = "Wallet", + Price = 10.5M, + Images = "product03.jpg", + Rating = 5, + Category = Category.Accesories, + UserId = "3", + Active = true, + Ammount = 2 + }); + context.SaveChanges(); + context.Products.Add(new Product + { + Name = "Blue Shoe", + Price = 34.5M, + Images = "product04.jpg", + Rating = 3, + Category = Category.Shoes, + UserId = "1", + Active = true, + Ammount = 8 + }); + context.SaveChanges(); + context.Products.Add(new Product + { + Name = "Black Heels", + Price = 39.5M, + Images = "product05.jpg", + Rating = 4, + Category = Category.Shoes, + UserId = "2", + Active = true, + Ammount = 1 + }); + context.SaveChanges(); + context.Products.Add(new Product + { + Name = "Work Bag", + Price = 15M, + Images = "product06.jpg", + Rating = 5, + Category = Category.Accesories, + UserId = "3", + Active = true, + Ammount = 4 + }); + context.SaveChanges(); + List pid = context.Products.Select(p => p.Id).ToList(); + + context.Reviews.Add(new Review + { + UserId = "1", + ProductId = pid[1], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 3, + Date = new DateTime(2019, 12, 26) + }); + context.Reviews.Add(new Review + { + UserId = "1", + ProductId = pid[2], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 4, + Date = new DateTime(2019, 12, 13) + }); + context.Reviews.Add(new Review + { + UserId = "2", + ProductId = pid[1], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 5, + Date = new DateTime(2020, 1, 7) + }); + context.Reviews.Add(new Review + { + UserId = "1", + ProductId = pid[5], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 1, + Date = new DateTime(2019, 12, 26) + }); + context.Reviews.Add(new Review + { + UserId = "2", + ProductId = pid[3], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 2, + Date = new DateTime(2020, 2, 10) + }); + context.Reviews.Add(new Review + { + UserId = "3", + ProductId = pid[0], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 3, + Date = new DateTime(2019, 12, 26) + }); + context.Reviews.Add(new Review + { + UserId = "1", + ProductId = pid[4], + ReviewText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit," + + " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam," + + " quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", + Rating = 3, + Date = new DateTime(2019, 12, 26) + }); + + context.Auctions.Add(new Auction + { + Active = true, + ActualPrice = 14, + ActualUser = "2", + Ammount = 1, + Date = new DateTime(2020, 12, 24), + InitialPrice = 14, + InitialTime = new DateTime(2020, 07, 15), + ProductId = pid[5], + User_Sale_ID = "3", + }); + + context.BankAccounts.Add(new BankAccount + { + AccountId = "88888888", + Titular = "Shoppify", + Ammount = 0.1F + }); + + { + IdentityRole role = new IdentityRole(); + role.Name = "Admin"; + role.NormalizedName = "ADMIN"; + roleManager.CreateAsync(role).Wait(); + } + { + IdentityRole role = new IdentityRole(); + role.Name = "Moderator"; + role.NormalizedName = "MODERATOR"; + roleManager.CreateAsync(role).Wait(); + } + + userManager.AddToRoleAsync(admin, "Admin").Wait(); + userManager.AddToRoleAsync(moderator, "Moderator").Wait(); + + context.SaveChanges(); + } + } +} + diff --git a/Program.cs b/Program.cs index 1e510b4..77b21da 100644 --- a/Program.cs +++ b/Program.cs @@ -17,20 +17,7 @@ public class Program public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); - using(var scope = host.Services.CreateScope()) - { - var serviceProvider = scope.ServiceProvider; - try - { - var userManager = serviceProvider.GetRequiredService>(); - var roleManager = serviceProvider.GetRequiredService>(); - var dbcontext = serviceProvider.GetRequiredService(); - Security.SecuritySeed.SeedData(userManager, roleManager,dbcontext); - } - catch { } - } host.Run(); - } public static IHostBuilder CreateHostBuilder(string[] args) => diff --git a/Security/SecuritySeed.cs b/Security/SecuritySeed.cs deleted file mode 100644 index 653904b..0000000 --- a/Security/SecuritySeed.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Project.Models; - -namespace Project.Security -{ - public class SecuritySeed - { - - public static void SeedData(UserManager userManager, RoleManager roleManager,ApplicationDBContext context) - { - SeedRoles(roleManager); - SeedUsers(userManager,context); - } - - private static void SeedUsers(UserManager userManager, ApplicationDBContext context) - { - ShoppingCartRepository shoppingCart = new ShoppingCartRepository(context); - - if(userManager.FindByNameAsync("Admin").Result == null) - { - var s = shoppingCart.AddEntity(new ShoppingCart()); - var user = new User - { - Active = true, - City = "Habana", - Email = "admin@mail.com", - Id = "4", - Info = "Administrator", - LastName = "Admin", - Name = "Admin", - NormalizedEmail = "ADMIN@MAIL.COM", - NormalizedUserName = "ADMIN", - PhoneNumber = "12345678", - UserName = "Admin", - SecurityStamp = Guid.NewGuid().ToString(), - LockoutEnabled = false, - ShoppingCartId = s.Id - }; - try - { - IdentityResult identityResult = userManager.CreateAsync(user, "Password123!").Result; - if (identityResult.Succeeded) - { - userManager.AddToRoleAsync(user, "Admin").Wait(); - } - } - catch (Exception e) - { - var d = e.InnerException; - } - } - if (userManager.FindByNameAsync("Moderator").Result == null) - { - var s2 = shoppingCart.AddEntity(new ShoppingCart()); - var moderator = new User - { - Active = true, - City = "Habana", - Email = "moderator@mail.com", - Id = "5", - Info = "Moderator", - LastName = "Moderator", - Name = "Moderator", - NormalizedEmail = "MODERATOR@MAIL.COM", - NormalizedUserName = "MODERATOR", - PhoneNumber = "23456789", - UserName = "Moderator", - SecurityStamp = Guid.NewGuid().ToString(), - LockoutEnabled = false, - ShoppingCartId = s2.Id - }; - - try - { - IdentityResult identityResult = userManager.CreateAsync(moderator, "Password123!").Result; - if (identityResult.Succeeded) - { - userManager.AddToRoleAsync(moderator, "Moderator").Wait(); - } - } - catch (Exception e) - { - var d = e.InnerException; - } - } - } - - private static void SeedRoles(RoleManager roleManager) - { - if (!roleManager.RoleExistsAsync("Admin").Result) - { - IdentityRole role = new IdentityRole(); - role.Name = "Admin"; - role.NormalizedName = "ADMIN"; - IdentityResult identityResult = roleManager.CreateAsync(role).Result; - } - if (!roleManager.RoleExistsAsync("Moderator").Result) - { - IdentityRole role = new IdentityRole(); - role.Name = "Moderator"; - role.NormalizedName = "MODERATOR"; - IdentityResult identityResult = roleManager.CreateAsync(role).Result; - } - } - - - - } -} diff --git a/Startup.cs b/Startup.cs index 248d225..5ea11b3 100644 --- a/Startup.cs +++ b/Startup.cs @@ -84,7 +84,8 @@ public void ConfigureServices(IServiceCollection services) } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IServiceProvider serviceProvider,UserManager userManager, RoleManager roleManager) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, + ApplicationDBContext context, UserManager userManager, RoleManager roleManager) { if (env.IsDevelopment()) { @@ -113,9 +114,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IServiceP pattern: "{controller=Home}/{action=Index}/{id?}"); }); - - //seed.SeedAdminUser(); - + Seed.AddData(context, userManager, roleManager); } } }