Example #1
0
        public IActionResult All()
        {
            var currentUserId  = this.userService.GetUserId(this.User.Identity.Name);
            var productsInCart = this.cartService.GetAllProductsForCartViewModel(currentUserId);

            var complexModel = new ComplexModel <List <BuyProductInputModel>, List <ProductCartViewModel> >
            {
                ViewModel = productsInCart
            };

            if (TempData.ContainsKey(GlobalConstants.ErrorsFromPOSTRequest))
            {
                //Merge model states
                ModelStateHelper.MergeModelStates(TempData, this.ModelState);
            }

            if (this.TempData[GlobalConstants.InputModelFromPOSTRequestType]?.ToString() == $"List<{nameof(BuyProductInputModel)}>")
            {
                complexModel.InputModel = JsonSerializer.Deserialize <List <BuyProductInputModel> >(this.TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString());
            }

            complexModel.ViewModel
            .OrderBy(x => x.Id)
            .ToList();

            //Validate if quantity for one of the products exceeds the quantity in stock
            for (int i = 0; i < complexModel.ViewModel.Count; i++)
            {
                var productViewModel = complexModel.ViewModel[i];
                if (productViewModel.QuantityInStock < productViewModel.Quantity)
                {
                    this.ModelState.AddModelError($"InputModel[{i}].Quantity", "This product's selected quantity is more than the available quantity in stock.");
                    if (this.ViewData["CartBuyButtonErrorForQuantity"] == null)
                    {
                        this.ViewData["CartBuyButtonErrorForQuantity"] = true;
                    }
                }
            }

            return(this.View(complexModel));
        }
Example #2
0
        public IActionResult Checkout()
        {
            var currentUserId = this.userService.GetUserId(this.User.Identity.Name);

            var cardProducts = this.cartService.GetAllProductsForCheckoutViewModel(currentUserId);

            //Check if the user has any products in their cart
            if (cardProducts.Count == 0)
            {
                //Set notification
                NotificationHelper.SetNotification(TempData, NotificationType.Error, "You do not have any products in your cart");

                return(this.RedirectToAction("All", "Carts"));
            }

            var checkoutViewModel = new CheckoutViewModel
            {
                ProductsInfo   = cardProducts,
                TotalPrice     = cardProducts.Sum(x => x.SinglePrice * x.Quantity),
                Countries      = this.countryService.GetAllCountries(),
                PaymentMethods = this.paymentMethodService.GetAllPaymentMethods()
            };

            var complexModel = new ComplexModel <CheckoutInputModel, CheckoutViewModel>
            {
                ViewModel = checkoutViewModel
            };

            if (this.TempData[GlobalConstants.ErrorsFromPOSTRequest] != null)
            {
                ModelStateHelper.MergeModelStates(this.TempData, this.ModelState);
            }

            if (this.TempData[GlobalConstants.InputModelFromPOSTRequestType]?.ToString() == nameof(CheckoutInputModel))
            {
                complexModel.InputModel = JsonSerializer.Deserialize <CheckoutInputModel>(this.TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString());
            }

            return(this.View(complexModel));
        }
        public HttpResponseMessage UpdateCustomer(HttpRequestMessage request, [FromBody] CustomerMaintenanceDTO customerDTO)
        {
            TransactionalInformation transaction;

            CustomerMaintenanceViewModel customerMaintenanceViewModel = new CustomerMaintenanceViewModel();

            if (!ModelState.IsValid)
            {
                var errors = ModelState.Errors();
                customerMaintenanceViewModel.ReturnMessage    = ModelStateHelper.ReturnErrorMessages(errors);
                customerMaintenanceViewModel.ValidationErrors = ModelStateHelper.ReturnValidationErrors(errors);
                customerMaintenanceViewModel.ReturnStatus     = false;
                var badresponse = Request.CreateResponse <CustomerMaintenanceViewModel>(HttpStatusCode.BadRequest, customerMaintenanceViewModel);
                return(badresponse);
            }

            Customer customer = new Customer();

            ModelStateHelper.UpdateViewModel(customerDTO, customer);

            CustomerApplicationService customerApplicationService = new CustomerApplicationService(customerDataService);

            customerApplicationService.UpdateCustomer(customer, out transaction);

            customerMaintenanceViewModel.Customer         = customer;
            customerMaintenanceViewModel.ReturnStatus     = transaction.ReturnStatus;
            customerMaintenanceViewModel.ReturnMessage    = transaction.ReturnMessage;
            customerMaintenanceViewModel.ValidationErrors = transaction.ValidationErrors;

            if (transaction.ReturnStatus == false)
            {
                var badresponse = Request.CreateResponse <CustomerMaintenanceViewModel>(HttpStatusCode.BadRequest, customerMaintenanceViewModel);
                return(badresponse);
            }
            else
            {
                var response = Request.CreateResponse <CustomerMaintenanceViewModel>(HttpStatusCode.Created, customerMaintenanceViewModel);
                return(response);
            }
        }
Example #4
0
        public async Task <IActionResult> Create([Bind("FirstName, LastName, PersonTitleId")] MedicalTrialPrincipalInvestigator investigator)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(investigator);
                    await _context.SaveChangesAsync();

                    return(Json(new { result = "ok" }));
                }
                else
                {
                    Hashtable errors = ModelStateHelper.Errors(ModelState);
                    return(Json(new { success = false, errors }));
                }
            }
            catch (DbUpdateException)
            {
                return(null);
            }
        }
Example #5
0
        public async Task <IActionResult> EditPrincipalInvestigator(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var investigator = await _context.MedicalTrialsPrincipalInvestigators
                               .AsNoTracking()
                               .SingleOrDefaultAsync(m => m.ID == id);

            investigator.FirstName = Request.Form["Name"];
            investigator.LastName  = Request.Form["Description"];
            int personTitleId = string.IsNullOrEmpty(Request.Form["PersonTitleId"]) ? 0 : Int32.Parse(Request.Form["PersonTitleId"]);

            investigator.PersonTitleId = personTitleId;

            if (TryValidateModel(investigator))
            {
                try
                {
                    _context.MedicalTrialsPrincipalInvestigators.Update(investigator);
                    _context.SaveChanges();
                }
                catch (DbUpdateException /* ex */)
                {
                    ModelState.AddModelError("", "Unable to save changes. " +
                                             "Try again, and if the problem persists, " +
                                             "see your system administrator.");
                }
            }
            else
            {
                Hashtable errors = ModelStateHelper.Errors(ModelState);
                return(Json(new { success = false, errors }));
            }

            return(Json(new { result = "ok" }));
        }
 public async Task<IActionResult> Create(CaseReportFormCategory formCategory)
 {
     try
     {
         formCategory.Name = Request.Form["Name"];
         if (ModelState.IsValid)
         {
             _context.Add(formCategory);
             await _context.SaveChangesAsync();
             return Json(new { result = "ok" });
         }
         else
         {
             Hashtable errors = ModelStateHelper.Errors(ModelState);
             return Json(new { success = false, errors });
         }
     }
     catch (DbUpdateException)
     {
         return null;
     }
 }
Example #7
0
        private bool ValidateContestDetailModel(ContestDetailModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            bool validationPassed = TryValidateModel(model);

            if (!validationPassed)
            {
                ViewBag.TitleErrorMessage                 = ModelStateHelper.GetFirstError(ModelState, "Title");
                ViewBag.CreatorErrorMessage               = ModelStateHelper.GetFirstError(ModelState, "Creator");
                ViewBag.UsergroupNameErrorMessage         = ModelStateHelper.GetFirstError(ModelState, "UsergroupName");
                ViewBag.StartTimeStringErrorMessage       = ModelStateHelper.GetFirstError(ModelState, "StartTimeString");
                ViewBag.EndTimeStringErrorMessage         = ModelStateHelper.GetFirstError(ModelState, "EndTimeString");
                ViewBag.ParticipationModeNameErrorMessage = ModelStateHelper.GetFirstError(ModelState, "ParticipationModeName");
                ViewBag.AuthorizationModeNameErrorMessage = ModelStateHelper.GetFirstError(ModelState, "AuthorizationModeName");
            }

            if (string.Compare(model.AuthorizationModeName, "Protected", true) == 0 &&
                (string.IsNullOrEmpty(model.Password) || model.Password.Length < 6))
            {
                validationPassed             = false;
                ViewBag.PasswordErrorMessage = "Password should be at least 6 characters long.";
            }

            DateTime startTime = DateTime.Parse(model.StartTimeString);
            DateTime endTime   = DateTime.Parse(model.EndTimeString);

            if (endTime <= startTime)
            {
                validationPassed = false;
                ViewBag.EndTimeStringErrorMessage = "End time must be later than start time.";
            }

            return(validationPassed);
        }
        public IActionResult Edit(string categoryId)
        {
            EditCategoryInputModel inputModel;

            if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null)
            {
                ModelStateHelper.MergeModelStates(TempData, this.ModelState);
                inputModel = JsonSerializer.Deserialize <EditCategoryInputModel>(TempData[GlobalConstants.InputModelFromPOSTRequest].ToString());
            }
            else
            {
                //Check if category exists
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    return(this.NotFound());
                }

                var category = this.categoryService.GetCategoryById(categoryId);
                inputModel = this.mapper.Map <EditCategoryInputModel>(category);
            }

            return(this.View(inputModel));
        }
        public async Task <IActionResult> Create([Bind("CategoryName")] DiagnosisCategory diagnosisCategory)
        {
            try
            {
                this.CheckFieldUniqueness(_context.DiagnosisCategories, "CategoryName", diagnosisCategory.CategoryName);
                if (ModelState.IsValid)
                {
                    _context.Add(diagnosisCategory);
                    await _context.SaveChangesAsync();

                    return(Json(new { result = "ok" }));
                }
                else
                {
                    Hashtable errors = ModelStateHelper.Errors(ModelState);
                    return(Json(new { success = false, errors }));
                }
            }
            catch (DbUpdateException)
            {
                return(null);
            }
        }
        public async Task <IActionResult> Create(PatientVisit patientVisit)
        {
            _patientVisitManager = new PatientVisitManager(_context, ViewBag, Request.Form);

            InitViewBags();

            var itemsToSave = _patientVisitManager.SavePatientExaminationsForVisit(patientVisit);

            this.CheckIfAtLeastOneIsSelected(itemsToSave.Count);

            if (ModelState.IsValid)
            {
                _context.Add(patientVisit);
                _context.PatientExaminations.AddRange(itemsToSave);
                await _context.SaveChangesAsync();
            }
            else
            {
                Hashtable errors = ModelStateHelper.Errors(ModelState);
                return(Json(new { success = false, errors }));
            }
            return(Json(new { result = "ok" }));
        }
        public async Task <IActionResult> Create([Bind("Name")] SideEffect sideEffect)
        {
            try
            {
                this.CheckFieldUniqueness(_context.SideEffects, "Name", sideEffect.Name);
                if (ModelState.IsValid)
                {
                    _context.Add(sideEffect);
                    await _context.SaveChangesAsync();

                    return(Json(new { result = "ok" }));
                }
                else
                {
                    Hashtable errors = ModelStateHelper.Errors(ModelState);
                    return(Json(new { success = false, errors }));
                }
            }
            catch (DbUpdateException)
            {
                return(null);
            }
        }
        public async Task <IActionResult> All()
        {
            var currentUserId  = this.userService.GetUserId(this.User.Identity.Name);
            var productsInCart = this.cartService.GetAllProductsForCartViewModel(currentUserId);

            var complexModel = new ComplexModel <List <BuyProductInputModel>, List <ProductCartViewModel> >
            {
                ViewModel = productsInCart
            };

            if (TempData.ContainsKey(GlobalConstants.ErrorsFromPOSTRequest))
            {
                //Merge model states
                ModelStateHelper.MergeModelStates(TempData, this.ModelState);
            }

            if (this.TempData[GlobalConstants.InputModelFromPOSTRequestType]?.ToString() == $"List<{nameof(BuyProductInputModel)}>")
            {
                complexModel.InputModel = JsonSerializer.Deserialize <List <BuyProductInputModel> >(this.TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString());
            }

            return(this.View(complexModel));
        }
        public IActionResult EditCategoryItem(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var foundItem = _context.CaseReportFormCategories
                                  .Where(crfc => crfc.ID == id)
                                  .FirstOrDefault();

            if (foundItem == null)
            {
                return NotFound();
            }
            foundItem.Name = Request.Form["Name"];
            if (TryValidateModel(foundItem))
            {
                try
                {
                    _context.Update(foundItem);
                    _context.SaveChanges();
                }
                catch (DbUpdateException /* ex */)
                {
                    ModelState.AddModelError("", "Unable to save changes. " +
                        "Try again, and if the problem persists, " +
                        "see your system administrator.");
                }
            }
            else
            {
                Hashtable errors = ModelStateHelper.Errors(ModelState);
                return Json(new { success = false, errors });
            }

            return Json(new { result = "ok" });
        }
        public async Task <IActionResult> Edit(EditCategoryInputModel inputModel)
        {
            if (this.categoryService.CategoryExists(inputModel.Id, true) == false)
            {
                this.ModelState.AddModelError("Id", "This category doesn't exist.");
            }

            if (this.categoryService.CategoryNameExists(inputModel.Name, inputModel.Id, true) == true)
            {
                this.ModelState.AddModelError("Name", "This category name has been already taken. Choose a different one");
            }

            if (this.ModelState.IsValid == false)
            {
                TempData[GlobalConstants.ErrorsFromPOSTRequest]     = ModelStateHelper.SerialiseModelState(this.ModelState);
                TempData[GlobalConstants.InputModelFromPOSTRequest] = JsonSerializer.Serialize(inputModel);

                return(this.RedirectToAction(nameof(Edit), new { categoryId = inputModel.Id }));
            }

            await this.categoryService.EditAsync(inputModel.Id, inputModel.Name);

            return(this.RedirectToAction(nameof(All)));
        }
        public async Task <IActionResult> Remove(string productId, string errorReturnUrl)
        {
            if (this.productService.ProductExistsById(productId) == false)
            {
                this.ModelState.AddModelError("removeProduct_productId", "This product doesn't exist");
            }

            if (this.ModelState.IsValid == false)
            {
                //Add notification
                NotificationHelper.SetNotification(TempData, NotificationType.Error, "An error occured while removing product. Product wasn't removed");

                //Store needed info for get request in TempData
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.Redirect(errorReturnUrl));
            }

            await this.productService.RemoveProductAsync(productId);

            NotificationHelper.SetNotification(TempData, NotificationType.Success, "Successfully remove product.");

            return(this.RedirectToAction("All", "Products", new { area = "" }));
        }
        public async Task <IActionResult> Edit(EditProductInputModel inputModel)
        {
            //Set input model short description
            inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40);

            //Store input model for passing in get action
            TempData[GlobalConstants.InputModelFromPOSTRequest]     = JsonSerializer.Serialize(inputModel);
            TempData[GlobalConstants.InputModelFromPOSTRequestType] = nameof(EditProductInputModel);

            //Check without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Edit), "Products", new { productId = inputModel.Id }));
            }

            //Check if product with this id exists
            if (this.productService.ProductExistsById(inputModel.Id) == false)
            {
                this.ModelState.AddModelError("", "The product that you are trying to edit doesn't exist.");
            }

            var productId = inputModel.Id;

            //Check if product with this model or name exist and it is not the product that is currently being edited
            if (this.productService.ProductExistsByModel(inputModel.Model, productId) == true)
            {
                this.ModelState.AddModelError("Model", "Product with this model already exists.");
            }
            if (this.productService.ProductExistsByName(inputModel.Name, productId))
            {
                this.ModelState.AddModelError("Name", "Product with this name already exists.");
            }

            //Check if there is a main image, regardless of the imageMode
            if ((inputModel.MainImage == null && inputModel.ImagesAsFileUploads == false) || (inputModel.MainImageUploadInfo.ImageUpload == null && inputModel.MainImageUploadInfo.IsBeingModified && inputModel.ImagesAsFileUploads == true))
            {
                this.ModelState.AddModelError("", "Main image is required");

                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Edit), "Products", new { productId = productId }));
            }

            //CHECK THE IMAGES LINKS
            if (inputModel.ImagesAsFileUploads == false)
            {
                //Check if all of these images are unique
                if (this.productImageService.ImagesAreRepeated(inputModel.MainImage, inputModel.AdditionalImages))
                {
                    this.ModelState.AddModelError("", "There are 2 or more non-unique images");
                }

                //Check if main image is already used by OTHER products
                if (this.productImageService.ProductImageExists(inputModel.MainImage, productId) == true)
                {
                    this.ModelState.AddModelError("MainImage", "This image is already used.");
                }

                if (inputModel.AdditionalImages == null)
                {
                    inputModel.AdditionalImages = new List <string>();
                }

                //Check if any of the additional images are used by OTHER products
                for (int i = 0; i < inputModel.AdditionalImages.Count; i++)
                {
                    var additionalImage = inputModel.AdditionalImages[i];
                    if (this.productImageService.ProductImageExists(additionalImage, productId) == true)
                    {
                        this.ModelState.AddModelError($"AdditionalImages[{i}]", "This image is already used.");
                    }
                }
            }
            //CHECK IMAGES UPLOADS
            else
            {
                var mainImageUpload = inputModel.MainImageUploadInfo.ImageUpload;

                //Check main image upload extension is valid, but only if the user has actually selected a file themselves
                if (inputModel.MainImageUploadInfo.IsBeingModified && this.productImageService.ValidImageExtension(mainImageUpload) == false)
                {
                    this.ModelState.AddModelError("MainImageUploadInfo.ImageUpload", "The uploaded image is invalid");
                }

                if (inputModel.AdditionalImagesUploadsInfo == null)
                {
                    inputModel.AdditionalImagesUploadsInfo = new List <EditProductImageUploadInputModel>();
                }

                var additionalImagesUploads = inputModel.AdditionalImagesUploadsInfo
                                              .Select(x => x.ImageUpload)
                                              .Where(imageUpload => imageUpload != null)
                                              .ToList();

                //Check additional images uploads
                for (int i = 0; i < additionalImagesUploads.Count; i++)
                {
                    var imageUpload = additionalImagesUploads[i];
                    if (imageUpload != null && this.productImageService.ValidImageExtension(imageUpload) == false)
                    {
                        this.ModelState.AddModelError($"AdditionalImagesUploadsInfo[{i}].ImageUpload.", "The uploaded image is invalid");
                    }
                }
            }

            //Check if categories exist in the database or if there are even any categories for this product
            for (int i = 0; i < inputModel.CategoriesIds.Count; i++)
            {
                var categoryId = inputModel.CategoriesIds[i];
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist");
                }
            }
            if (inputModel.CategoriesIds.Count == 0)
            {
                this.ModelState.AddModelError("", "You need to add at least one category for this product");
            }

            //Check if categories exist in the database
            for (int i = 0; i < inputModel.CategoriesIds.Count; i++)
            {
                var categoryId = inputModel.CategoriesIds[i];
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist");
                }
            }

            //Check if categories are unique
            if (inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct().Count() != inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Count())
            {
                this.ModelState.AddModelError($"", "One category cannot be used multiple times.");
            }


            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Edit), "Products", new { productId = inputModel.Id }));
            }

            await this.productService.EditAsync(inputModel);

            var product = this.productService.GetProductById(inputModel.Id, false);

            await this.categoryService.EditCategoriesToProductAsync(product, inputModel.CategoriesIds);

            //Set notification
            NotificationHelper.SetNotification(this.TempData, NotificationType.Success, "Product was successfully edited");

            return(this.RedirectToAction("ProductPage", "Products", new { area = "", productId = inputModel.Id }));
        }
        public IActionResult Edit(string productId)
        {
            if (this.productService.ProductExistsById(productId) == false)
            {
                NotificationHelper.SetNotification(this.TempData, NotificationType.Error, "The product doesn't exist");

                return(this.RedirectToAction("ProductPage", "Products", new { area = "", productId = productId }));
            }

            EditProductInputModel inputModel = null;

            //Add each model state error from the last action to this one. Fill the input model with he values from the last post action
            if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null && TempData[GlobalConstants.InputModelFromPOSTRequestType]?.ToString() == nameof(EditProductInputModel))
            {
                ModelStateHelper.MergeModelStates(TempData, this.ModelState);

                var inputModelJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString();
                inputModel = JsonSerializer.Deserialize <EditProductInputModel>(inputModelJSON);
                var product = this.productService.GetProductById(productId, true);

                //Add categories names
                inputModel.CategoriesNames = new List <string>();
                var categoriesNames = this.categoryService.GetCategoryNamesFromIds(inputModel.CategoriesIds);
                inputModel.CategoriesNames.AddRange(categoriesNames);

                //Set the image path for all of the modifiedImages
                if (inputModel.MainImageUploadInfo.ModifiedImage.Id != null)
                {
                    inputModel.MainImageUploadInfo.ModifiedImage.Path = this.productImageService.GetImageById(inputModel.MainImageUploadInfo.ModifiedImage.Id).Image;
                }

                //Set isBeingModified param for mainImageUpload to false
                inputModel.MainImageUploadInfo.IsBeingModified = false;

                foreach (var additionalImageUploadInfo in inputModel.AdditionalImagesUploadsInfo)
                {
                    var modifiedImage = additionalImageUploadInfo.ModifiedImage;
                    if (modifiedImage.Id != null)
                    {
                        modifiedImage.Path = this.productImageService.GetImageById(modifiedImage.Id).Image;
                    }

                    //Set isBeingModified param for additionalImageUpload to false
                    additionalImageUploadInfo.IsBeingModified = false;
                }
            }
            //If there wasn't an error with the edit form prior to this, just fill the inputModel like normal
            else
            {
                var product = this.productService.GetProductById(productId, true);
                inputModel = this.mapper.Map <EditProductInputModel>(product);

                //Get the categories for the product
                var productCategories = this.categoryService.GetCategoriesForProduct(product.Id).ToList();
                inputModel.CategoriesIds   = productCategories.Select(x => x.Id).ToList();
                inputModel.CategoriesNames = productCategories.Select(x => x.Name).ToList();

                //Set image mode
                inputModel.ImagesAsFileUploads = false;

                //Get the main image
                var mainImage = this.productImageService.GetMainImage(productId);

                //Set main image path
                inputModel.MainImage = mainImage.Image;

                //Set main image upload info
                inputModel.MainImageUploadInfo = new EditProductImageUploadInputModel
                {
                    ImageUpload   = null,
                    ModifiedImage = new ImageIdAndPathInputModel {
                        Id = mainImage.Id, Path = mainImage.Image
                    }
                };

                //Get additional images
                var additionalImages = this.productImageService.GetAdditionalImages(productId);

                inputModel.AdditionalImages            = new List <string>();
                inputModel.AdditionalImagesUploadsInfo = new List <EditProductImageUploadInputModel>();

                //Sed additional images uploads and paths
                for (int i = 0; i < additionalImages.Count; i++)
                {
                    var image = additionalImages[i];
                    inputModel.AdditionalImages.Add(image.Image);
                    inputModel.AdditionalImagesUploadsInfo.Add(new EditProductImageUploadInputModel
                    {
                        ImageUpload   = null,
                        ModifiedImage = new ImageIdAndPathInputModel {
                            Id = image.Id, Path = image.Image
                        }
                    });
                }
            }

            //Set input model short description
            inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40);

            return(this.View(inputModel));
        }
Example #18
0
        public IActionResult Create([Bind("ID, StartDate, EndDate, PatientIds")] Report report)
        {
            if (Request.Form.Files.Count > 0)
            {
                IFormFile file = Request.Form.Files[0];

                string webRootPath = _hostingEnvironment.WebRootPath;
                Action <FileStream, IFormFile, string> readFileAction = (stream, formFile, extension) => {
                    var    reportBuilder = new CPAMortalityAuditReportBuilder(_context, stream, _logger, formFile);
                    string newPath       = Path.Combine(webRootPath, "Upload");
                    string fileExtension = Path.GetExtension(file.FileName).ToLower();
                    string fullPath      = Path.Combine(newPath, file.FileName);
                    report.InputFilePath = fullPath;
                    reportBuilder.Build();
                };
                FileImporter.Import(file, webRootPath, readFileAction);
                var reportType = _context.ReportTypes
                                 .FirstOrDefault(rt => rt.Discriminator == "CPAMortalityAudit");
                report.ReportTypeId = reportType.ID;

                _context.Reports.Update(report);
                _context.SaveChanges();
                return(Json(new { success = true, id = report.ID }));
            }
            else
            {
                var reportType = _context.ReportTypes
                                 .FirstOrDefault(rt => rt.Discriminator == Request.Form["ReportTypeID"]);
                StringValues patientIds;
                if (reportType == null)
                {
                    return(Json(new { success = false }));
                }
                var reportItems = new List <PatientReportItem>();
                if (!string.IsNullOrEmpty(Request.Form["PatientIds"]))
                {
                    patientIds = Request.Form["PatientIds"];
                }
                if (patientIds.ToList()[0] == "null")
                {
                    ModelState.AddModelError("Base", "You need to add at least one patient to this report");
                }
                if (patientIds.ToList()[0] != "null" && !string.IsNullOrEmpty(patientIds))
                {
                    var idsToFind = patientIds.ToString()
                                    .Split(",")
                                    .Select(id => Int32.Parse(id))
                                    .ToList();

                    var patients = _context.Patients.Where(p => idsToFind.Contains(p.ID));
                    foreach (var patient in patients)
                    {
                        var patientReportItem = new PatientReportItem()
                        {
                            PatientId = patient.ID
                        };
                        reportItems.Add(patientReportItem);
                    }
                }
                report.ReportTypeId       = reportType.ID;
                report.PatientReportItems = reportItems;

                if (ModelState.IsValid)
                {
                    _context.Reports.Update(report);
                    _context.SaveChanges();
                    return(Json(new { success = true, id = report.ID }));
                }
                else
                {
                    Hashtable errors = ModelStateHelper.Errors(ModelState);
                    return(Json(new { success = false, errors }));
                }
            }
        }
Example #19
0
        public IActionResult UpdatePost([FromBody] UpdatePostViewModel model)
        {
            var user = userRepository.GetApplicationUserByUsername(User.Identity.Name, true);

            if (user == null)
            {
                return(Unauthorized());
            }
            var post = postRepository.GetPostByPostId(model.PostId, true, new string[] { "CurrentVersion", "PostTags", "ExternalFiles" });

            if (post == null)
            {
                return(NotFound());
            }
            try {
                bool errors = false;
                if (model.CurrentVersion != null)
                {
                    var postVersion = postRepository.GetPostVersionByPostVersionId((int)model.CurrentVersion);
                    if (postVersion == null)
                    {
                        errors = true;
                        ModelState.AddModelError("PostVersion", "PostVersion not found");
                    }
                    post.CurrentVersion = postVersion;
                }
                if (model.AliasSet)
                {
                    post.Alias = model.Alias;
                }
                if (model.Published != null)
                {
                    post.Published = (bool)model.Published;
                    if (post.FirstPublished == null)
                    {
                        post.FirstPublished = DateTime.Now;
                    }
                }
                if (model.List != null)
                {
                    post.List = (bool)model.List;
                }
                if (model.PostTags != null)
                {
                    var newTags = new List <PostTag>();
                    var allTags = tagRepository.GetTags().ToDictionary(x => x.TagId, x => x);
                    foreach (var tag in model.PostTags)
                    {
                        if (!allTags.ContainsKey(tag))
                        {
                            return(BadRequest());
                        }
                        newTags.Add(new PostTag()
                        {
                            PostId = post.PostId, TagId = tag
                        });
                    }
                    post.PostTags = newTags;
                }
                if (errors)
                {
                    return(BadRequest(ModelStateHelper.GetModelStateErrors(ModelState)));
                }
                postRepository.UpdatePost(post);
                return(Ok(Conversions.PostViewModelFromPost(post)));
            }
            catch (Exception) {
                return(BadRequest());
            }
        }
        public async Task <IActionResult> EditReview(EditReviewInputModel inputModel, string pageFragment, string commentsPage, string commentsOrderingOption)
        {
            var productId = inputModel.ProductId;

            var commentId = inputModel.CommentId;

            //Sanitize pageFragment
            pageFragment = this.javaScriptEncoder.Encode(pageFragment);

            //Sanitize commentsPage
            if (commentsPage != null)
            {
                commentsPage = this.htmlEncoder.Encode(commentsPage);
            }


            //Store input model for passing in get action
            TempData["InputModelFromPOSTRequest"]     = JsonSerializer.Serialize(inputModel);
            TempData["InputModelFromPOSTRequestType"] = nameof(EditReviewInputModel);

            //Check if data is valid without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Add suitable model state error for UI validation
                var newModelState = new ModelStateDictionary(this.ModelState);
                foreach (var modelStateEntry in this.ModelState.Values)
                {
                    foreach (var modelStateError in modelStateEntry.Errors)
                    {
                        newModelState.AddModelError($"CommentId_{inputModel.CommentCounter}", modelStateError.ErrorMessage);
                    }
                }

                //Store needed info for get request in TempData
                TempData["ErrorsFromPOSTRequest"] = ModelStateHelper.SerialiseModelState(newModelState);

                return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsPage, commentsOrderingOption }, pageFragment));
            }

            var userId = this.userService.GetUserId(this.User.Identity.Name);

            var oldProductRating = new ProductRating();

            if (inputModel?.ProductRatingViewModel?.AverageRating > 0)
            {
                //Check if rating from this user for this product already exists
                if (this.productService.ProductRatingExists(userId, productId) == true)
                {
                    oldProductRating = this.productService.GetProductRating(userId, productId);
                }
                else
                {
                    this.ModelState.AddModelError($"Rating_{inputModel.CommentCounter}", "You have not given a review for this product!!!");
                }
            }
            else
            {
                oldProductRating = null;
            }


            var oldComment = new ProductComment();

            //Check if the comment exists and if it belongs to the current user and is for this product TODO
            if (this.productCommentService.CommentMatchesUserAndProduct(commentId, userId, productId) == false)
            {
                oldComment = null;
                this.ModelState.AddModelError($"CommentId_{inputModel.CommentCounter}", "You have not given a review with a comment for this product!!!");
            }
            else
            {
                oldComment = this.productCommentService.GetProductComment(commentId);
            }

            //Check if model state is valid after checking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData["ErrorsFromPOSTRequest"] = ModelStateHelper.SerialiseModelState(this.ModelState);

                //Reload same page with the TempData
                return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsPage, commentsOrderingOption }, pageFragment));
            }

            if (oldComment != null)
            {
                await this.productCommentService.EditCommentTextAsync(oldComment, inputModel.Text);
            }
            if (oldProductRating != null)
            {
                await this.productService.EditProductRating(oldProductRating, (double)inputModel.ProductRatingViewModel.AverageRating);
            }

            return(this.RedirectToAction("ProductPage", "Products", new { productId, toReplyComment = oldComment.Id, commentsPage, commentsOrderingOption }, pageFragment));
        }
        public async Task <IActionResult> ReplyToComment(ReplyCommentInputModel inputModel, string pageFragment, string commentsPage, string commentsOrderingOption)
        {
            var productId = inputModel.ProductId;

            var commentId = inputModel.ParentCommentId;

            //Sanitize pageFragment
            pageFragment = this.javaScriptEncoder.Encode(pageFragment);

            //Sanitize commentsPage
            if (commentsPage != null)
            {
                commentsPage = this.htmlEncoder.Encode(commentsPage);
            }

            //Check if data is valid without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store input model for passing in get action
                TempData["InputModelFromPOSTRequest"]     = JsonSerializer.Serialize(inputModel);
                TempData["InputModelFromPOSTRequestType"] = nameof(ReplyCommentInputModel);

                //Add suitable model state error for UI validation
                var newModelState = new ModelStateDictionary(this.ModelState);
                foreach (var modelStateEntry in this.ModelState.Values)
                {
                    foreach (var modelStateError in modelStateEntry.Errors)
                    {
                        newModelState.AddModelError($"ParentCommentId_{inputModel.CommentCounter}", modelStateError.ErrorMessage);
                    }
                }

                //Store needed info for get request in TempData
                TempData["ErrorsFromPOSTRequest"] = ModelStateHelper.SerialiseModelState(newModelState);

                return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsPage, commentsOrderingOption }, pageFragment));
            }

            var userId = this.userService.GetUserId(this.User.Identity.Name);

            //Check if parent comment for this product exists
            if (this.productCommentService.CommentExists(commentId) == false)
            {
                this.ModelState.AddModelError($"ParentCommentId_{inputModel.CommentCounter}", "Can't reply to nonexistent comment.");
            }

            //Check if the user isn't trying to reply to himself
            if (this.productCommentService.CommentBelongsToUser(commentId, userId))
            {
                this.ModelState.AddModelError($"ParentCommentId_{inputModel.CommentCounter}", "Can't reply to yourself.");
            }

            //Check if model state is valid after checking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store input model for passing in get action
                TempData["InputModelFromPOSTRequest"]     = JsonSerializer.Serialize(inputModel);
                TempData["InputModelFromPOSTRequestType"] = nameof(ReplyCommentInputModel);

                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData["ErrorsFromPOSTRequest"] = ModelStateHelper.SerialiseModelState(this.ModelState);

                //Reload same page with the TempData
                return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsPage, commentsOrderingOption }, pageFragment));
            }

            //Create new reply comment
            var replyComment = new ProductComment
            {
                ProductId       = productId,
                ParentCommentId = commentId,
                Text            = inputModel.Text,
                CommentedOn     = DateTime.UtcNow,
                UserId          = userId
            };

            await this.productCommentService.AddAsync(replyComment);

            return(this.RedirectToAction("ProductPage", "Products", new { productId, toReplyComment = replyComment.Id, commentsPage = commentsPage, commentsOrderingOption }, pageFragment));
        }
Example #22
0
        public async Task <ActionResult> SetInfo(UserVModel user, UserOtherVModel other, string province, string city, string area)
        {
            ModelState.Remove("Name");
            ModelState.Remove("ConfirmPassword");
            ModelState.Remove("Password");
            ModelState.Remove("RoleId");
            ModelState.Remove("Avatar");
            if (!ModelState.IsValid)
            {
                return(Json(new JsonResultModel {
                    Message = ModelStateHelper.GetAllErrorMessage(ModelState)
                }));
            }
            user.Id      = CurrentUserInfo.Id;
            other.UserId = CurrentUserInfo.Id;

            var olduser = Users.GetUserById(CurrentUserInfo.Id);

            //邮箱修改需要重新验证
            if (olduser.Email.ToLower() != user.Email.ToLower())
            {
                user.EmailStatus = false;
            }
            else
            {
                user.EmailStatus = olduser.EmailStatus;
            }

            //修改基本信息
            var status = UserPublic.UpdateUser(user);

            if (!status)
            {
                return(Json(new JsonResultModel {
                    Message = "修改基本信息失败!"
                }));
            }
            var userOther = await Users.GetUserOtherById(user.Id);

            if (userOther == null || userOther.IsNull)
            {
                status = await UserPublic.AddUserOther(other) > 0;
            }
            else
            {
                status = UserPublic.UpdateUserOther(other);
            }
            if (!status)
            {
                return(Json(new JsonResultModel {
                    Message = "修改信息失败!"
                }));
            }

            await UserPublic.DeleteUserPosition(CurrentUserInfo.Id);

            #region 地址
            if (!string.IsNullOrEmpty(province))
            {
                int pid = await
                          UserPublic.AddUserPosition(new UserPositionVModel
                {
                    Code   = int.Parse(province),
                    Type   = 0,
                    UserId = CurrentUserInfo.Id
                });

                if (pid == 0)
                {
                    return(Json(new JsonResultModel {
                        Message = "修改居住地区信息失败,!"
                    }));
                }
            }
            if (!string.IsNullOrEmpty(city))
            {
                int cid = await
                          UserPublic.AddUserPosition(new UserPositionVModel
                {
                    Code   = int.Parse(city),
                    Type   = 1,
                    UserId = CurrentUserInfo.Id
                });

                if (cid == 0)
                {
                    return(Json(new JsonResultModel {
                        Message = "修改居住地区信息失败,!"
                    }));
                }
            }
            if (!string.IsNullOrEmpty(area))
            {
                int aid = await
                          UserPublic.AddUserPosition(new UserPositionVModel
                {
                    Code   = int.Parse(area),
                    Type   = 2,
                    UserId = CurrentUserInfo.Id
                });

                if (aid == 0)
                {
                    return(Json(new JsonResultModel {
                        Message = "修改居住地区信息失败,!"
                    }));
                }
            }

            #endregion
            UsersLogin.RefreshCookieUserInfo(CurrentUserInfo.Id);
            return(Json(new JsonResultModel {
                ResultState = true, Message = "修改成功!"
            }));
        }
        public async Task <IActionResult> AddReview(ComplexModel <AddReviewInputModel, ProductInfoViewModel> complexModel, string pageFragment, string commentsPage, string commentsOrderingOption)
        {
            var productId = complexModel.InputModel.ProductId;

            //Sanitize pageFragment
            pageFragment = this.javaScriptEncoder.Encode(pageFragment);

            //Store input model for passing in get action
            TempData["InputModelFromPOSTRequest"]     = JsonSerializer.Serialize(complexModel.InputModel);
            TempData["InputModelFromPOSTRequestType"] = nameof(AddReviewInputModel);

            //Check if data is valid without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData["ErrorsFromPOSTRequest"] = ModelStateHelper.SerialiseModelState(this.ModelState);

                //Store needed info for get request in TempData
                return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsOrderingOption, commentsPage }, pageFragment));
            }

            var userId = this.userService.GetUserId(this.User.Identity.Name);

            var newProductRating = new ProductRating
            {
                ProductId = productId,
                UserId    = userId,
                Rating    = (int)complexModel.InputModel.Rating
            };

            var newComment = new ProductComment
            {
                CommentedOn     = DateTime.UtcNow,
                ParentCommentId = null,
                ProductId       = productId,
                Text            = complexModel.InputModel.Text,
                UserId          = userId,
            };

            //Check if user has already left a review for this product
            if (this.productService.ProductRatingExists(newProductRating) == true && this.productCommentService.CommentExists(newComment) == true)
            {
                this.ModelState.AddModelError("InputModel.Rating", "You have already given a review for this product!!!");
            }

            //Check if rating from this user for this product already exists
            else if (this.productService.ProductRatingExists(newProductRating) == true)
            {
                this.ModelState.AddModelError("InputModel.Rating", "You have already given a review with this rating for this product!!!");
            }

            //Check if comment already from this user for this product already exists(as part of his review, he can still have comments as replies to other people for the same product)
            else if (this.productCommentService.CommentExists(newComment) == true)
            {
                this.ModelState.AddModelError("InputModel.Text", "You have already given a review with a comment for this product!!!");
            }

            //Check if model state is valid after checking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData["ErrorsFromPOSTRequest"] = ModelStateHelper.SerialiseModelState(this.ModelState);

                //Reload same page with the TempData
                return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsPage, commentsOrderingOption }, pageFragment));
            }

            //Set the rating foreign key for new comment
            var newRating = new ProductRating
            {
                ProductCommentId = newComment.Id,
                ProductId        = productId,
                UserId           = userId,
                Rating           = (int)complexModel.InputModel.Rating
            };

            await this.productCommentService.AddAsync(newComment);

            newComment.ProductRatingId = newRating.Id;

            await this.productService.AddRatingAsync(newRating);

            return(this.RedirectToAction("ProductPage", "Products", new { productId, commentsPage = 1, commentsOrderingOption }, pageFragment));
        }
        public async Task <IActionResult> ProductPage(string productId, string toReplyComment, int commentsPage, int commentsOrderingOption)
        {
            //Check if the product in question exists
            if (this.productService.ProductExistsById(productId) == false)
            {
                return(this.NotFound());
            }

            var product   = this.productService.GetProductById(productId, true);
            var viewModel = mapper.Map <ProductInfoViewModel>(product);

            //Add main image to product view model
            var productMainImage = this.productImageService.GetMainImage(productId);

            viewModel.MainImage = productMainImage.Image;

            //Add additional images
            var additionalImages = this.productImageService.GetAdditionalImages(productId);

            viewModel.AdditionalImages = additionalImages;

            viewModel.ProductCategories = this.categoryService.GetCategoriesForProduct(productId);

            //Sanitize commentsPage
            commentsPage = int.Parse(this.htmlEncoder.Encode(commentsPage.ToString()));

            var currentUserId = this.userService.GetUserId(this.User.Identity.Name);

            viewModel.CurrentUserId = currentUserId;

            //Short description
            viewModel.ShortDescription = this.productService.GetShordDescription(viewModel.Description, 40);

            //Overall product rating
            viewModel.ProductRating = new ProductRatingViewModel(this.productService.GetAverageRating(viewModel.ProductRatings));

            await FillProductInfoViewModel(viewModel, productId, commentsPage, toReplyComment, commentsOrderingOption);

            //Add each model state error from the last action to this one
            if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null)
            {
                ModelStateHelper.MergeModelStates(TempData, this.ModelState);
            }

            object complexModel     = null;
            var    typeOfInputModel = TempData[GlobalConstants.InputModelFromPOSTRequestType];

            //If input model is for adding review
            if (typeOfInputModel?.ToString() == nameof(AddReviewInputModel))
            {
                complexModel = AssignViewAndInputModels <AddReviewInputModel, ProductInfoViewModel>(viewModel);
            }
            //If input model is for replying to a comment
            else if (typeOfInputModel?.ToString() == nameof(ReplyCommentInputModel))
            {
                var replyCommentInputModelsJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString();
                var replyCommentInputModel      = JsonSerializer.Deserialize <ReplyCommentInputModel>(replyCommentInputModelsJSON);
                viewModel.ReplyCommentInputModel = replyCommentInputModel;

                complexModel = AssignViewAndInputModels <AddReviewInputModel, ProductInfoViewModel>(viewModel, true);
            }
            //If there isn't an input model
            else
            {
                complexModel = AssignViewAndInputModels <AddReviewInputModel, ProductInfoViewModel>(viewModel, true);
            }

            return(this.View("ProductPage", complexModel));
        }
        public async Task <IActionResult> Add(AddProductInputModel inputModel)
        {
            var newProduct = this.mapper.Map <Product>(inputModel);

            //Set input model short description
            inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40);

            //Store input model for passing in get action
            TempData[GlobalConstants.InputModelFromPOSTRequest]     = JsonSerializer.Serialize(inputModel);
            TempData[GlobalConstants.InputModelFromPOSTRequestType] = nameof(AddProductInputModel);

            //Check without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Add), "Products"));
            }

            //Check if product with this model or name
            if (this.productService.ProductExistsByModel(inputModel.Model) == true)
            {
                this.ModelState.AddModelError("Model", "Product with this model already exists.");
            }
            if (this.productService.ProductExistsByName(inputModel.Name))
            {
                this.ModelState.AddModelError("Name", "Product with this name already exists.");
            }

            //Check if there is a main image, regardless of the imageMode
            if ((inputModel.MainImage == null && inputModel.ImagesAsFileUploads == false) || (inputModel.MainImageUpload == null && inputModel.ImagesAsFileUploads == true))
            {
                this.ModelState.AddModelError("", "Main image is required");

                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Add), "Products"));
            }

            //CHECK THE IMAGES LINKS
            if (inputModel.ImagesAsFileUploads == false)
            {
                //Check if all of these images are unique
                if (this.productImageService.ImagesAreRepeated(inputModel.MainImage, inputModel.AdditionalImages))
                {
                    this.ModelState.AddModelError("", "There are 2 or more non-unique images");
                }

                //Check if main image is already used
                if (this.productImageService.ProductImageExists(inputModel.MainImage) == true)
                {
                    this.ModelState.AddModelError("MainImage", "This image is already used.");
                }

                if (inputModel.AdditionalImages == null)
                {
                    inputModel.AdditionalImages = new List <string>();
                }

                //Check if any of the additional images are used
                for (int i = 0; i < inputModel.AdditionalImages.Count; i++)
                {
                    var additionalImage = inputModel.AdditionalImages[i];
                    if (this.productImageService.ProductImageExists(additionalImage) == true)
                    {
                        this.ModelState.AddModelError($"AdditionalImages[{i}]", "This image is already used.");
                    }
                }
            }
            //CHECK IMAGES UPLOADS
            else
            {
                //Check main image upload
                if (this.productImageService.ValidImageExtension(inputModel.MainImageUpload) == false)
                {
                    this.ModelState.AddModelError("MainImageUpload", "The uploaded image is invalid");
                }

                if (inputModel.AdditionalImagesUploads == null)
                {
                    inputModel.AdditionalImagesUploads = new List <IFormFile>();
                }

                //Check additional images uploads
                for (int i = 0; i < inputModel.AdditionalImagesUploads.Count; i++)
                {
                    var imageUpload = inputModel.AdditionalImagesUploads[i];
                    if (this.productImageService.ValidImageExtension(imageUpload) == false)
                    {
                        this.ModelState.AddModelError($"AdditionalImageUpload[{i}]", "The uploaded image is invalid");
                    }
                }
            }

            //Check if categories exist in the database or if there are even any categories for this product
            for (int i = 0; i < inputModel.CategoriesIds.Count; i++)
            {
                var categoryId = inputModel.CategoriesIds[i];
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist");
                }
            }
            if (inputModel.CategoriesIds.Count == 0)
            {
                this.ModelState.AddModelError("", "You need to add at least one category for this product");
            }

            //Check if categories are unique
            if (inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct().Count() != inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Count())
            {
                this.ModelState.AddModelError($"", "One category cannot be used multiple times.");
            }

            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Add), "Products"));
            }

            //Add images to product
            if (inputModel.ImagesAsFileUploads == false)
            {
                newProduct.Images = new List <ProductImage>();

                //Set additional images
                newProduct.Images = inputModel.AdditionalImages
                                    .Where(x => x != null)
                                    .Select(x => new ProductImage {
                    Image = x, Product = newProduct
                }).ToList();

                //Set main image
                newProduct.Images.Add(new ProductImage {
                    Image = inputModel.MainImage, IsMain = true, Product = newProduct, ProductId = newProduct.Id
                });
            }
            else
            {
                newProduct.Images = new List <ProductImage>();

                //Upload main image
                var imageUrl = await this.productImageService.UploadImageAsync(inputModel.MainImageUpload, newProduct);

                //Set the main image
                newProduct.Images.Add(new ProductImage {
                    Image = imageUrl, IsMain = true, Product = newProduct, ProductId = newProduct.Id
                });

                //Upload the additional images and set the additional images
                foreach (var additionalImage in inputModel.AdditionalImagesUploads)
                {
                    var additionalImageUrl = await this.productImageService.UploadImageAsync(additionalImage, newProduct);

                    newProduct.Images.Add(new ProductImage {
                        Image = additionalImageUrl, IsMain = false, Product = newProduct, ProductId = newProduct.Id
                    });
                }
            }

            //Add product
            await this.productService.AddAsync(newProduct);

            //Add categories
            await this.categoryService.AddCategoriesToProductAsync(newProduct, inputModel.CategoriesIds);

            //Set notification
            NotificationHelper.SetNotification(this.TempData, NotificationType.Success, "Product was successfully added");

            return(this.RedirectToAction("ProductPage", "Products", new { area = "", productId = newProduct.Id }));
        }
Example #26
0
        public async Task <IActionResult> Edit(AddProductInputModel inputModel)
        {
            //Set input model short description
            inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40);

            //Store input model for passing in get action
            TempData[GlobalConstants.InputModelFromPOSTRequest]     = JsonSerializer.Serialize(inputModel);
            TempData[GlobalConstants.InputModelFromPOSTRequestType] = nameof(AddProductInputModel);

            //Set input model mode to edit
            inputModel.IsAdding = false;

            //Check without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Edit), "Products", new { productId = inputModel.Id }));
            }

            //Check if product with this id exists
            if (this.productService.ProductExistsById(inputModel.Id) == false)
            {
                this.ModelState.AddModelError("", "The product that you are trying to edit doesn't exist.");
            }

            var productId = inputModel.Id;

            //Check if product with this model or name exist and it is not the product that is currently being edited
            if (this.productService.ProductExistsByModel(inputModel.Model, productId) == true)
            {
                this.ModelState.AddModelError("Model", "Product with this model already exists.");
            }
            if (this.productService.ProductExistsByName(inputModel.Name, productId))
            {
                this.ModelState.AddModelError("Name", "Product with this name already exists.");
            }

            //Check if all of these images are unique
            if (this.productService.ImagesAreRepeated(inputModel.MainImage, inputModel.AdditionalImages))
            {
                this.ModelState.AddModelError("", "There are 2 or more non-unique images");
            }

            //Check if main image is already used
            if (this.productService.ProductImageExists(inputModel.MainImage, productId) == true)
            {
                this.ModelState.AddModelError("MainImage", "This image is already used.");
            }

            //Check if categories exist in the database or if there are even any categories for this product
            for (int i = 0; i < inputModel.CategoriesIds.Count; i++)
            {
                var categoryId = inputModel.CategoriesIds[i];
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist");
                }
            }
            if (inputModel.CategoriesIds.Count == 0)
            {
                this.ModelState.AddModelError("", "You need to add at least one category for this product");
            }

            //Check if categories exist in the database
            for (int i = 0; i < inputModel.CategoriesIds.Count; i++)
            {
                var categoryId = inputModel.CategoriesIds[i];
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist");
                }
            }

            //Check if categories are unique
            if (inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct().Count() != inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Count())
            {
                this.ModelState.AddModelError($"", "One category cannot be used multiple times.");
            }


            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Edit), "Products", new { productId = inputModel.Id }));
            }

            await this.productService.EditAsync(inputModel);

            var product = this.productService.GetProductById(inputModel.Id, false);

            await this.categoryService.EditCategoriesToProductAsync(product, inputModel.CategoriesIds);

            //Set notification
            NotificationHelper.SetNotification(this.TempData, NotificationType.Success, "Product was successfully edited");

            return(this.RedirectToAction(nameof(ProductPage), "Products", new { productId = inputModel.Id }));
        }
Example #27
0
        public async Task <IActionResult> Add(AddProductInputModel inputModel)
        {
            var newProduct = this.mapper.Map <Product>(inputModel);

            //Set input model short description
            inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40);

            //Store input model for passing in get action
            TempData[GlobalConstants.InputModelFromPOSTRequest]     = JsonSerializer.Serialize(inputModel);
            TempData[GlobalConstants.InputModelFromPOSTRequestType] = nameof(AddProductInputModel);

            //Check without looking into the database
            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Add), "Products"));
            }

            await this.TryUpdateModelAsync(inputModel, typeof(AddProductInputModel), "");

            //Check if product with this model or name
            if (this.productService.ProductExistsByModel(inputModel.Model) == true)
            {
                this.ModelState.AddModelError("Model", "Product with this model already exists.");
            }
            if (this.productService.ProductExistsByName(inputModel.Name))
            {
                this.ModelState.AddModelError("Name", "Product with this name already exists.");
            }

            //Check if all of these images are unique
            if (this.productService.ImagesAreRepeated(inputModel.MainImage, inputModel.AdditionalImages))
            {
                this.ModelState.AddModelError("", "There are 2 or more non-unique images");
            }

            //Check if main image is already used
            if (this.productService.ProductImageExists(inputModel.MainImage) == true)
            {
                this.ModelState.AddModelError("MainImage", "This image is already used.");
            }

            //Check if any of the additional images are used
            for (int i = 0; i < inputModel.AdditionalImages.Count; i++)
            {
                var additionalImage = inputModel.AdditionalImages[i];
                if (this.productService.ProductImageExists(additionalImage) == true)
                {
                    this.ModelState.AddModelError($"AdditionalImages[{i}]", "This image is already used.");
                }
            }

            //Check if categories exist in the database or if there are even any categories for this product
            for (int i = 0; i < inputModel.CategoriesIds.Count; i++)
            {
                var categoryId = inputModel.CategoriesIds[i];
                if (this.categoryService.CategoryExists(categoryId) == false)
                {
                    this.ModelState.AddModelError($"CategoriesIds{i}", "This category doesn't exist");
                }
            }
            if (inputModel.CategoriesIds.Count == 0)
            {
                this.ModelState.AddModelError("", "You need to add at least one category for this product");
            }

            //Check if categories are unique
            if (inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Distinct().Count() != inputModel.CategoriesIds.Where(x => string.IsNullOrWhiteSpace(x) == false).Count())
            {
                this.ModelState.AddModelError($"", "One category cannot be used multiple times.");
            }

            if (this.ModelState.IsValid == false)
            {
                //Store needed info for get request in TempData only if the model state is invalid after doing the complex checks
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.RedirectToAction(nameof(Add), "Products"));
            }

            //Set additional images
            newProduct.AdditionalImages = inputModel.AdditionalImages
                                          .Where(x => x != null)
                                          .Select(x => new ProductImage {
                Image = x, Product = newProduct
            }).ToList();

            //Add product
            await this.productService.AddAsync(newProduct);

            //Add categories
            await this.categoryService.AddCategoriesToProductAsync(newProduct, inputModel.CategoriesIds);/**/

            //Set notification
            NotificationHelper.SetNotification(this.TempData, NotificationType.Success, "Product was successfully added");

            return(this.RedirectToAction(nameof(ProductPage), "Products", new { productId = newProduct.Id }));
        }
        public ActionResult EditNews(NewsEditViewModel Model)
        {
            bool   _success    = false;
            string _Error      = "";
            bool   _isCreation = false;

            try
            {
                if (User.Identity.IsAuthenticated)
                {
                    if (ModelState.IsValid)
                    {
                        Model.PublishDate            = Model.PublishDate.ToUniversalTime();
                        Model.LastModificationUserId = UserSession.UserId;
                        if (Model.TypeId == CommonsConst.NewsType.PublishOnly)
                        {
                            Model.MailSubject       = null;
                            Model.TypeUserMailingId = null;
                        }

                        if (Model.Id <= 0)
                        {
                            _isCreation = true;
                            int NewsId = _newsService.CreateNews(Model);
                            Model.Id = NewsId;
                            if (NewsId > 0)
                            {
                                _success = true;
                            }
                        }
                        else
                        {
                            _success = _newsService.EditNews(Model);
                        }

                        // Scehdule
                        if (_success)
                        {
                            if (!Model.HasScheduledTaskBeenExecuted && Model.ScheduledTaskId.HasValue)
                            {
                                _success = _scheduledTaskService.CancelTaskById(Model.ScheduledTaskId.Value);
                            }

                            if (_success && !Model.HasScheduledTaskBeenExecuted && Model.TypeId != CommonsConst.NewsType.PublishOnly && Model.Active)
                            {
                                if (Model.PublishDate < DateTime.UtcNow)
                                {
                                    Model.PublishDate = DateTime.UtcNow.AddSeconds(5);
                                }

                                _success = _scheduledTaskService.ScheduleNews(Model.Id, Model.PublishDate - DateTime.UtcNow);
                            }
                        }
                    }
                    else
                    {
                        _Error = ModelStateHelper.GetModelErrorsToDisplay(ModelState);
                    }
                }
                else
                {
                    _Error = "[[[You are not logged in.]]]";
                }

                if (!_success && String.IsNullOrWhiteSpace(_Error))
                {
                    _Error = "[[[Error while saving the update.]]]";
                }
            }
            catch (Exception e)
            {
                _success = false;
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Id = " + Model.Id);
            }
            return(Json(new { Result = _success, Error = _Error, IsCreation = _isCreation }));
        }
Example #29
0
        public ActionResult Edit(SubscriptionEditModel model)
        {
            var modelState = new ModelStateHelper <SubscriptionEditModel>(ModelState);

            // Проверка ComponentTypeId
            if (model.Object == SubscriptionObject.ComponentType && model.ComponentTypeId == null)
            {
                modelState.AddErrorFor(x => x.ComponentTypeId, "Выберите тип компонента");
            }

            // Проверка ComponentId
            if (model.Object == SubscriptionObject.Component && model.ComponentId == null)
            {
                modelState.AddErrorFor(x => x.ComponentId, "Выберите компонент");
            }

            // Проверка Channel
            if (model.Id == null && model.Channel == null)
            {
                // канал должен указываться явно только для новых подписок
                modelState.AddErrorFor(x => x.Channel, "Выберите канал");
            }

            // Проверка UserId
            if (model.Id == null && model.UserId == null)
            {
                // Пользователь должен указываться явно только для новых подписок
                modelState.AddErrorFor(x => x.UserId, "Выберите пользователя");
            }

            // проверка цвета
            var color = model.Color.GetSelectedOne();

            if (color == null)
            {
                modelState.AddErrorFor(x => x.Color, "Укажите цвет");
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                // проверка прав
                var isOtherUser = CurrentUser.Id != model.UserId;
                if (isOtherUser)
                {
                    if (CurrentUser.IsAdmin() == false)
                    {
                        throw new UserFriendlyException("Нет прав на создание подписок другим пользователям");
                    }
                }

                var importance = ImportanceHelper.Get(color).Value;
                var client     = GetDispatcherClient();
                if (model.Id == null)
                {
                    // создание новой подписки
                    var createData = new CreateSubscriptionRequestData()
                    {
                        UserId  = model.UserId.Value,
                        Channel = model.Channel.Value,
                        DurationMinimumInSeconds = TimeSpanHelper.GetSeconds(model.MinimumDuration),
                        ResendTimeInSeconds      = TimeSpanHelper.GetSeconds(model.ResendTime),
                        Importance         = importance,
                        IsEnabled          = model.IsEnabled,
                        NotifyBetterStatus = model.NotifyBetterStatus,
                        Object             = model.Object
                    };
                    if (model.Object == SubscriptionObject.Component)
                    {
                        createData.ComponentId = model.ComponentId;
                    }
                    if (model.Object == SubscriptionObject.ComponentType)
                    {
                        createData.ComponentTypeId = model.ComponentTypeId;
                    }
                    var response = client.CreateSubscription(CurrentUser.AccountId, createData);
                    response.Check();
                    model.Id = response.Data.Id;
                }
                else
                {
                    // редактирование существующей подписки
                    var updateData = new UpdateSubscriptionRequestData()
                    {
                        Id = model.Id.Value,
                        NotifyBetterStatus       = model.NotifyBetterStatus,
                        IsEnabled                = model.IsEnabled,
                        ResendTimeInSeconds      = TimeSpanHelper.GetSeconds(model.ResendTime),
                        DurationMinimumInSeconds = TimeSpanHelper.GetSeconds(model.MinimumDuration),
                        Importance               = importance
                    };
                    var response = client.UpdateSubscription(CurrentUser.AccountId, updateData);
                    response.Check();
                }
                if (model.ModalMode)
                {
                    return(GetSuccessJsonResponse(new { subscriptionId = model.Id }));
                }
                return(Redirect(model.ReturnUrl));
            }
            catch (UserFriendlyException exception)
            {
                model.Exception = exception;
            }

            return(View(model));
        }
        public async Task <IActionResult> ChangeSaleStatus(ComplexModel <ChangeSaleStatusInputModel, List <SaleStatus> > complexModel)
        {
            if (this.ModelState.IsValid == false)
            {
                //Set up temp data with model state and input model
                this.TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);
                this.TempData["NewSaleStatusId"] = complexModel.InputModel.NewSaleStatusId;

                return(this.RedirectToAction(nameof(ChangeSaleStatus), new { saleId = complexModel.InputModel.SaleId }));
            }

            //Check if status and sale exist
            if (this.saleService.SaleStatusExists(complexModel.InputModel.NewSaleStatusId) == false)
            {
                this.ModelState.AddModelError("InputModel.NewSaleStatusId", "This sale status doesn't exist");
            }

            if (this.ModelState.IsValid == false)
            {
                //Set up temp data with model state and input model
                this.TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);
                this.TempData["NewSaleStatusId"] = complexModel.InputModel.NewSaleStatusId;

                return(this.RedirectToAction(nameof(ChangeSaleStatus), new { saleId = complexModel.InputModel.SaleId }));
            }

            //Capture the payment intent and officially complete the sale and charge the customer if the paymentStatus is confirmed
            var newSaleStatus = this.saleService.GetSaleStatusById(complexModel.InputModel.NewSaleStatusId);

            if (newSaleStatus.Name == GlobalConstants.ConfirmedSaleStatus)
            {
                var paymentIntentId = this.saleService.GetPaymentIntentId(complexModel.InputModel.SaleId);
                if (paymentIntentId != null)
                {
                    var paymentIntent = await this.paymentIntentService.GetAsync(paymentIntentId);

                    if (paymentIntent.Status == "requires_capture")
                    {
                        await this.paymentIntentService.CaptureAsync(paymentIntentId);
                    }
                }
            }
            //Set free the payment intent and the funds if the paymentStatus is declined
            else if (newSaleStatus.Name == GlobalConstants.DeclinedSaleStatus)
            {
                var paymentIntentId = this.saleService.GetPaymentIntentId(complexModel.InputModel.SaleId);
                if (paymentIntentId != null)
                {
                    var paymentIntent = await this.paymentIntentService.GetAsync(paymentIntentId);

                    if (paymentIntent.Status == "requires_capture")
                    {
                        await this.paymentIntentService.CancelAsync(paymentIntentId);
                    }
                }
            }

            await this.saleService.ChangeSaleStatusAsync(complexModel.InputModel.SaleId, complexModel.InputModel.NewSaleStatusId);

            //Set up success notification
            NotificationHelper.SetNotification(this.TempData, NotificationType.Success, $"You have successfully changed sale status");

            return(this.RedirectToAction(nameof(Search)));
        }