Esempio n. 1
0
        public async Task <ImagemViewModel> Inserir(ImagemViewModel imagemViewModel)
        {
            try
            {
                var imagem = ConvertModelMapper <Imagem, ImagemViewModel>(imagemViewModel);

                imagem.DataCadastro = DateTime.Now;
                imagem.IdUsuario    = IdUsuario;

                string nomeFisicoArquivoBlob = ObterNomeFisicoArquivo(imagem.Formato);
                byte[] image = StringHelper.Base64ToArrayByte(imagemViewModel.Base64);

                if (!_notificationService.ValidEntity(imagem))
                {
                    return(null);
                }

                imagem.UrlImagemBlob = await _fileRepository.Upload(nomeFisicoArquivoBlob, image);

                imagem.NomeImagemBlob = nomeFisicoArquivoBlob;

                await _imagemRepository.InserirAsync(imagem);

                return(ConvertModelMapper <ImagemViewModel, Imagem>(imagem));
            }
            catch
            {
                _notificationService.AddNotification("Erro ao tentar inserir a imagem", "Houve uma falha ao tentar inserir a imagem, por favor, tente novamente.");
                return(null);
            }
        }
        public ActionResult AddTicket(FormCollection collection)
        {
            var ticket = _kanbanService.AddTicket(collection, _userService.GetUserIdByUsername(User.Identity.Name));

            //notifications for assignees
            var assigneesNotification = _notificationService.AddNotification("New ticket created!", "You've been assigned to newly created ticket: " + ticket.Name + ".");

            if (collection["assignees"] != null)
            {
                foreach (var userId in collection["assignees"].Split(',').ToList())
                {
                    _notificationService.AddUserNotification(assigneesNotification.Id, userId);
                }
            }

            //notifications for watchers
            var watchersNotification = _notificationService.AddNotification("New ticket created!", "You've been assigned to newly created ticket: " + ticket.Name + ", as watcher!");

            if (collection["watchers"] != null)
            {
                foreach (var userId in collection["watchers"].Split(',').ToList())
                {
                    _notificationService.AddUserNotification(watchersNotification.Id, userId);
                }
            }

            ViewBag.AssigneesNotification = assigneesNotification.Id;
            ViewBag.WatchersNotification  = watchersNotification.Id;

            return(PartialView("_Ticket", ticket));
        }
Esempio n. 3
0
        public async Task <bool> DemoteModerator(string username)
        {
            var user = await userManager.FindByNameAsync(username);

            if (user != null)
            {
                var isInRole = await userManager.IsInRoleAsync(user, "moderator");

                if (user != null && isInRole)
                {
                    var resultDel = await userManager.RemoveFromRoleAsync(user, "moderator");

                    var resultAdd = await userManager.AddToRoleAsync(user, "user");

                    if (resultAdd.Succeeded && resultDel.Succeeded)
                    {
                        var profileToId = (await context
                                           .Profiles
                                           .Include(p => p.User)
                                           .FirstOrDefaultAsync(p => p.User.UserName == username))
                                          .Id;

                        var profileTo = await profileService.GetSimpleProfileById(profileToId);

                        var profileFrom = -1;
                        var text        = "У вас забрали права модератора";
                        await notificationService.AddNotification(profileTo, profileFrom, text, null, null);

                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 4
0
        public async Task <ArquivoIdiomaViewModel> Inserir(ArquivoIdiomaViewModel model)
        {
            try
            {
                var arquivoIdioma = ConvertModelMapper <ArquivoIdioma, ArquivoIdiomaViewModel>(model);

                arquivoIdioma.NomeArquivoBlob = ObterNomeFisicoArquivo();
                byte[] arquivo = StringHelper.Base64ToArrayByte(model.Arquivo.Split(",")[1]);

                if (!_notificationService.ValidEntity(arquivoIdioma))
                {
                    return(null);
                }

                arquivoIdioma.UrlArquivoBlob = await _fileRepository.Upload(arquivoIdioma.NomeArquivoBlob, arquivo);

                var arquivoResponse = await _arquivoIdiomaRepository.InserirAsync(arquivoIdioma);

                return(ConvertModelMapper <ArquivoIdiomaViewModel, ArquivoIdioma>(arquivoResponse));
            }
            catch (Exception ex)
            {
                _notificationService.AddNotification("Erro ao salvar arquivo de idioma", "Erro ao tentar salvar o Arquivo de Idioma, tente novamente.");
                return(null);
            }
        }
        public async Task <IActionResult> ForgetPassword(ForgetPasswordViewModel model)
        {
            SetPageContent("forgetpassword");

            if (ModelState.IsValid)
            {
                var user = _userManager.Users.FirstOrDefault(i => i.PhoneNumber == model.CellPhone);
                if (user == null || !(await _userManager.IsPhoneNumberConfirmedAsync(user)))
                {
                    ModelState.AddModelError("", "Kullanıcı kaydı bulunamadı. Lütfen tekrar deneyiniz.");
                    return(View(model));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.RouteUrl("resetpassword", new { userId = user.Id, code = code });

                _notificationService.AddNotification(user.Id, NotificationTypes.ForgetPassMail, param: callbackUrl);

                return(SetTransactionResult(
                           string.Format("Şifre yenileme maili {0} adresine başarılı bir şekilde gönderilmiştir. Mailinize gelecek şifre yenileme linki ile şifrenizi değiştirebilirsiniz.", Utils.MaskEmail(user.Email)),
                           Url.RouteUrl("home"),
                           TransactionType.Success
                           ));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 6
0
        async public Task <TransactionResult> AddEmploye(string userId, EmployeFormViewModel model)
        {
            try
            {
                var user = new User
                {
                    FullName             = model.FullName,
                    UserName             = model.Email,
                    PhoneNumber          = model.CellPhone,
                    Email                = model.Email,
                    EmailConfirmed       = true,
                    SlugUrl              = GetUniqueSlugUrl(model.FullName),
                    TwoFactorEnabled     = true,
                    PhoneNumberConfirmed = true,
                    LockoutEnabled       = bool.Parse(model.IsActive),
                    CreatedDate          = DateTime.Now
                };

                var existsPhoneNumberOrEmail = _userManager.Users.Any(i => i.PhoneNumber == model.CellPhone || i.Email == model.Email);

                if (existsPhoneNumberOrEmail)
                {
                    return(new TransactionResult()
                    {
                        Message = "Email veya Cep Telefonu başka bir kullanıcı tarafından kullanılmaktadır.", Type = TransactionType.Warning
                    });
                }
                else
                {
                    string password = Utils.GeneratePassword(3, 3, 3);

                    var result = await _userManager.CreateAsync(user, password);

                    if (result.Succeeded)
                    {
                        user = await _userManager.FindByIdAsync(user.Id);

                        await _userManager.SetLockoutEnabledAsync(user, bool.Parse(model.IsActive));

                        await _userManager.AddToRoleAsync(user, "Admin");

                        _notificationService.AddNotification(user.Id, NotificationTypes.AdminInfoMail, param: password);

                        //_notificationService.SendAdminUserInfo(user.Id, user.Email, user.Email, password);
                    }
                }

                return(new TransactionResult()
                {
                    Type = TransactionType.Success
                });
            }
            catch (Exception ex)
            {
                return(new TransactionResult(message: ex.Message, type: TransactionType.Error));
            }
        }
Esempio n. 7
0
 public static void RemoveUserFromTeam(string UserId, string TeamId)
 {
     TS.DecrementMembersNumber(TeamId);
     TMS.RemoveUser(TeamId, UserId);
     foreach (User tm in TMS.GetMembers(TeamId))
     {
         var ntf = new Notification(UserId, tm.Id, TeamId, 3);
         NS.AddNotification(ntf);
     }
 }
Esempio n. 8
0
        public async Task Delete(Guid id)
        {
            var user = await _userRepository.GetById(id);

            if (user is null)
            {
                _notificationService.AddNotification("UserDeleteError", $"O usuário com id {id} não foi encontras");
            }
            user.Deactivate();
            await _userRepository.Update(user);
        }
Esempio n. 9
0
        public void AfterRegistration(string userID, string notificationDescription = null, IEnumerable <string> SelectedUserCategories = null)
        {
            try
            {
                var freeToken = _dbContext.Campain.FirstOrDefault(i => i.SlugUrl == "ilk-uyelik");
                if (freeToken != null)
                {
                    var bought = new BoughtHistory()
                    {
                        Id          = Guid.NewGuid(),
                        UserId      = userID,
                        CampainId   = freeToken.Id,
                        CreatedDate = DateTime.Now,
                        IsPaid      = true
                    };
                    _dbContext.BoughtHistory.Add(bought);

                    if (!string.IsNullOrEmpty(notificationDescription))
                    {
                        _notificationService.AddNotification(userID, NotificationTypes.RegistrationExternalProvider, param: notificationDescription);
                    }
                    else
                    {
                        _notificationService.AddNotification(userID, NotificationTypes.Registration);
                    }
                }

                if (SelectedUserCategories != null && SelectedUserCategories.Count() > 0)
                {
                    var categories = _categoryServices.GetCategories();
                    foreach (var relation in SelectedUserCategories)
                    {
                        var category = categories.FirstOrDefault(i => i.SlugUrl == relation);

                        if (category != null)
                        {
                            _dbContext.UserCategoryRelation.Add(new UserCategoryRelation()
                            {
                                Id         = Guid.NewGuid(),
                                CategoryId = category.Id,
                                SelectDate = DateTime.Now,
                                UserId     = userID
                            });
                        }
                    }
                }

                _dbContext.SaveChanges();
            }
            catch { }
        }
Esempio n. 10
0
        public async Task <IActionResult> Post([FromBody] ChallengeModel model)
        {
            var currentUserId = _userManager.GetUserId(User);

            if (model == null ||
                string.IsNullOrEmpty(model.ReceivingPlayerId) ||
                string.IsNullOrEmpty(model.SendingPlayerId) ||
                model.SendingPlayerId != currentUserId)
            {
                return(BadRequest());
            }

            if (model.SendingPlayerId == model.ReceivingPlayerId)
            {
                return(BadRequest());
            }

            var sendingPlayer   = _applicationUserService.GetUserById(model.SendingPlayerId ?? "");
            var receivingPlayer = _applicationUserService.GetUserById(model.ReceivingPlayerId ?? "");

            var challenge = new Challenge
            {
                SendingPlayerId   = model.SendingPlayerId,
                ReceivingPlayerId = model.ReceivingPlayerId,
                SendingPlayer     = sendingPlayer,
                ReceivingPlayer   = receivingPlayer,
                Type = model.ChallengeType,
                SendingPlayerStatus   = ChallengeStatus.Accepted,
                ReceivingPlayerStatus = ChallengeStatus.Pending,
                MatchId = model.MatchId
            };

            var notification = new Notification
            {
                SendingPlayerId   = model.SendingPlayerId,
                ReceivingPlayerId = model.ReceivingPlayerId,
                Status            = NotificationStatus.Unread,
                Message           = string.Format("{0} has challenged you to a match", sendingPlayer.PlayerName),
                Subject           = "Challenge Request",
                HasOptions        = true,
                Challenge         = challenge
            };

            _challengeService.AddChallenge(challenge);
            _notifactionService.AddNotification(notification);
            await _challengeService.SaveAsync();

            await _notifactionService.SaveAsync();

            return(Ok());
        }
 public void AddCommentNotificationsAndActivity(long?parentId, long contentId, long subDirectoryId, User creator)
 {
     if (parentId.HasValue)
     {
         var parentComment = GetCommentById(parentId.Value);
         _notificationService.AddNotification(NotificationTypeMap.Reply, parentComment.ContentId, parentComment.CreatorId,
                                              subDirectoryId, creator.Fullname);
         _activityService.AddActivity(ActivityTypeMap.Replied, contentId, creator.Id, subDirectoryId);
     }
     else
     {
         _activityService.AddActivity(ActivityTypeMap.Commented, contentId, creator.Id, subDirectoryId);
     }
 }
Esempio n. 12
0
        public async Task <IActionResult> Post([FromBody] NotificationModel model)
        {
            var currentUserId = _userManager.GetUserId(User);

            if (model == null || model.SendingPlayerId != currentUserId)
            {
                return(BadRequest());
            }

            var notification = new Notification()
            {
                SendingPlayerId   = model.SendingPlayerId,
                ReceivingPlayerId = model.ReceivingPlayerId,
                SendingPlayer     = _applicationUserService.GetUserById(model.SendingPlayerId ?? ""),
                ReceivingPlayer   = _applicationUserService.GetUserById(model.ReceivingPlayerId ?? ""),
                Message           = model.Message,
                Status            = NotificationStatus.Unread,
                Subject           = model.Subject,
                HasOptions        = model.HasOptions
            };

            _notificationService.AddNotification(notification);
            await _notificationService.SaveAsync();

            return(Ok());
        }
Esempio n. 13
0
        private async Task SetNotificationAsync(CProfile profileTo, int profileFrom, string link, string userFromName, int?commentId)
        {
            var text = $"Пользователь {userFromName} ответил на ваш";
            var alt  = "комментарий";

            await notificationService.AddNotification(profileTo, profileFrom, text, link, alt, commentId);
        }
        public bool ReportComment(long userId, int commentId)
        {
            var user = _userService.GetUserById(userId);

            if (user != null && HasUserAlreadyReported(userId, commentId))
            {
                var comment = _commentRepository.GetAll().FirstOrDefault(x => x.Id == commentId);
                if (comment != null)
                {
                    var content = comment.Content1;
                    if (content != null)
                    {
                        var reported = AddReportClaim(userId, commentId);
                        if (reported)
                        {
                            if (!_investigationService.DoesInvestigationExistForComment(commentId))
                            {
                                _investigationService.AddInvestigation(userId, commentId);
                            }

                            AddReportClaim(userId, commentId);
                            _userService.CalculateAndUpdateUserReportStatistics(userId);
                            _notificationService.AddNotification(NotificationTypeMap.Report, content.Id, comment.CreatorId,
                                                                 content.SubDirectoryId, user.Fullname);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        public IActionResult AddNotification([FromBody] NotificationForCreationDto notificationFromBody)
        {
            if (!_userService.CheckIfUserExists(notificationFromBody.TargetUserId) ||
                !_offerService.CheckIfOfferExists(notificationFromBody.OfferId))
            {
                return(NotFound());
            }

            if (notificationFromBody.Type == NotificationType.RentRequest)
            {
                if (!_offerService.CheckIfOfferIsActive(notificationFromBody.OfferId))
                {
                    return(BadRequest("Oferta nieaktywna."));
                }
                else if (_notificationService.CheckIfUserAlreadySendRentRequest(
                             notificationFromBody.TargetUserId, notificationFromBody.OfferId))
                {
                    return(BadRequest("Proœba o wypo¿yczenie dla tej oferty ju¿ zosta³a przes³ana."));
                }
                else if (!_rentService.CheckIfUserHasEnoughPoints(notificationFromBody.TargetUserId))
                {
                    return(BadRequest("Niewystarczaj¹ca iloœæ punktów na zrealizowanie wypo¿yczenia."));
                }
            }

            var offerToReturn = _notificationService.AddNotification(notificationFromBody);

            return(Ok(offerToReturn));
        }
Esempio n. 16
0
        public bool SaveInquiry(InquiryResponse inquiryResp)
        {
            bool isCreated = true;

            if (inquiryResp.Inquiry.InquiryID > 0)
            {
                inquiryRepository.Update(inquiryResp.Inquiry);
                isCreated = false;
            }
            else
            {
                inquiryRepository.Add(inquiryResp.Inquiry);
            }
            inquiryRepository.SaveChanges();

            SaveInquiryDetails(inquiryResp);
            documentService.AddDocuments(inquiryResp.InquiryDocuments, inquiryResp.Inquiry.InquiryID, DocumentType.Inquiry);

            //Send Notification
            notificationService.AddNotification(new Notification
            {
                CategoryId      = (int)NotificationType.Inquiry,
                ItemId          = inquiryResp.Inquiry.InquiryID,
                ActionPerformed = isCreated?(int)ActionPerformed.Created: (int)ActionPerformed.Updated,
                CreatedBy       = inquiryResp.Inquiry.UpdatedBy,
                CreatedDate     = DateTime.UtcNow,
                Title           = "Inquiry - " + (inquiryResp.Inquiry.CompanyName.Length > 35? inquiryResp.Inquiry.CompanyName.Substring(0, 35) + "..." : inquiryResp.Inquiry.CompanyName)
            });
            return(true);
        }
Esempio n. 17
0
        private void SendNotification(SendRequest_PopUp arg1, string _message)
        {
            TMS.AddRequest((BindingContext as Team).Id, _userID);
            Notification notification = new Notification(PS.GetUser().Id, ((Team)BindingContext).CreatorID, ((Team)BindingContext).Id, 1, _message);

            NS.AddNotification(notification);
            SendRequest_button.IsVisible = false;
        }
        public async Task <IList <ProductCategoryResponseModel> > GetAll()
        {
            var productCategories = await _productCategoryRepository
                                    .GetAll();

            if (productCategories is null)
            {
                _notificationService.AddNotification("GetAllError", "Não há produtos cadastrados");
                return(null);
            }
            return(productCategories.Select(d => new ProductCategoryResponseModel
            {
                SupplierName = d.Supplier.TradingName,
                CategoryName = d.CategoryName.ToString(),
                IsActive = d.IsActive ? "Sim" : "Não"
            }).ToList());
        }
Esempio n. 19
0
        // bam nut theo doi
        public async void FollowPost_Clicked(object sender, EventArgs e)
        {
            if (!UserLogged.IsLogged)
            {
                await DisplayAlert("", Language.vui_long_dang_nhap, Language.dong);

                RedirectToLoginPage();
                return;
            }
            loadingPopup.IsVisible = true;
            if (!this.IsFollow)
            {
                var response = await ApiHelper.Post("api/post/AddToFavoritePosts/" + this.viewModel.GetPost.Id, null, true);

                if (response.IsSuccess)
                {
                    this.IsFollow = true;

                    INotificationService notificationService = DependencyService.Get <INotificationService>();
                    var notification = new NotificationModel()
                    {
                        UserId           = viewModel.GetPost.UserId,
                        Title            = UserLogged.FullName + Language.dang_theo_doi_tin_dang_cua_ban,
                        NotificationType = NotificationType.ViewPost,
                        PostId           = viewModel.GetPost.Id,
                        CreatedDate      = DateTime.Now,
                        IsRead           = false,
                        Thumbnail        = viewModel.GetPost.AvatarFullUrl
                    };

                    await notificationService.AddNotification(notification, Language.theo_doi);
                }
            }
            else
            {
                var response = await ApiHelper.Post("api/post/RemoveFromFavoritePosts/" + this.viewModel.GetPost.Id, null, true);

                if (response.IsSuccess)
                {
                    this.IsFollow = false;
                }
            }

            if (this.IsFollow) // dang theo doi.
            {
                //BtnFollowPost.TextColor = Color.Red;
                this.viewModel.ButtonCommandList[1].Text       = Language.bo_theo_doi_bai_dang;
                this.viewModel.ButtonCommandList[1].FontFamily = FontAwesomeHelper.GetFont("FontAwesomeSolid");
            }
            else
            {
                //BtnFollowPost.TextColor = Color.Red;
                this.viewModel.ButtonCommandList[1].Text       = Language.theo_doi_bai_dang;
                this.viewModel.ButtonCommandList[1].FontFamily = FontAwesomeHelper.GetFont("FontAwesomeRegular");
            }

            loadingPopup.IsVisible = false;
        }
Esempio n. 20
0
        private async Task SetNotification(CProfile profileTo, CProfile ownerProfile, string link)
        {
            var profileFrom  = ownerProfile.Id;
            var userNameFrom = ownerProfile.User.UserName;
            var text         = $"На ваши новости подписался пользователь";
            var alt          = userNameFrom;

            await notificationService.AddNotification(profileTo, profileFrom, text, link, alt);
        }
Esempio n. 21
0
        private async Task SetNotificationAsync(CProfile user, CNews news, string link)
        {
            var profileFromName = user.User.UserName;
            var profilFrom      = user.Id;
            var profileTo       = news.Owner;
            var text            = $"Пользователь {profileFromName} оценил вашу";
            var alt             = "статью";

            await notificationService.AddNotification(profileTo, profilFrom, text, link, alt);
        }
Esempio n. 22
0
 public bool VerifyEntityExistence <T>(object entity, INotificationService notificationService)
     where T : BaseEntity
 {
     if (entity is null)
     {
         notificationService.AddNotification($"{typeof(T).Name}NotFound",
                                             $"{typeof(T).Name} Não encontrado");
         return(true);
     }
     return(false);
 }
Esempio n. 23
0
        public async Task <IList <SupplierResponseModel> > GetAll()
        {
            var suppliers = await _supplierRepository.GetAll();

            if (suppliers is null)
            {
                _notificationService.AddNotification("SupplierGetAllError", "Não há fornecedores cadastrados");
                return(null);
            }
            return(suppliers.Select(supplier => new SupplierResponseModel
            {
                Id = supplier.Id,
                cpnj = supplier.cpnj,
                Email = supplier.Email.ToString(),
                Address = supplier.Address,
                TradingName = supplier.TradingName,
                CorporateName = supplier.CorporateName,
                Telephone = supplier.Telephone.ToString()
            }).ToList());
        }
Esempio n. 24
0
        public async Task <bool> EnviarEmailRedefinicaoSenha(string username)
        {
            try
            {
                var usuario = await _usuarioRepository.ObterNomeEmailUsuarioPorUsername(username);

                string token     = _tokenService.GenerateSimpleToken();
                string url       = $"{_clientSettings.Url}/atualizar-senha/{HttpUtility.UrlEncode(token)}";
                var    emailHtml = Email.TemplateEmailRedefinicaoSenha
                                   .Replace("{usuario}", usuario.NomeCompleto)
                                   .Replace("{url}", url);

                var email = _emailAddress.GetEmailAddress(usuario.NomeCompleto, usuario.Email, "ScanText - Redefinição de Senha", string.Empty, emailHtml);
                return(await _emailRepository.EnviarEmailAsync(email));
            }
            catch (Exception)
            {
                _notificationService.AddNotification("Envio do E-mail de Redefinição de Senha", "Falha ao enviar o e-mail para a redefinição de senha, tente novamente.");
                return(false);
            }
        }
Esempio n. 25
0
        public async Task <ActionResult> LinkLoginCallback()
        {
            var user = await _userManager.FindByIdAsync(_userManager.GetUserId(User));

            var info = await _signInManager.GetExternalLoginInfoAsync(_userManager.GetUserId(User));

            if (info == null)
            {
                TempData["message"]        = "Beklenmedik bir hata oluştu. Lütfen tekrar deneyiniz.";
                TempData["messagesuccess"] = false;
                return(RedirectToRoute("settings"));
            }

            var result = await _userManager.AddLoginAsync(user, info);

            var message = string.Empty;

            if (!result.Succeeded)
            {
                message             = string.Join(";", result.Errors.Select(i => i.Code));
                TempData["message"] = message
                                      .Replace("LoginAlreadyAssociated", string.Format("{0} hesabınız başka bir kullanıcıya bağlı olduğu için doğrulama işlemi yapılamadı.", info.LoginProvider));
                TempData["messagesuccess"] = false;
            }
            else
            {
                _notificationService.AddNotification(user.Id, NotificationTypes.LinkExternalProvider, param: info.LoginProvider);
            }

            return(RedirectToRoute("settings"));
        }
Esempio n. 26
0
        public async Task <IActionResult> AddNotification(
            [FromBody] AddNotificationBindingModel addNotificationBindingModel, int tvSeriesId)
        {
            string user   = User.Identity.Name;
            var    result = await _notificationService.AddNotification(addNotificationBindingModel, tvSeriesId, user);

            if (result.ErrorOccurred)
            {
                return(BadRequest(result));
            }

            return(Ok(result));
        }
Esempio n. 27
0
 public async Task <IActionResult> Contact([FromBody] ContactModel model)
 {
     if (ModelState.IsValid)
     {
         await _notes.AddNotification(
             AlertType.Contact,
             0,
             $"{model.Name}|{model.Email}",
             model.Content.StripHtml()
             );
     }
     return(Ok());
 }
Esempio n. 28
0
        public async Task <ActionResult <ExcecutorDTO> > AddExcecutor([FromBody] ExcecutorDTO user)
        {
            var task = await tasksInfoService.GetTaskDescription(user.TaskId);

            string msg = $"Now you can start execute task {task.Title}";
            await notificationService.AddNotification(msg, user.ExcecutorId);

            await _hubContext.Clients.All.SendAsync("sendMessage", user.ExcecutorId, msg);

            var dtos = await tasksInfoService.AddExcecutor(user);

            return(Ok(dtos));
        }
Esempio n. 29
0
        public TransactionResult CreateOffer(string UserId, Guid itemId, string categorySlug, string itemSlug, string comment, decimal price)
        {
            try
            {
                var tokenCount = _userEngine.CurrentUserToken(UserId, disableCache: true);
                if (tokenCount <= 0)
                {
                    return(new TransactionResult(message: "Yeterli jetonunuz bulunmamaktadır. Teklif verebilmek için jeton almanız gerekmektedir.", type: TransactionType.Error));
                }

                var myOffer = _dbContext.Offer.FirstOrDefault(i => i.ItemId == itemId && i.UserId == UserId);
                if (myOffer != null)
                {
                    return(new TransactionResult(message: "Bu hizmet için verilmiş teklifiniz var. Birden fazla teklif veremezsiniz!", type: TransactionType.Error));
                }

                var item = _dbContext.Item.FirstOrDefault(i => i.Id == itemId);
                if (item != null && (item.StatusID == (int)StatusTypes.Declined || item.StatusID == (int)StatusTypes.Closed))
                {
                    return(new TransactionResult(message: "Bu hizmet sonlandığı için teklif veremezsiniz!", type: TransactionType.Error));
                }

                var offer = new Offer();
                offer.Id         = Guid.NewGuid();
                offer.UserId     = UserId;
                offer.ItemId     = itemId;
                offer.OfferPrice = price;
                offer.OfferDate  = DateTime.Now;
                offer.Comment    = comment;

                _dbContext.Offer.Add(offer);

                var spent = new SpentHistory()
                {
                    Id          = Guid.NewGuid(),
                    TokenSpent  = 1,
                    UserId      = UserId,
                    CreatedDate = DateTime.Now,
                    Title       = "Projeye teklif verdiniz."
                };
                _dbContext.SpentHistory.Add(spent);

                _dbContext.SaveChanges();

                _notificationService.AddNotification(UserId, NotificationTypes.CreateOffer, itemId: itemId.ToString());
                _notificationService.AddNotification(item.UserId, NotificationTypes.ReceivedOffer, itemId: itemId.ToString());

                return(new TransactionResult()
                {
                    Type = TransactionType.Success
                });
            }
            catch (Exception ex)
            {
                return(new TransactionResult(message: "Beklenmedik bir hata oluştu. Lütfen tekrar deneyiniz.", type: TransactionType.Error));
            }
        }
Esempio n. 30
0
        public async Task <ResponseDto <BaseModelDto> > AddTvSeriesUserRating(string userLogged, int tvSeriesId,
                                                                              AddTvSeriesRatingBindingModel tvSeriesRatingBindingModel)
        {
            var response = new ResponseDto <BaseModelDto>();

            var tvSeriesExists = await _tvSeriesRepository.ExistAsync(x => x.Id == tvSeriesId);

            if (!tvSeriesExists)
            {
                response.AddError(Model.TvShow, Error.tvShow_NotFound);
                return(response);
            }

            var ratingExists = await _tvSeriesUserRatingRepository.ExistAsync(x => x.UserId == userLogged && x.TvShowId == tvSeriesId);

            if (ratingExists)
            {
                response.AddError(Model.Rating, Error.rating_Already_Added);
                return(response);
            }

            var userRating = _mapper.Map <TvSeriesUserRating>(tvSeriesRatingBindingModel);

            userRating.Average  = (userRating.Effects + userRating.Music + userRating.Story) / 3;
            userRating.TvShowId = tvSeriesId;
            userRating.UserId   = userLogged;

            var result = await _tvSeriesUserRatingRepository.AddAsync(userRating);

            if (!result)
            {
                response.AddError(Model.Rating, Error.rating_Adding);
                return(response);
            }
            else
            {
                if (userLogged != null)
                {
                    AddNotificationBindingModel addNotificationBindingModel = new AddNotificationBindingModel();
                    addNotificationBindingModel.Type = "ratedTvSeries";

                    await _notificationService.AddNotification(addNotificationBindingModel, tvSeriesId, userLogged);
                }
            }

            response = await AddTvSeriesRating(userRating, response);

            return(response);
        }