Beispiel #1
0
        private async Task <ServiceResult> CloseAsync(Order order, Guid userId)
        {
            if (order.DateOfClosed.HasValue)
            {
                return(ServiceResultFactory.Success);
            }

            if (order.DateOfApproved.HasValue == false && order.DateOfRejected.HasValue == false)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(CloseAsync), "Order should be approved or rejected."));
            }

            order.DateOfClosed = DateTime.UtcNow;
            order.CloseUserId  = userId;

            _context.Orders.Update(order);

            return(await _context.SaveAsync(nameof(CloseAsync)));
        }
Beispiel #2
0
        public async Task <ServiceResult> ProccessOrderAsync(ProcessOrderType processOrder, Guid id, Guid userId)
        {
            var userExist = await _context.Users.AnyAsync(x => x.Id == userId);

            if (userExist == false)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(ProccessOrderAsync), "User not found."));
            }

            var order = await this.FindByAsync(x => x.Id == id);

            if (order == null)
            {
                return(ServiceResultFactory.NotFound);
            }

            ServiceResult result;

            switch (processOrder)
            {
            case ProcessOrderType.Approve:
                result = await this.ApproveAsync(order, userId);

                break;

            case ProcessOrderType.Reject:
                result = await this.RejectAsync(order, userId);

                break;

            case ProcessOrderType.Close:
                result = await this.CloseAsync(order, userId);

                break;

            default:
                throw new NotImplementedException(nameof(ProcessOrderType));
            }

            result.SetModelIfSuccess(order);

            return(result);
        }
Beispiel #3
0
        public async Task <ServiceResult> AddAsync(ShopItem model)
        {
            Check.NotNull(model, nameof(model));

            var menuItemExist = await _context.MenuItems.AnyAsync(x => x.Id == model.MenuItemId);

            if (menuItemExist == false)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(AddAsync), $"MenuItem not found with id: '{model.MenuItemId}'."));
            }

            _context.ShopItems.Add(model);

            var result = await _context.SaveAsync(nameof(AddAsync));

            result.SetModelIfSuccess(model);

            return(result);
        }
        public async Task <ServiceResult <InfoChannelMessageResponseViewModel> > GetSingle(int id)
        {
            var model = await _repository.GetSingleAsync(id);

            if (model == null)
            {
                return(ServiceResultFactory.Success <InfoChannelMessageResponseViewModel>(null));
            }

            var viewModel = new InfoChannelMessageResponseViewModel
            {
                Id        = model.Id,
                IsVisible = model.Visible,
                Subject   = model.Title,
                Message   = model.Message
            };

            return(ServiceResultFactory.Success(viewModel));
        }
        public async Task <ServiceResult <PaginatedListResult <PointOfSalesResponseViewModel> > > Search(PointOfSalesRequestViewModel viewModel)
        {
            var paginatedListWithModel = await _repository.Search(viewModel);

            // Mapping
            List <PointOfSalesResponseViewModel> Mapping(List <Store> list)
            {
                return(list?
                       .Select(model => new PointOfSalesResponseViewModel
                {
                    // TODO
                })
                       .ToList());
            }

            var paginatedListWithViewModel = paginatedListWithModel.Copy(Mapping);

            return(ServiceResultFactory.Success(paginatedListWithViewModel));
        }
Beispiel #6
0
        public async Task <ServiceResult> AddAsync(Order model)
        {
            Check.NotNull(model, nameof(model));

            var cartExist = await _context.Carts.AnyAsync(x => x.Id == model.CartId);

            if (cartExist == false)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(AddAsync), $"Cart not found with id: '{model.CartId}'."));
            }

            _context.Orders.Add(model);

            var result = await _context.SaveAsync(nameof(AddAsync));

            result.SetModelIfSuccess(model);

            return(result);
        }
        public async Task <ServiceResult <bool> > Delete(int companyId, int id)
        {
            if (id <= 0)
            {
                throw new ArgumentException("Argument should be greater than 0", nameof(id));
            }

            var model = await _repository.GetSingleByCompanyAsync(companyId, id);

            if (model == null)
            {
                return(ServiceResultFactory.Fail <bool>("Item not found"));
            }

            _repository.Delete(model);
            var changes = await _repository.SaveChangesAsync();

            return(ServiceResultFactory.Success(changes > 0));
        }
        public async Task <ServiceResult> AddAsync(InfoObject model)
        {
            Check.NotNull(model, nameof(model));

            var contentGroupExist = await _context.ContentGroups.AnyAsync(x => x.Id == model.ContentGroupId);

            if (contentGroupExist == false)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(model.ContentGroupId), $"ContentGroup not found with id: '{model.ContentGroupId}'."));
            }

            _context.InfoObjects.Add(model);
            _context.History.Add(ChangeHistory.Create(TableName.InfoObject, ActionType.Add));

            var result = await _context.SaveAsync(nameof(AddAsync));

            result.SetModelIfSuccess(model);

            return(result);
        }
Beispiel #9
0
        public async Task <ServiceResult <PaginatedListResult <InfoChannelMessagesDashboardResponseViewModel> > > InfoChannelMessages()
        {
            var paginatedListWithModel = await _infoChannelMessageRepository.Search(new InfoChannelMessagesRequestViewModel());

            List <InfoChannelMessagesDashboardResponseViewModel> Mapping(List <InfoChannelMessage> list)
            {
                return(list?
                       .Select(model => new InfoChannelMessagesDashboardResponseViewModel
                {
                    Id = model.Id,
                    Subject = model.Title,
                    Message = model.Message,
                    Date = model.UpdatedOn ?? model.CreatedOn
                })
                       .ToList());
            }

            var paginatedListWithViewModel = paginatedListWithModel.Copy(Mapping);

            return(ServiceResultFactory.Success(paginatedListWithViewModel));
        }
        public async Task <ServiceResult> SaveAsync(string code)
        {
            try
            {
                await this.SaveChangesAsync();

                return(ServiceResultFactory.Success);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(ServiceResultFactory.BadRequestResult(code, ex.InnerException.Message));
            }
            catch (DbUpdateException ex)
            {
                return(ServiceResultFactory.BadRequestResult(code, ex.InnerException.Message));
            }
            catch (Exception ex)
            {
                return(ServiceResultFactory.InternalServerErrorResult(ex.InnerException.Message));
            }
        }
        public async Task <ServiceResult <CustomerResponseViewModel> > GetSingle(int companyId, int id)
        {
            var model = await _repository.GetSingleByCompanyAsync(companyId, id);

            if (model == null)
            {
                return(ServiceResultFactory.Success <CustomerResponseViewModel>(null));
            }

            var viewModel = new CustomerResponseViewModel
            {
                Id = model.Id,
                UsernameOrEmail  = model.Email,
                Name             = model.Name,
                CompanysMainUser = model.IsCompany,
                //IsSeller = model.IsSeller, // TODO
                //IsActive = model.IsActive, // TODO
            };

            return(ServiceResultFactory.Success(viewModel));
        }
        public async Task <ServiceResult <PaginatedListResult <ProductGroupsResponseViewModel> > > SearchListOfProductGroups(ProductGroupsRequestViewModel viewModel)
        {
            var paginatedListWithModel = await _repository.SearchProductCategories(viewModel);

            // Mapping
            List <ProductGroupsResponseViewModel> Mapping(List <ProductCategory> list)
            {
                return(list?
                       .Select(model => new ProductGroupsResponseViewModel
                {
                    Id = model.Id,
                    Name = model.Name,
                    //KmPercent = model.
                })
                       .ToList());
            }

            var paginatedListWithViewModel = paginatedListWithModel.Copy(Mapping);

            return(ServiceResultFactory.Success(paginatedListWithViewModel));
        }
        public async Task <ServiceResult> AddAsync(AppUser model, string password)
        {
            Check.NotNull(model, nameof(model));
            Check.NotNullOrEmpty(model.Username, nameof(model.Username));
            Check.NotNullOrEmpty(model.Email, nameof(model.Email));
            Check.NotNullOrEmpty(password, nameof(password));

            // Doesn't supported StringComparison.OrdinalIgnoreCase by SQL
            var usernameExist = await this.ExistAsync(x => model.Username.ToLower() == x.Username.ToLower());

            if (usernameExist)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(AddAsync), "Username is already taken."));
            }

            var emailExist = await this.ExistAsync(x => model.Email.ToLower() == x.Email.ToLower());

            if (emailExist)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(AddAsync), "Email is already taken."));
            }

            model.Role = Role.Normalize(model.Role);
            if (string.IsNullOrEmpty(model.Role))
            {
                return(ServiceResultFactory.BadRequestResult(nameof(AddAsync), "Incorrect role name."));
            }

            var(passwordHash, passwordSalt) = _passwordManager.CreatePasswordHash(password);
            model.PasswordHash = passwordHash;
            model.PasswordSalt = passwordSalt;

            _context.Users.Add(model);

            var result = await _context.SaveAsync(nameof(AddAsync));

            result.SetModelIfSuccess(model);

            return(result);
        }
Beispiel #14
0
        public async Task <ServiceResult> AddAsync(MenuItem model)
        {
            Check.NotNull(model, nameof(model));
            Check.NotNullOrEmpty(model.Text, nameof(model.Text));

            // Doesn't supported StringComparison.OrdinalIgnoreCase by SQL
            var menuItemExist = await this.ExistAsync(x => model.Text.ToLower() == x.Text.ToLower());

            if (menuItemExist)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(AddAsync), $"MenuItem text already exist."));
            }

            _context.MenuItems.Add(model);
            _context.History.Add(ChangeHistory.Create(TableName.MenuItem, ActionType.Add));

            var result = await _context.SaveAsync(nameof(AddAsync));

            result.SetModelIfSuccess(model);

            return(result);
        }
        public async Task <ServiceResult <PaginatedListResult <CompanyLicencesResponseViewModel> > > Search(CompanyLicencesRequestViewModel viewModel)
        {
            var paginatedListWithModel = await _repository.Search(viewModel);

            List <CompanyLicencesResponseViewModel> Mapping(List <CompanyLicence> list)
            {
                return(list?
                       .Select(model => new CompanyLicencesResponseViewModel
                {
                    Id = model.Id,
                    ExpiresOn = model.ValidToDate,
                    LicenceKey = model.LicenceKey,
                    LincenceUpdatingDateTime = model.ValidToDate,
                    Version = model.Version
                })
                       .ToList());
            }

            var paginatedListWithViewModel = paginatedListWithModel.Copy(Mapping);

            return(ServiceResultFactory.Success(paginatedListWithViewModel));
        }
        public async Task <IServiceResult <List <GameDetails>, ApiErrorModel> > GetGamesForSteamIdAsync(string steamId64)
        {
            var games = await _steamService.GetGamesFromProfileAsync(steamId64);

            //Example of an error that is unexpected and should not be displayed in the browser
            if (games == null)
            {
                var em = new ApiErrorModel()
                {
                    Errors = new List <string>()
                    {
                        $"Failed to find games for Steam Id: {steamId64}"
                    },
                    Type = ApiErrorModel.TYPE_SILENT_ERROR
                };
                return(ServiceResultFactory.Error <List <GameDetails>, ApiErrorModel>(em));
            }

            //Type of error that is expected and should be relayed back to the client as a toast message
            if (games.Count == 0)
            {
                var em = new ApiErrorModel()
                {
                    Errors = new List <string>()
                    {
                        $"No games found for Steam Id: {steamId64}"
                    },
                    Type = ApiErrorModel.TYPE_TOAST_ERROR
                };

                return(ServiceResultFactory.Error <List <GameDetails>, ApiErrorModel>(em));
            }

            var returnValues = await _gameSearchService.GetAsync(games.Select(g => g.AppId).ToArray());


            return(ServiceResultFactory.Ok <List <GameDetails>, ApiErrorModel>(returnValues));
        }
        public async Task <ServiceResult <PaginatedListResult <InfoChannelMessagesResponseViewModel> > > Search(InfoChannelMessagesRequestViewModel viewModel)
        {
            var paginatedListWithModel = await _repository.Search(viewModel);

            // Mapping
            List <InfoChannelMessagesResponseViewModel> Mapping(List <InfoChannelMessage> list)
            {
                return(list?
                       .Select(model => new InfoChannelMessagesResponseViewModel
                {
                    Id = model.Id,
                    Subject = model.Title,
                    Message = model.Message,
                    Date = model.VisibleUntil,
                    IsVisible = model.Visible
                })
                       .ToList());
            }

            var paginatedListWithViewModel = paginatedListWithModel.Copy(Mapping);

            return(ServiceResultFactory.Success(paginatedListWithViewModel));
        }
        public async Task <IServiceResult <GameDetails, ApiErrorModel> > GetGameDetailsAsync(long appId)
        {
            var gameDetails = await _steamService.GetGameDetailsAsync(appId);

            if (gameDetails.HasError)
            {
                return(gameDetails);
            }

            if (gameDetails.Value == null)
            {
                return(ServiceResultFactory.Error <GameDetails, ApiErrorModel>(new ApiErrorModel()
                {
                    Errors = new List <string>()
                    {
                        $"Failed to find game for app id: {appId}"
                    },
                    Type = ApiErrorModel.TYPE_SILENT_ERROR
                }));
            }

            return(ServiceResultFactory.Ok <GameDetails, ApiErrorModel>(gameDetails.Value));
        }
        public async Task Add_Model_Valid_Result_InternalServerError()
        {
            _context
            .Setup(x => x.SaveAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(ServiceResultFactory.InternalServerErrorResult(It.IsAny <string>())));

            // Arrange
            var userService = new UserService(_context.Object, _passwordManager.Object);
            var user        = new AppUser
            {
                Username = "******",
                Email    = "*****@*****.**",
                Role     = Role.Admin
            };

            // Act
            var result = await userService.AddAsync(user, Constants.PASSWORD);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(ServiceResultKey.InternalServerError, result.Key);
            Assert.NotEmpty(result.Errors);
        }
        public async Task <ServiceResult <SupplierResponseViewModel> > GetSingle(int id)
        {
            var model = await _repository.GetSingleAsync(id);

            if (model == null)
            {
                return(ServiceResultFactory.Success <SupplierResponseViewModel>(null));
            }

            var viewModel = new SupplierResponseViewModel
            {
                CompanyId           = model.CompanyId,
                Name                = model.Name,
                RegistrationNumber  = model.CompanyRegNumber,
                Phone               = model.Phone,
                Email               = model.Email,
                Iban                = model.BankIban,
                BicSwift            = model.BankSwift,
                PaymentPeriodInDays = model.DeadlineDays,
                Comment             = model.Comment
            };

            return(ServiceResultFactory.Success(viewModel));
        }
Beispiel #21
0
        private async Task <ServiceResult> RejectAsync(Order order, Guid userId)
        {
            if (order.DateOfRejected.HasValue)
            {
                return(ServiceResultFactory.Success);
            }

            if (order.DateOfApproved.HasValue)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(RejectAsync), "Order is already approved."));
            }

            if (order.DateOfClosed.HasValue)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(RejectAsync), "Order is already closed."));
            }

            order.DateOfRejected = DateTime.UtcNow;
            order.RejectUserId   = userId;

            _context.Orders.Update(order);

            return(await _context.SaveAsync(nameof(RejectAsync)));
        }
        public async Task <ServiceResult> Edit(Guid id, [FromBody] InfoObjectEditModel apiEntity)
        {
            if (string.Equals(apiEntity.Type, InfoObjectType.Image.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // validate file exist
                var fileExistValidationAttribute = new FileExistValidationAttribute(Constants.WEB_CONTENT_ROOT_PATH, Constants.DEFAULT_PATH_TO_IMAGE);
                var validationResult             = fileExistValidationAttribute.IsValid(apiEntity.Content);
                if (validationResult != ValidationResult.Success)
                {
                    return(ServiceResultFactory.BadRequestResult(nameof(apiEntity.Content), validationResult.ErrorMessage));
                }
            }

            var entity = InfoObjectEditModel.Map(apiEntity, id);

            var result = await _infoObjectService.UpdateAsync(entity);

            if (result.TryCastModel(out InfoObject infoObject))
            {
                result.ViewModel = InfoObjectViewModel.Map(infoObject);
            }

            return(result);
        }
        public async Task <ServiceResult <int> > Create(PointOfSaleCreateOrUpdateRequestViewModel viewModel)
        {
            var model = new Store();

            MapViewModelToModel(viewModel, model);

            var validator        = new PointOfSaleCreateOrUpdateRequestViewModelValidator();
            var validationResult = await validator.ValidateAsync(model);

            if (!validationResult.IsValid)
            {
                return(ServiceResultFactory.Fail <int>(validationResult));
            }

            await _repository.AddAsync(model);

            var changes = await _repository.SaveChangesAsync();

            if (changes == 0)
            {
                return(ServiceResultFactory.Fail <int>("Insert fails"));
            }
            return(ServiceResultFactory.Success(model.Id));
        }
        public async Task <ServiceResult <bool> > Update(int id, ProductCreateOrUpdateRequestViewModel viewModel)
        {
            if (id <= 0)
            {
                throw new ArgumentException("Argument should be greater than 0", nameof(id));
            }

            var model = await _repository.GetSingleAsync(id);

            MapViewModelToModel(viewModel, model);

            var validator        = new ProductCreateOrUpdateRequestViewModelValidator();
            var validationResult = await validator.ValidateAsync(model);

            if (!validationResult.IsValid)
            {
                return(ServiceResultFactory.Fail <bool>(validationResult));
            }

            _repository.Update(model);
            var changes = await _repository.SaveChangesAsync();

            return(ServiceResultFactory.Success(changes > 0));
        }
Beispiel #25
0
        public async Task <ServiceResult> UpdateAsync(ShopItemDetail model)
        {
            Check.NotNull(model, nameof(model));

            var shopItemDetail = await _context.ShopItemDetails.FirstOrDefaultAsync(x => x.Id == model.Id);

            if (shopItemDetail == null)
            {
                return(ServiceResultFactory.NotFound);
            }

            var changed = false;

            // update shopItem
            if (Utility.IsModified(shopItemDetail.ShopItemId, model.ShopItemId))
            {
                var shopItemExist = await _context.ShopItems.AnyAsync(x => x.Id == model.ShopItemId);

                if (shopItemExist == false)
                {
                    return(ServiceResultFactory.BadRequestResult(nameof(UpdateAsync), $"ShopItem not found with id: '{model.ShopItemId}'."));
                }

                shopItemDetail.ShopItemId = model.ShopItemId;
                changed = true;
            }

            // update suborder
            if (Utility.IsModified(shopItemDetail.SubOrder, model.SubOrder))
            {
                shopItemDetail.SubOrder = model.SubOrder;
                changed = true;
            }

            // update price
            if (Utility.IsModified(shopItemDetail.Price, model.Price))
            {
                shopItemDetail.Price = model.Price;
                changed = true;
            }

            // update kind
            if (Utility.IsModified(shopItemDetail.Kind, model.Kind))
            {
                shopItemDetail.Kind = model.Kind;
                changed             = true;
            }

            // update quantity
            if (Utility.IsModified(shopItemDetail.Quantity, model.Quantity))
            {
                shopItemDetail.Quantity = model.Quantity;
                changed = true;
            }

            if (changed == false)
            {
                return(ServiceResultFactory.BadRequestResult(nameof(UpdateAsync), "Nothing to update."));
            }

            _context.ShopItemDetails.Update(shopItemDetail);

            var result = await _context.SaveAsync(nameof(UpdateAsync));

            result.SetModelIfSuccess(shopItemDetail);

            return(result);
        }
Beispiel #26
0
 public IServiceResult <Page <T>, ApiErrorModel> Page(Dictionary <string, int> paging)
 {
     return(ServiceResultFactory.Error <Page <T>, ApiErrorModel>(_em));
 }
        public IServiceQueryResult <SupplierInfoData> RetrieveSupplierInfo(object supplierId)
        {
            SupplierInfoData result = Repository.RetrieveSupplierInfo(supplierId);

            return(ServiceResultFactory.BuildServiceQueryResult <SupplierInfoData>(result));
        }
        public IServiceQueryResultList <SupplierInfoData> Search(SupplierCriteria criteria)
        {
            IEnumerable <SupplierInfoData> result = Repository.Search(criteria);

            return(ServiceResultFactory.BuildServiceQueryResult <SupplierInfoData>(result));
        }
        public IServiceQueryResultList <ContactData> SearchByEmployee(object employeeId)
        {
            IEnumerable <ContactData> result = Repository.SearchByEmployee(employeeId);

            return(ServiceResultFactory.BuildServiceQueryResult <ContactData>(result));
        }
        public IServiceQueryResultList <ContactData> SearchByCustomer(object customerId)
        {
            IEnumerable <ContactData> result = Repository.SearchByCustomer(customerId);

            return(ServiceResultFactory.BuildServiceQueryResult <ContactData>(result));
        }