Beispiel #1
0
        public async Task <IActionResult> AddReviewForBook(int id, [FromBody] ReviewForCreationDto reviewForCreationDto)
        {
            if (reviewForCreationDto == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var authId = 0;

            int.TryParse(User.FindFirst(ClaimTypes.NameIdentifier).Value, out authId);

            var user = await _repo.GetUser(authId);

            if (user == null)
            {
                return(Unauthorized());
            }

            var bookFromRepo = await _repo.GetBook(id);

            if (bookFromRepo == null)
            {
                return(NotFound());
            }

            if (await _repo.ReviewExists(user.Id, id))
            {
                return(BadRequest("You've already reviewed this book"));
            }

            var review = new Review()
            {
                UserId  = user.Id,
                BookId  = bookFromRepo.Id,
                Content = reviewForCreationDto.Content,
                Rating  = reviewForCreationDto.Rating
            };

            _repo.Add(review);

            if (!await _repo.SaveAll())
            {
                throw new Exception($"Book review for id {id} failed on save.");
            }

            return(StatusCode(201));
        }
Beispiel #2
0
        public void AddstoreTest()
        {
            //Add first
            _repository.Add(storeStub1);
            _repository.SaveChanges();

            //Check whether on database or not
            store = _repository.GetById(storeStub1.Id);
            Assert.IsNotNull(store, "Data Store Baru Berhasil Terbuat");

            //Delete so this method can be used again
            _repository.Delete(storeStub1);
            _repository.SaveChanges();
        }
        public async Task <IActionResult> Post([FromBody] StoreViewModel store)
        {
            var identity = (ClaimsIdentity)User.Identity;
            IEnumerable <Claim> claims = identity.Claims;
            var username = claims.Where(c => c.Type == "Username").FirstOrDefault().Value;
            var _user    = await _userRepository.GetSingleAsync(x => x.UserName == username);

            if (_user == null)
            {
                return(new BadRequestResult());
            }
            var _newStore = Mapper.Map <StoreViewModel, Store>(store);

            _newStore.UserId = _user.Id;
            _newStore.User   = _user;
            if (_newStore.Id == 0)
            {
                _storeRepository.Add(_newStore);
            }
            else
            {
                _storeRepository.Update(_newStore);
            }
            await _storeRepository.Commit();

            return(new NoContentResult());
        }
Beispiel #4
0
        public async Task CreateStoreAsync(Store store)
        {
            if (store == null)
            {
                throw new ArgumentNullException(nameof(store) + " is null");
            }

            if (store.CompanyId == Guid.Empty)
            {
                throw new MissingCompanyIdException(nameof(store) + " is missing a company id!");
            }

            var newStore = new DAL.Models.Store
            {
                CompanyId = store.CompanyId,
                Name      = store.Name,
                Address   = store.Address,
                City      = store.City,
                Country   = store.Country,
                Zip       = store.Zip,
                Longitude = store.Longitude,
                Latitude  = store.Latitude
            };

            _storeRepository.Add(newStore);

            await _unitOfWork.CommitAsync();
        }
Beispiel #5
0
        /// <summary>
        /// Add Stuff To Store
        /// </summary>
        /// <param name="storeViewModel"></param>
        /// <returns></returns>
        public Store AddStoreContent(StoreViewModel storeViewModel)
        {
            var store = storeViewModel.ConvertToStoreModel();

            _storeRepository.Add(store);
            _storeRepository.SaveChanges();
            return(store);
        }
Beispiel #6
0
        public async Task Handle(StoreCreateCommand message, CancellationToken cancellationToken)
        {
            var e = new Store(
                message.Id, message.StoreChainId, message.Name,
                message.Latitude, message.Longitude, message.Address);

            store.Add(e);
        }
Beispiel #7
0
        public async Task <StoreModel> Create(StoreModel model)
        {
            model.ID = Guid.NewGuid();
            var data = await _repo.Add(model);

            data = await this.UpdateStoreImage(data, model);

            return(data);
        }
Beispiel #8
0
        public async Task <ActionResult> CreateStoreAsync([FromBody] CreateStoreRequestModel storeModel)
        {
            var store = new Store(storeModel.Name, storeModel.StoreTypeId);

            _storeRepository.Add(store);
            await _storeRepository.UnitOfWork.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetByIdAsync), new { id = store.Id }, null));
        }
Beispiel #9
0
        public ActionResult Create(Category category)
        {
            if (ModelState.IsValid)
            {
                categoryRepository.Add(category);
                return(RedirectToAction("List"));
            }

            return(View(category));
        }
        //[ValidateAntiForgeryToken]
        public IActionResult Create(StorePhotoViewModel viewModel, Stores stores, ApplicationUser app)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (viewModel.Photo != null)
                {
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + viewModel.Photo.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);

                    viewModel.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                var test = User.Claims.ToList()
                           .Where(u => u.Type.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"))
                           .FirstOrDefault().Value;
                //var test = _context.Users.Select(x => x.Id).FirstOrDefault();
                var newStore = new Stores
                {
                    Name          = viewModel.Name,
                    Description   = viewModel.Description,
                    Address       = viewModel.Address,
                    states        = viewModel.states,
                    Photopath     = uniqueFileName,
                    AspNetUsersId = test
                };
                ////Stores storeschoice = storeRepository.GetStoresByViewModel(viewModel);
                ////if (storeschoice == null)
                ////{
                ////    return NotFound();
                ////}
                ////viewModel.Store = storeschoice;
                ////drugs.Stores = viewModel.Store;
                ////_drugRepository.Add(drugs);
                ////viewModel = GetStoreDrugView(storeschoice);
                ////return View(viewModel);
                //ApplicationUser applicationUser = _store.GetUserByStore(app);
                //if(applicationUser==null)
                //{
                //    return NotFound();
                //}
                //app.stores = applicationUser.stores;

                _store.Add(newStore);
                return(RedirectToAction("Store"));
                //return RedirectToAction("Store", "Medicine", new
                //{
                //    Id = stores.Id
                //});
            }
            return(View());
        }
        public async Task <IActionResult> Post([FromBody] Customer model)
        {
            if (ModelState.IsValid)
            {
                _repository.Add(model);
                if (await _repository.SaveAsync())
                {
                    return(Created($"api/customer", model));
                }
            }

            return(BadRequest("Failed to create new customer"));
        }
Beispiel #12
0
        public IHttpActionResult Post([FromBody] StoreCreateModel storeModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var newStore = Mapper.Map <Store>(storeModel);
            var id       = _storeRepository.Add(newStore);
            var location = new Uri(Request.RequestUri + "/" + id);

            return(Created(location, id));
        }
Beispiel #13
0
        public GeneralResponse AddStore(AddStoreRequestOld request)
        {
            GeneralResponse response = new GeneralResponse();

            try
            {
                Store store = new Store();
                store.ID             = Guid.NewGuid();
                store.CreateDate     = PersianDateTime.Now;
                store.CreateEmployee = _employeeRepository.FindBy(request.CreateEmployeeID);
                store.OwnerEmployee  = this._employeeRepository.FindBy(request.OwnerEmployeeID);
                store.StoreName      = request.StoreName;
                store.Note           = request.Note;

                store.RowVersion = 1;

                // Validation
                if (store.GetBrokenRules().Count() > 0)
                {
                    foreach (BusinessRule businessRule in store.GetBrokenRules())
                    {
                        response.ErrorMessages.Add(businessRule.Rule);
                    }

                    return(response);
                }

                _storeRepository.Add(store);
                _uow.Commit();

                ////response.success = true;
            }
            catch (Exception ex)
            {
                response.ErrorMessages.Add(ex.Message);
            }

            return(response);
        }
Beispiel #14
0
        public async Task <Store> AddAsync(StoreRequest request)
        {
            if (await _repository.Find(request.StoreName, request.Address) != null)
            {
                throw new ApiException("Store at given address with given name is already existing!");
            }
            var store = _mapper.Map <Store>(request);

            var addedStore = await _repository.Add(store);

            await _repository.SaveChangesAsync();

            return(addedStore);
        }
Beispiel #15
0
        public async Task <string> CreateStoreAsync()
        {
            string result = String.Empty;

            try
            {
                result = await _storeRepository.Add(this);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
        public Task <bool> Handle(CreateStoreCommand request, CancellationToken cancellationToken)
        {
            Store store = new Store()
            {
                Name    = request.Name,
                Address = request.Address,
                Region  = request.Region,
                City    = request.City,
            };

            _storeRepository.Add(store);
            _unitOfWork.Commit();

            return(Task.FromResult(true));
        }
Beispiel #17
0
        public ActionResult Create(Product p)
        {
            SelectList categories = new SelectList(categoryRepository.Items, "Id", "Name");

            ViewBag.Categories = categories;

            if (ModelState.IsValid)
            {
                TempData["message"] = $"продукт \"{p.Name}\" был добавлен";
                productRepository.Add(p);

                return(RedirectToAction("Index"));
            }

            return(View(p));
        }
Beispiel #18
0
        public ValidationResult CreateNewStore(Store store)
        {
            var storeInDb = storeRepo.GetByDistrictName(store.DistrictName);

            if (storeInDb != null)
            {
                validationResult.AddError(new ValidationError($"A loja da {store.DistrictName} já foi cadastrada.", MessageCategory.BusinessRule));
            }

            if (validationResult.IsValid)
            {
                storeRepo.Add(store);
            }

            return(validationResult);
        }
        public async Task <IActionResult> CreateStore(StoreForCreatingDto storeForCreatingDto)
        {
            storeForCreatingDto.Name = storeForCreatingDto.Name.ToLower();
            var store = new Store {
                Name = storeForCreatingDto.Name
            };

            if (await _repo.StoreExists(store))
            {
                return(BadRequest(string.Format("There is already a store with the given information.")));
            }

            _repo.Add(store);
            await _repo.SaveAll();

            return(Ok(store));
        }
Beispiel #20
0
        public ResponseMessageModel Save(StoreUpModel model)
        {
            var response = new ResponseMessageModel();

            if (model.FranchiseStoreId <= EntityConstants.NO_VALUE)
            {
                SaveAddress(model);
                _repositoryStore.Add(model);
            }
            else
            {
                SaveAddress(model);
                _repositoryStore.Update(model);
            }

            return(response);
        }
        public async Task <IActionResult> Post([FromBody] OrderModel model)
        {
            if (ModelState.IsValid)
            {
                var customer = _repository.GetCustomer(User.Identity.Name);
                if (customer != null)
                {
                    if (!customer.Addresses.Any())
                    {
                        return(BadRequest("Customer must have at least one address."));
                    }
                    if (model.Items == null || !model.Items.Any())
                    {
                        return(BadRequest("Orders must have line items."));
                    }

                    var order = new Order()
                    {
                        OrderDate   = model.OrderDate == DateTime.MinValue ? DateTime.Today : model.OrderDate,
                        Address     = customer.Addresses.First(),
                        Customer    = customer,
                        OrderNumber = model.OrderNumber ?? Guid.NewGuid().ToString(),
                        Items       = model.Items.Select(s =>
                        {
                            var product = _repository.GetProductByGTINCode(s.GTINCode);
                            return(new OrderItem()
                            {
                                Product = product,
                                Price = s.Price == 0 ? product.ListPrice : s.Price,
                                Discount = s.Discount,
                                Quantity = s.Quantity == 0 ? 1f : s.Quantity
                            });
                        }).ToList()
                    };

                    _repository.Add(order);

                    if (await _repository.SaveAsync())
                    {
                        return(Created($"api/orders/{order.Id}", order));
                    }
                }
            }

            return(BadRequest("Request Body incorrect"));
        }
        public async Task <IActionResult> Post([FromBody] CustomerModel model)
        {
            if (ModelState.IsValid)
            {
                var cust = _mapper.Map <Customer>(model);

                cust.Addresses.Add(_mapper.Map <Address>(model.Address));

                _repository.Add(cust);
                if (await _repository.SaveAsync())
                {
                    return(Created($"api/customer", cust));
                }
            }

            return(BadRequest(ModelState));
        }
        public async Task <IActionResult> Post([FromBody] Customer model)
        {
            if (ModelState.IsValid)
            {
                if (_repository.GetCustomer(User.Identity.Name) != null)
                {
                    return(BadRequest("Customer Exists. Try updating customer instead."));
                }

                model.Username = User.Identity.Name;

                _repository.Add(model);
                if (await _repository.SaveAsync())
                {
                    return(Created($"api/customer", model));
                }
            }

            return(BadRequest("Failed to create new customer"));
        }
        public ICommandResult Execute(CreateStoreCommand command)
        {
            try
            {
                if (command == null)
                {
                    throw new ArgumentNullException();
                }

                var store = new Store();
                AddStore(command, store);
                _storeRepository.Add(store);
                _unitOfWork.Commit();
                return(new SuccessResult(StoreCommandMessage.StoreCreatedSuccessfully));
            }
            catch (Exception exception)
            {
                _logger.Error(exception.Message);
                return(new FailureResult(StoreCommandMessage.StoreCreationFailed));
            }
        }
Beispiel #25
0
        public async Task <IActionResult> Create([FromBody] StoreDTO dto,
                                                 CancellationToken cancellationToken = default)
        {
            var smartZone = await _smartZoneRepository.FindByIdAsync(dto.SmartZoneId);

            if (smartZone == null)
            {
                return(NotFound("No SmartZone Found"));
            }

            var store = _mapper.Map <Store>(dto);

            store.IsDeleted       = false;
            store.OneStarRating   = 0;
            store.TwoStarRating   = 0;
            store.ThreeStarRating = 0;
            store.FourStarRating  = 0;
            store.FiveStarRating  = 0;

            _storeRepository.Add(store);
            await _storeRepository.SaveChangesAsync(cancellationToken);

            return(CreatedAtAction(nameof(GetById), new { store.Id }, _mapper.Map <StoreDTO>(store)));
        }
Beispiel #26
0
 // POST api/<controller>
 public void Post([FromBody] Store value)
 {
     Store store = storeRepository.Add(value);
 }
Beispiel #27
0
        public async Task <IActionResult> AddOrder([FromBody] OrderForCreationDto orderForCreationDto)
        {
            if (orderForCreationDto == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var orderEntity = _mapper.Map <Order>(orderForCreationDto);

            foreach (var item in orderEntity.OrderItems)
            {
                var bookFromRepo = await _repo.GetBook(item.BookId);

                if (bookFromRepo == null)
                {
                    return(BadRequest());
                }
            }

            if (!orderForCreationDto.Guest)
            {
                var authId = 0;
                int.TryParse(User.FindFirst(ClaimTypes.NameIdentifier).Value, out authId);

                var user = await _repo.GetUser(authId);

                if (user == null)
                {
                    return(Unauthorized());
                }

                orderEntity.UserId = user.Id;

                _repo.Add(orderEntity);

                if (!await _repo.SaveAll())
                {
                    throw new Exception("Failed to create order");
                }

                var authOrderToReturn = _mapper.Map <OrderForUserToReturnDto>(orderEntity);

                return(CreatedAtRoute("GetOrder", new { orderId = authOrderToReturn.Id }, authOrderToReturn));
            }

            _repo.Add(orderEntity);

            if (!await _repo.SaveAll())
            {
                throw new Exception("Failed to create order");
            }

            var guestOrderToReturn = _mapper.Map <OrderForGuestToReturnDto>(orderEntity);

            return(StatusCode(201, guestOrderToReturn));
        }
Beispiel #28
0
 public void CreateStore(Store Store)
 {
     StoreRepository.Add(Store);
 }
Beispiel #29
0
        public void CreateStore(StoreDto input)
        {
            var store = StoreMapper.Map(input);

            _storeRepository.Add(store);
        }
 public void CreateStore(Stores.Model.Store store)
 {
     storesRepository.Add(store);
 }