public async Task <IActionResult> ClientGetCustomerInfo()
        {
            var sessionUsername = HttpContext.Session.GetString(SessionConstant.Username);

            if (string.IsNullOrEmpty(sessionUsername))
            {
                return(Ok(ResponseDTO.BadRequest()));
            }

            var customer = await _repository.FirstOrDefault(c => c.Username == sessionUsername);

            if (customer == null)
            {
                return(Ok(ResponseDTO.NotFound()));
            }

            return(Ok(ResponseDTO.Ok(new
            {
                id = customer.Id,
                customer.Name,
                dateOfBirth = customer.DateOfBirth.ToString("o"),
                email = customer.Email,
                phoneNumber = customer.PhoneNumber,
                gender = customer.Gender
            })));
        }
        public async Task <IActionResult> ClientAddAddress([FromBody] BodyAddressDTO dto)
        {
            var customer = await GetCustomer();

            if (customer == null)
            {
                return(Ok(ResponseDTO.BadRequest("Invalid customers' username.")));
            }

            var newAddress = new Address()
            {
                City                 = dto.city,
                District             = dto.district,
                Ward                 = dto.ward,
                Street               = dto.street,
                CustomerId           = customer.Id,
                RecipientName        = dto.name,
                RecipientPhoneNumber = dto.phoneNumber
            };

            customer.Addresses.Add(newAddress);
            await _context.SaveChangesAsync();

            var listResponse = new List <object>();

            foreach (var add in customer.Addresses)
            {
                listResponse.Add(ConvertToResponseAddressDTO(add, customer.Id));
            }
            return(Ok(ResponseDTO.Ok(listResponse)));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> UpdateCustomer(int id, [FromBody] UpdateOrderDTO dto)
        {
            if (id != dto.Id)
            {
                return(Ok(ResponseDTO.BadRequest("URL ID and Item ID does not matched.")));
            }

            // Validate
            var entity = await _repository.FirstOrDefault(x => x.Id == id);

            if (entity == null)
            {
                return(Ok(ResponseDTO.BadRequest("Item ID is not existed.")));
            }

            entity.Status        = dto.Status;
            entity.ConfirmDate   = dto.ConfirmDate;
            entity.CancelDate    = dto.CancelDate;
            entity.BeginDelivery = dto.BeginDelivery;
            entity.DeliveryDate  = dto.DeliveryDate;
            entity.Note          = dto.Note;

            await _repository.Update(entity);

            return(Ok(ResponseDTO.Ok(entity)));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a new session for the given user,
        /// with <paramref name="pQuestionsQuantity"/> questions from the
        /// given category and level.
        /// </summary>
        /// <returns>The session.</returns>
        /// <param name="pUserId">User identifier</param>
        /// <param name="pCategoryId">Category identifier.</param>
        /// <param name="pLevelId">Level identifier.</param>
        /// <param name="pQuestionsQuantity">Questions quantity.</param>
        public ResponseDTO <SessionDTO> NewSession(int pUserId, int pCategoryId, int pLevelId, int pQuestionsQuantity)
        {
            if (pQuestionsQuantity < MIN_SESSION_QUESTIONS_QUANTITY)
            {
                throw new BadRequestException($"Questions quantity must be greather than {MIN_SESSION_QUESTIONS_QUANTITY}");
            }
            using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
            {
                var user      = bUoW.UserRepository.Get(pUserId) ?? throw new NotFoundException($"User id {pUserId} not found.");
                var level     = bUoW.LevelRepository.Get(pLevelId) ?? throw new NotFoundException($"Level id {pLevelId} not found.");
                var category  = bUoW.CategoryRepository.Get(pCategoryId) ?? throw new NotFoundException($"Category id {pCategoryId} not found.");
                var questions = bUoW.QuestionRepository.GetQuestions(category, level, pQuestionsQuantity).ToList();
                var session   = new Session
                {
                    User      = user,
                    Level     = level,
                    Category  = category,
                    Questions = questions,
                    Date      = DateTime.Now,
                    Score     = 0d
                };
                bUoW.SessionRepository.Add(session);

                bUoW.Complete();
                var sessionDTO = _mapper.Map <SessionDTO>(session);
                return(ResponseDTO <SessionDTO> .Ok("Session successfully created.", sessionDTO));
            }
        }
Ejemplo n.º 5
0
        protected async Task <IActionResult> _GetById <ResponseModel>(int id, RequestContext context)
            where ResponseModel : BaseDTO
        {
            try
            {
                var entity = await _repository.GetById(id);

                if (entity == null)
                {
                    return(Ok(ResponseDTO.NotFound()));
                }

                var models = MapToResponseModels <ResponseModel>(new List <Model>()
                {
                    entity
                });
                var resultModel = await FinishMappingResponseModels(models, new List <Model>() { entity }, context);

                return(Ok(ResponseDTO.Ok(resultModel.First())));
            }
            catch (Exception e)
            {
                return(HandleExceptionInRequest(e));
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Logout.
 /// </summary>
 public ResponseDTO <object> Logout()
 {
     this.LoggedUser           = null;
     this.CurrentSession       = null;
     this.SelectedQuestionsSet = null;
     return(ResponseDTO.Ok("Successfully logged out."));
 }
        public async Task <ResponseDTO> RegisterExchangeRate(RegisterExchangeRateRequest request)
        {
            if (request.Target == request.Base)
            {
                return(ResponseDTO.Fail("Base and target currency can't be the same."));
            }

            var baseCurrency = await _context.CurrencySymbols.AsNoTracking()
                               .FirstOrDefaultAsync(x => x.Symbol == request.Base);

            var targetCurrency = await _context.CurrencySymbols.AsNoTracking()
                                 .FirstOrDefaultAsync(x => x.Symbol == request.Target);

            var currencyExistAndIsEnabled = CurrencyExistAndIsEnabled(baseCurrency, request.Base);

            if (!currencyExistAndIsEnabled)
            {
                return(currencyExistAndIsEnabled);
            }

            var targetCurrencyExist = CurrencyExistAndIsEnabled(targetCurrency, request.Target);

            if (!targetCurrencyExist)
            {
                return(targetCurrencyExist);
            }

            var exchangeRate = new Domain.ExchangeRate(request.Base, request.Target, request.Rate);

            _context.ExchangeRates.Add(exchangeRate);
            await _context.SaveChangesAsync();

            return(ResponseDTO.Ok());
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Record an answer for a question from an ongoing session.
        /// </summary>
        /// <returns>Answer result.</returns>
        /// <param name="pSessionAnswer">Session answer parameters.</param>
        public ResponseDTO <AnswerResultDTO> AddAnswer(SessionAnswerDTO pSessionAnswer)
        {
            if (pSessionAnswer.Session == null)
            {
                return(ResponseDTO <AnswerResultDTO> .BadRequest("Failed to add answer. Invalid session."));
            }
            using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
            {
                var           question      = bUoW.QuestionRepository.Get(pSessionAnswer.Question.Id);
                var           answers       = question.Answers.Where(answer => pSessionAnswer.Answers.Select(a => a.Id).Contains(answer.Id)).ToList();
                SessionAnswer sessionAnswer = new SessionAnswer
                {
                    Answers    = answers,
                    Question   = bUoW.QuestionRepository.Get(pSessionAnswer.Question.Id),
                    AnswerTime = pSessionAnswer.AnswerTime
                };

                // Get session entity from the given SessionId
                Session session = bUoW.SessionRepository.Get(pSessionAnswer.Session.Id) ?? throw new Exception($"Session id {pSessionAnswer.Session.Id} not found.");
                session.Answers.Add(sessionAnswer);

                AnswerResultDTO answerResult = _mapper.Map <AnswerResultDTO>(sessionAnswer);
                bUoW.Complete();

                return(ResponseDTO <AnswerResultDTO> .Ok(answerResult.IsCorrect? "Right!" : "Wrong answer.", answerResult));
            }
        }
Ejemplo n.º 9
0
        /*
         *  Summary:
         *  - Give a change to modify response models before return.
         */
        // protected virtual async Task<object> FinishMapResponseModel(object responseEntity, Model entity)
        // {
        //     return await Task.FromResult(responseEntity);
        // }


        /*
         *  Summary: Return resposne for get request.
         */
        public async Task <IActionResult> ResultForGetAll(IEnumerable <dynamic> items, int totalRecords)
        {
            if (items.Count() == 0)
            {
                return(Ok(ResponseDTO.NotFound()));
            }
            return(Ok(ResponseDTO.Ok(items, totalRecords)));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> GetUser()
        {
            var users = await repo.GetUser();

            var items = mapper.Map <List <ResponseUserDto> >(users);

            return(Ok(ResponseDTO.Ok(items, items.Count())));
        }
Ejemplo n.º 11
0
 public ResponseDTO <object> UpdateQuestionsSetData(string pQuestionsSetName)
 {
     using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
     {
         IQuestionsSetImporter questionsSetImporter = _questionsSetImporterFactory.GetImporter(pQuestionsSetName);
         questionsSetImporter.UpdateData();
         return(ResponseDTO.Ok("Data updated successfully."));
     }
 }
Ejemplo n.º 12
0
        public async Task<IActionResult> ClientCartUpdate([FromBody] List<BodyCartDTO> updateList)
        {
            var customer = await GetCustomerFromSession();
            if (customer == null)
            {
                return Ok(ResponseDTO.BadRequest());
            }

            var cart = await _context.Carts.FirstOrDefaultAsync(o => o.CustomerId == customer.Id);
            if (cart == null)
            {
                return Ok(ResponseDTO.OkEmpty());
            }

            var cartItems = _context.CartItems
                .Include(c => c.Stock).ThenInclude(o => o.Shoes).ThenInclude(o => o.ShoesImages)
                .Include(c => c.Stock).ThenInclude(o => o.Size)
                .Where(o => o.CartId == cart.Id);


            // Update details
            foreach (var detail in updateList)
            {
                var updateItem = cartItems.FirstOrDefault(c => c.Stock.Id == detail.stockId);
                if (updateItem != null)
                {
                    if (detail.quantity > 0)
                    {
                        updateItem.Amount = detail.quantity;
                    }
                    else
                    {
                        _context.CartItems.Remove(updateItem);
                    }
                }
            }
            _context.SaveChanges();


            // Parse responses
            var items = new List<dynamic>();
            foreach (var item in cartItems)
            {
                items.Add(new
                {
                    stockId = item.Stock.Id,
                    shoesId = item.Stock.ShoesId,
                    name = item.Stock.Shoes.Name,
                    sizeName = item.Stock.Size.Name,
                    quantity = item.Amount,
                    price = item.Stock.Shoes.Price,
                    image = item.Stock.Shoes.ShoesImages.FirstOrDefault().ImagePath
                });
            }

            return Ok(ResponseDTO.Ok(items, items.Count));
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Get all session results for a given Questions Set.
 /// </summary>
 /// <param name="pQuestionsSetId">Questions set identifier.</param>
 public ResponseDTO <IEnumerable <SessionResultDTO> > GetSessionResults(int pQuestionsSetId)
 {
     using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
     {
         List <Session> sessions = bUoW.SessionRepository.GetByQuestionsSet(pQuestionsSetId).ToList();
         sessions.Sort();
         IEnumerable <SessionResultDTO> sessionResults = _mapper.Map <IEnumerable <SessionResultDTO> >(sessions);
         return(ResponseDTO <IEnumerable <SessionResultDTO> > .Ok(sessionResults));
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Finish the given session and calculate its score.
        /// </summary>
        /// <param name="pSessionId">Session identifier</param>
        /// <returns>The session result <see cref="SessionResultDTO"/>.</returns>
        public ResponseDTO <SessionResultDTO> FinishSession(int pSessionId)
        {
            using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
            {
                Session session = bUoW.SessionRepository.Get(pSessionId);
                session.Score = this.CalculateScore(session);
                bUoW.Complete();

                return(ResponseDTO <SessionResultDTO> .Ok($"Session ended! Your score is {session.Score}"));
            }
        }
Ejemplo n.º 15
0
        public void NewSessionShouldReturnOk()
        {
            _sessionServiceMock.Setup(service => service.NewSession(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>()))
            .Returns(ResponseDTO <SessionDTO> .Ok(new SessionDTO()));

            var response = _operativeServices.NewSession(1, 1, 1, 1);

            Assert.IsTrue(response.Success);
            Assert.AreEqual(ResponseCode.Ok, response.Code);
            Assert.NotNull(response.Data);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Gets all Questions Sets available.
 /// </summary>
 /// <returns>Questions set list.</returns>
 public ResponseDTO <IEnumerable <QuestionsSetDTO> > GetQuestionsSets()
 {
     using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
     {
         var questionsSets = _mapper.Map <IEnumerable <QuestionsSetDTO> >(bUoW.QuestionsSetRepository.GetAll().ToList());
         if (!questionsSets.Any())
         {
             throw new NoContentException("There are no questions sets in the database");
         }
         return(ResponseDTO <IEnumerable <QuestionsSetDTO> > .Ok(questionsSets));
     }
 }
Ejemplo n.º 17
0
        public void GetQuestionsSetsShouldReturnOk()
        {
            var mockResponse = ResponseDTO <IEnumerable <QuestionsSetDTO> > .Ok(new List <QuestionsSetDTO>());

            this._questionSetServiceMock.Setup(service => service.GetQuestionsSets()).Returns(mockResponse);

            var response = _operativeServices.GetQuestionsSets();

            Assert.IsTrue(response.Success);
            Assert.AreEqual(ResponseCode.Ok, response.Code);
            Assert.NotNull(response.Data);
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> GetUserById(int id)
        {
            var users = await repo.GetUserById(id);

            if (users == null)
            {
                return(BadRequest(ResponseDTO.NotFound()));
            }

            var items = mapper.Map <ResponseUserDto>(users);

            return(Ok(ResponseDTO.Ok(items)));
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Update(int id, [FromBody] ProviderDTO dto)
        {
            var entity = _mapper.Map <Provider>(dto);

            entity.Id = id;

            var updatedItem = await _repository.Update(entity);

            if (updatedItem == null)
            {
                return(Ok(ResponseDTO.BadRequest("Item ID is not existed.")));
            }

            return(Ok(ResponseDTO.Ok(entity)));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets next question for current session.
        /// </summary>
        /// <returns>The question.</returns>
        public ResponseDTO <QuestionDTO> NextQuestion()
        {
            if (CurrentSession == null)
            {
                return(ResponseDTO <QuestionDTO> .BadRequest("No active session."));
            }
            if (CurrentSession.RemainingQuestions.Count > 0)
            {
                QuestionDTO nextQuestion = CurrentSession.RemainingQuestions.First();
                CurrentSession.RemainingQuestions.RemoveAt(0);
                nextQuestion.ShowedMoment = DateTime.Now;

                return(ResponseDTO <QuestionDTO> .Ok(nextQuestion));
            }
            return(ResponseDTO <QuestionDTO> .NoContent("There are no more questions for the given session"));
        }
        public IActionResult ClientUpdateCustomer(int id, [FromBody] CustomerUpdateDTO dto)
        {
            var customer = _context.Customers.FirstOrDefault(c => c.Id == id);

            if (customer == null)
            {
                return(Ok(ResponseDTO.BadRequest("CustomerId is not found.")));
            }

            customer.PhoneNumber = dto.phoneNumber;
            customer.Email       = dto.email;
            customer.Gender      = dto.gender;
            customer.Name        = dto.name;
            _context.SaveChanges();
            return(Ok(ResponseDTO.Ok(customer)));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Register a new User.
        /// </summary>
        /// <param name="pUsername">Username.</param>
        /// <param name="pPassword">Password.</param>
        /// <param name="pConfirmPassword">Confirmed password.</param>
        public ResponseDTO <object> SignUp(string pUsername, string pPassword, string pConfirmPassword)
        {
            if (pUsername == null || pUsername.Length < 6)
            {
                return(ResponseDTO.BadRequest("Username must contain at least 6 characters."));
            }
            // Regex for username. Must starts with a letter and can only contain
            // alphanumeric characters or underscore (_)
            // \w in regex means word or underscore
            Regex regex = new Regex("^([a-zA-Z][a-zA-Z0-9])\\w*$");

            if (!regex.IsMatch(pUsername))
            {
                return(ResponseDTO.BadRequest("Username must starts with a letter and " +
                                              "can only contain alphanumeric characters and underscores."));
            }
            if (pPassword.Length < 6)
            {
                return(ResponseDTO.BadRequest("Password must contain at least 6 characters."));
            }
            if (!string.Equals(pPassword, pConfirmPassword))
            {
                return(ResponseDTO.BadRequest("Passwords do not match."));
            }
            User user = new User
            {
                Username = pUsername,
                Password = pPassword,
                Rol      = UserRol.Operator
            };

            using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
            {
                var existingUser = bUoW.UserRepository.Get(user.Username);
                if (existingUser != null)
                {
                    return(ResponseDTO.BadRequest("User already registered."));
                }

                bUoW.UserRepository.Add(user);
                bUoW.Complete();

                return(ResponseDTO.Ok("Successfully signed up! "));
            }
        }
        public async Task <IActionResult> UpdateAddress(int id, [FromBody] AddressDTO dto)
        {
            if (id == dto.Id)
            {
                return(BadRequest(ResponseDTO.BadRequest("URL ID and Item ID does not matched.")));
            }
            var entity = _mapper.Map <Address>(dto);

            entity.Id = id;

            var updatedItem = _context.Addresses.Update(entity);

            if (updatedItem == null)
            {
                return(BadRequest(ResponseDTO.BadRequest("Item ID is not existed.")));
            }
            return(Ok(ResponseDTO.Ok(entity)));
        }
Ejemplo n.º 24
0
        // Customer update + Address Update clone cai nay
        public async Task <IActionResult> UpdateShoes(int id, [FromBody] ShoesDTO dto)
        {
            if (id != dto.Id)
            {
                return(Ok(ResponseDTO.BadRequest("URL ID and Item ID does not matched.")));
            }
            var entity = _mapper.Map <Shoes>(dto);

            entity.Id = id;

            var updatedItem = await _repository.Update(entity);

            if (updatedItem == null)
            {
                return(Ok(ResponseDTO.BadRequest("Item ID is not existed.")));
            }
            return(Ok(ResponseDTO.Ok(entity)));
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Login for the given username and password.
 /// </summary>
 /// <returns>The authorized user if login is successful.</returns>
 /// <param name="pUsername">Username.</param>
 /// <param name="pPassword">Password.</param>
 public ResponseDTO <UserDTO> Login(string pUsername, string pPassword)
 {
     using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
     {
         User user = bUoW.UserRepository.Get(pUsername);
         // Non-existing user
         if (user == null)
         {
             return(ResponseDTO <UserDTO> .NotFound($"There is no user associated with the username {pUsername}"));
         }
         // Password matches with user's password: successful login
         if (string.Equals(user.Password, pPassword))
         {
             return(ResponseDTO <UserDTO> .Ok(_mapper.Map <UserDTO>(user)));
         }
         return(ResponseDTO <UserDTO> .Unauthorized("Incorrect password."));
     }
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Save the specified pQuestionsSet into database.
 /// </summary>
 /// <param name="pQuestionsSet">Questions set.</param>
 public ResponseDTO <object> Save(QuestionsSet pQuestionsSet)
 {
     if (pQuestionsSet == null)
     {
         throw new NullReferenceException("Questions Set cannot be null");
     }
     using (IUnitOfWork bUoW = _unitOfWorkFactory.GetUnitOfWork())
     {
         QuestionsSet entity = bUoW.QuestionsSetRepository.Get(pQuestionsSet.Id);
         if (entity == null)
         {
             throw new NotFoundException($"No questions set found with id {pQuestionsSet.Id}");
         }
         entity.ExpectedAnswerTime = pQuestionsSet.ExpectedAnswerTime;
         bUoW.Complete();
     }
     return(ResponseDTO.Ok("Questions Set successfully saved."));
 }
Ejemplo n.º 27
0
        // Helper method
        protected async Task <IActionResult> _UpdateItemForAdminAsync(Model model)
        {
            IActionResult response = BadRequest(ResponseDTO.NotFound());

            if (!(await _repository.ExistWhere(m => m.Id == model.Id)))
            {
                return(response);
            }

            var item = await _repository.Update(model);

            if (item == null)
            {
                return(response);
            }

            response = Ok(ResponseDTO.Ok(item));
            return(response);
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> UpdateUser(int id, UpdateDto dto)
        {
            var user = await repo.GetUserById(id);

            if (user == null)
            {
                return(BadRequest(ResponseDTO.NotFound()));
            }

            user.Username    = dto.Username;
            user.Email       = dto.Email;
            user.RoleId      = dto.RoleId;
            user.Name        = dto.Name;
            user.PhoneNumber = dto.PhoneNumber;

            await repo.Update(user);

            return(Ok(ResponseDTO.Ok(user)));
        }
Ejemplo n.º 29
0
        protected async Task <IActionResult> _AddItem(Model item)
        {
            IActionResult result = BadRequest(ResponseDTO.BadRequest());

            try
            {
                var insertedItem = await _repository.Add(item);

                result = Ok(ResponseDTO.Ok(insertedItem));
            }
            catch (DbUpdateException ex)
            {
                var res = ResponseDTO.BadRequest($"Cannot add new { typeof(Model).Name }.");
                result = BadRequest(res);
                _logger.LogError(ex.ToString());
            }

            return(result);
        }
Ejemplo n.º 30
0
        public async Task<IActionResult> ClientCartGet()
        {
            var customer = await GetCustomerFromSession();
            if (customer == null)
            {
                return Ok(ResponseDTO.BadRequest());
            }

            var cart = await _context.Carts.FirstOrDefaultAsync(o => o.CustomerId == customer.Id);
            if (cart == null)
            {
                return Ok(ResponseDTO.OkEmpty());
            }

            var cartItems = await _context.CartItems
                .Include(c => c.Stock).ThenInclude(o => o.Shoes).ThenInclude(o => o.ShoesImages)
                .Include(c => c.Stock).ThenInclude(o => o.Size)
                .Where(o => o.CartId == cart.Id)
                .ToListAsync();

            var items = new List<dynamic>();
            foreach (var item in cartItems)
            {
                items.Add(new
                {
                    stockId = item.Stock.Id,
                    shoesId = item.Stock.ShoesId,
                    name = item.Stock.Shoes.Name,
                    sizeName = item.Stock.Size.Name,
                    quantity = item.Amount,
                    price = item.Stock.Shoes.Price,
                    image = item.Stock.Shoes.ShoesImages.FirstOrDefault().ImagePath
                });
            }

            return Ok(ResponseDTO.Ok(items, items.Count));
        }