Esempio n. 1
0
        public async Task <PropertySearchListViewModel> CreateAsync(PropertySearchCreateViewModel model, string agentId)
        {
            if (string.IsNullOrEmpty(agentId))
            {
                throw new ArgumentException("Не е установен брокерът задаващ въпроса!");
            }

            if (!(await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Agent)) ||
                  await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Administrator))))
            {
                throw new NotAuthorizedUserException("Потребителят няма право на това действие! Само админи и брокери имат достъп !");
            }

            PropertySearches propertySearch = new PropertySearches
            {
                CityId = model.CityId,
                AdditionalInformation = model.AdditionalInformation,
                AgentId            = agentId,
                AreaInSquareMeters = model.AreaInSquareMeters,
                Areas        = model.Areas,
                IsRentSearch = model.IsRentSearch,
                PriceFrom    = model.PriceFrom,
                PriceTo      = model.PriceTo,
                UnitTypes    = new HashSet <PropertyTypes>(await _dbContext.PropertyTypes
                                                           .Where(pt => model.UnitTypeIds.Any(ut => pt.PropertyTypeId == ut))
                                                           .ToListAsync()),
                PersonSearcher = new PersonSearcher
                {
                    Name                  = model.PersonSearcher.Name,
                    PhoneNumber           = model.PersonSearcher.PhoneNumber,
                    Email                 = model.PersonSearcher.Email,
                    AdditionalInformation = model.PersonSearcher.AdditionalInformation
                }
            };

            _dbContext.PropertySearches.Add(propertySearch);
            await _dbContext.SaveChangesAsync();

            #region Create notification

            var creatorName = await _dbContext.Users
                              .Where(u => u.Id == propertySearch.AgentId)
                              .Select(a => a.FirstName + " " + a.LastName)
                              .FirstOrDefaultAsync();

            var notificationToCreate = new NotificationCreateViewModel
            {
                NotificationTypeId = (int)NotificationType.Property,
                NotificationLink   = "/propertysearches/details?id=" + propertySearch.Id,
                NotificationText   = creatorName + " добави търсене на имот с цена " + propertySearch.PriceFrom + "лв." + " - " + propertySearch.PriceTo + "лв."
            };

            await _notificationCreator.CreateGlobalNotification(notificationToCreate, propertySearch.AgentId);

            #endregion

            return(await GetAsync(propertySearch.Id));
        }
Esempio n. 2
0
        public async Task <TrainingListViewModel> CreateAsync(TrainingCreateViewModel model, string adminId)
        {
            if (string.IsNullOrEmpty(adminId))
            {
                throw new ArgumentException("Не е намерен администартора, който създава Обучение!");
            }

            if (!await _userManager.IsInRoleAsync(adminId, Enum.GetName(typeof(Role), Role.Administrator)))
            {
                throw new NotAuthorizedUserException("Потребителят няма право на това действие! Само админи имат право да създават обучения !");
            }

            if (model.TrainingDate == null)
            {
                throw new ArgumentException("Не е въведена дата на обучението!");
            }

            var training = new Model.Trainings
            {
                TrainingDate                = (DateTime)model.TrainingDate,
                TrainingTheme               = model.TrainingTheme,
                AdditionalDescription       = model.AdditionalDescription,
                TrainingMaterialsFolderLink = model.TrainingMaterialsFolderLink
            };

            _dbContext.Trainings.Add(training);
            await _dbContext.SaveChangesAsync();

            #region notification

            var notificationToCreate = new NotificationCreateViewModel
            {
                NotificationTypeId = (int)NotificationType.Learning,
                NotificationLink   = "/trainings/index?trainingId=" + training.Id,
                NotificationText   = "Ще се проведе обучение на тема: " + training.TrainingTheme + " в " +
                                     training.TrainingDate.ToString("dddd, dd.MM.yyyyг. hh:mmч.")
            };

            await _notificationCreator.CreateGlobalNotification(notificationToCreate, adminId);

            #endregion

            return(await Get(training.Id));
        }
Esempio n. 3
0
        public async Task <AgentQuestionListViewModel> Create(string question, string agentId)
        {
            if (string.IsNullOrEmpty(question))
            {
                throw new ArgumentException("Не е въведен въпрос!");
            }

            if (string.IsNullOrEmpty(agentId))
            {
                throw new ArgumentException("Не е намерен брокерът задаващ въпроса в системата!");
            }

            var questionToCreate = new Model.AgentQuestions.AgentQuestions
            {
                Question = question,
                AgentId  = agentId
            };

            _dbContext.AgentQuestions.Add(questionToCreate);
            await _dbContext.SaveChangesAsync();

            var createdQuestion = await Get(questionToCreate.Id, agentId);

            #region Create Notification

            var notificationToCreate = new NotificationCreateViewModel
            {
                NotificationTypeId  = (int)NotificationType.Question,
                NotificationPicture = "",
                NotificationLink    = "/agentquestions/index?questionId=" + createdQuestion.Id,
                NotificationText    = createdQuestion.AskingAgentName + " пита: " + createdQuestion.Question
            };

            await _notificationCreator.CreateGlobalNotification(notificationToCreate, agentId);

            #endregion

            return(createdQuestion);
        }
Esempio n. 4
0
        /// <summary>
        /// Create post
        /// </summary>
        /// <param name="model"></param>
        /// <param name="postCreatorId"></param>
        /// <returns></returns>
        public async Task <PostDetailViewModel> Create(PostCreateViewModel model, string postCreatorId)
        {
            //Does the user exist in the db
            if (!await userManager.Users.AnyAsync(u => u.Id == postCreatorId))
            {
                throw new ArgumentException("Не е намерен потребителят с който сте логнати!");
            }

            if (!await ThemesManager.Exists(model.ThemeId))
            {
                throw new ArgumentException("Не е намерена темата в която искате да създадете пост!");
            }

            var postToCreate = Mapper.Map <Posts>(model, opts => opts.Items.Add("UserId", postCreatorId));

            postToCreate.Tags = new HashSet <Tags>(model.Tags.Select(t => new Tags {
                Name = t
            }).ToList());

            unitOfWork.PostsRepository.Add(postToCreate);
            await unitOfWork.SaveAsync();

            var postRelativeDirPath = Path.Combine(ConfigurationManager.AppSettings["BlogPostFolderRelativePath"], postToCreate.PostId.ToString());
            var postPhysicalDirPath = Path.Combine(HttpRuntime.AppDomainAppPath.TrimEnd('\\'), postRelativeDirPath.TrimStart('\\'));

            Directory.CreateDirectory(postPhysicalDirPath);
            try
            {
                foreach (HttpPostedFileBase image in model.ImageFiles)
                {
                    if (image == null)
                    {
                        continue;
                    }

                    var imagePath = Path.Combine(postPhysicalDirPath, image.FileName);
                    ImageHelpers.SaveImage(image, imagePath);
                    ImageHelpers.SaveAsWebP(image, imagePath);

                    var imageRelPath = Path.Combine(postRelativeDirPath, image.FileName);
                    postToCreate.Images.Add(new PostImages {
                        ImagePath = imageRelPath
                    });
                }

                //This edit is cuz, we first add the property and use its id for the images Directory
                unitOfWork.PostsRepository.Edit(postToCreate);
                await unitOfWork.SaveAsync();

                var post = Mapper.Map <PostDetailViewModel>(postToCreate);

                #region Notifications

                var notificationToCreate = new NotificationCreateViewModel
                {
                    NotificationTypeId  = (int)NotificationType.Post,
                    NotificationPicture = post.ImageUrls.Any() ? post.ImageUrls[0] : "",
                    NotificationLink    = "/posts/details?id=" + post.PostId,
                    NotificationText    = post.AuthorName + " публикува пост: " + post.Title
                };

                await _notificationCreator.CreateGlobalNotification(notificationToCreate, postCreatorId);

                #endregion

                return(post);
            }
            catch (Exception e)
            {
                //if something wrong delete the post from db and filesystem
                unitOfWork.PostsRepository.Delete(postToCreate);
                await unitOfWork.SaveAsync();

                Directory.Delete(postPhysicalDirPath, true);
                throw;
            }
        }
Esempio n. 5
0
        public async Task <RecordListViewModel> CreateRecord(CreateRecordViewModel model, string agentId)
        {
            if (!await IsAgentExisting(agentId))
            {
                throw new ArgumentException("Агентът, не е намерен!");
            }

            var record = new ContactsDiary
            {
                Address = model.Address,
                AdditionalDescription = model.AdditionalDescription,
                AgentId               = agentId,
                CityDistrict          = model.CityDistrict,
                CityId                = model.CityId,
                ContactedPersonTypeId = model.ContactedPersonTypeId,
                DealTypeId            = model.DealTypeId,
                Name = model.Name,
                NegotiationStateId = model.NegotiationStateId,
                PhoneNumber        = model.PhoneNumber,
                PropertySource     = model.PropertySource,
                PropertyTypeId     = model.PropertyTypeId
            };

            dbContext.ContactsDiary.Add(record);
            await dbContext.SaveChangesAsync();

            var createdClient = await dbContext.ContactsDiary
                                .Include(r => r.Agent)
                                .Include(r => r.NegotiationState)
                                .Include(r => r.ContactedPersonType)
                                .Include(r => r.DealType)
                                .Include(r => r.PropertyType)
                                .Where(c => c.Id == record.Id).Select(r => new RecordListViewModel
            {
                Id                    = r.Id,
                CreatedOn             = r.CreatedOn,
                PhoneNumber           = r.PhoneNumber,
                Name                  = r.Name,
                CityId                = r.CityId,
                CityName              = r.City.CityName,
                CityDistrict          = r.CityDistrict,
                Address               = r.Address,
                PropertySource        = r.PropertySource,
                AdditionalDescription = r.AdditionalDescription,
                ContactedPersonTypeId = r.ContactedPersonTypeId,
                ContactedPersonType   = r.ContactedPersonType.ContactedPersonType,
                DealTypeId            = r.DealTypeId,
                DealType              = r.DealType.DealType,
                PropertyTypeId        = r.PropertyTypeId,
                PropertyType          = r.PropertyType.PropertyTypeName,
                NegotiationStateId    = r.NegotiationStateId,
                NegotiationState      = r.NegotiationState.State,
                RecordColor           = r.NegotiationState.Color,
                AgentId               = r.AgentId,
                AgentName             = r.Agent.FirstName + " " + r.Agent.LastName
            })
                                .FirstOrDefaultAsync() ?? throw new ContentNotFoundException("Не е намерен записът!");

            #region Notifications

            var notificationToCreate = new NotificationCreateViewModel
            {
                NotificationTypeId  = (int)NotificationType.Contact,
                NotificationPicture = "",
                NotificationLink    = "/contactsdiary/index?contactId=" + record.Id,
                NotificationText    = createdClient.AgentName + " добави контакт: " + createdClient.ContactedPersonType + " - тел:" + createdClient.PhoneNumber
            };

            await notificationCreator.CreateGlobalNotification(notificationToCreate, agentId);

            #endregion

            return(createdClient);
        }
Esempio n. 6
0
        public async Task <FileListViewModel> Create(FileCreateViewModel model, string agentId)
        {
            if (string.IsNullOrEmpty(agentId))
            {
                throw new NotAuthorizedUserException("Само потребители могат да качват файлове!");
            }

            if (!await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Administrator)) &&
                !await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Agent)) &&
                !await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Maintenance)))
            {
                throw new NotAuthorizedUserException("Нямате право да извършвате това действие!");
            }

            if (await Exist(fileName: model.Name, folderId: model.FolderId))
            {
                throw new ArgumentException("Съществува файл с това име в тази папка!");
            }


            string filePath = Path.GetFileNameWithoutExtension(model.Name) + Path.GetExtension(model.File.FileName);

            if (model.FolderId != null)
            {
                filePath = Path.Combine(await _dbContext.Folders
                                        .Where(f => f.Id == model.FolderId).Select(f => f.RelativePath)
                                        .FirstOrDefaultAsync() ?? "", filePath);
            }
            else
            {
                filePath = Path.Combine(_baseMaterialsPath, filePath);
            }

            var physicalFilePath = Path.Combine(HttpRuntime.AppDomainAppPath.TrimEnd('\\'), filePath.Replace('/', '\\').TrimStart('\\'));

            try
            {
                model.File.SaveAs(physicalFilePath);
            }
            catch (Exception)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath) ?? throw new ArgumentException("Пътят е грешен"));
                model.File.SaveAs(physicalFilePath);
            }

            var file = new Files
            {
                Name         = Path.GetFileName(filePath),
                FolderId     = model.FolderId,
                AgentId      = agentId,
                SizeInBytes  = model.File.ContentLength,
                Type         = MimeMapping.GetMimeMapping(model.File.FileName),
                RelativePath = filePath
            };

            try
            {
                _dbContext.Files.Add(file);
                await _dbContext.SaveChangesAsync();
            }
            catch (Exception)
            {
                File.Delete(physicalFilePath);
                throw;
            }


            var createdFile = await Get(file.Id, agentId);

            #region Notifications

            var notificationToCreate = new NotificationCreateViewModel
            {
                NotificationTypeId  = (int)NotificationType.Material,
                NotificationPicture = "",
                NotificationLink    = "/agentmaterials/index?fileId=" + createdFile.Id + (createdFile.FolderId != null ? "&folderId=" + createdFile.FolderId : ""),
                NotificationText    = createdFile.AgentName + " добави материал: " + createdFile.Name
            };

            await _notificationCreator.CreateGlobalNotification(notificationToCreate, agentId);

            #endregion

            return(createdFile);
        }