using AutoMapper; using gehGassi.Common.Data; using gehGassi.Core.Interfaces; using gehGassi.Core.Services; using gehGassi.Domain.Common; using gehGassi.Permissions; using gehGassi.Web.Auth; using gehGassi.Web.Auth.Attributes; using gehGassi.Web.Helper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization; using System.Collections.Generic; using System.Linq; using gehGassi.Web.Models; using System.Threading.Tasks; using System; using gehGassi.Domain.Messages; using gehGassi.External.Services; using NetTopologySuite.Geometries; using NetTopologySuite; using System.IO; namespace gehGassi.Web.Controllers { /// /// Controller für die Verwaltung von Systemnachrichten /// public class SystemMessageController : BaseController { private readonly IMapper _mapper; private readonly IStringLocalizer _localizer; private readonly ISystemMessageService _systemMessageService; private readonly ICountryService _countryService; private readonly IAppUserService _appUserService; private readonly IPushNotificationService _pushNotificationService; /// /// Erstellt eine Instanz /// /// Instanz eines IMapper /// Instanz eines IStringLocalizer /// Instanz eines ISystemMessageService /// Instanz eines ICountryService /// Instanz eines IAppUserService /// Instanz eines IPushNotificationService public SystemMessageController(IMapper mapper, IStringLocalizer localizer, ISystemMessageService systemMessageService, ICountryService countryService, IAppUserService appUserService, IPushNotificationService pushNotificationService) { _mapper = mapper; _localizer = localizer; _systemMessageService = systemMessageService; _countryService = countryService; _appUserService = appUserService; _pushNotificationService = pushNotificationService; } /// /// Gibt einen View für die Systemnachrichten-Verwaltung zurück /// /// View [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] public IActionResult Index() { return View(); } /// /// Gibt eine Liste von Entitäten basierend auf Abfragekriterien zurück /// /// Abfragekriterien /// Liste von gefundenen Entitäten [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [HttpPost] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult GetSystemMessages([FromBody] DataManager dm) { if (dm != null) { var propList = new List(); dm.SetComplexProperties(propList); if (dm.Where != null) { foreach (var whereFilter in dm.Where) { if (whereFilter.predicates == null) continue; foreach (var whereFilterPredicate in whereFilter.predicates) { if (whereFilterPredicate.Field == "sex") whereFilterPredicate.value = (Sex)((int)((long)whereFilterPredicate.value)); } } } } var resultList = _systemMessageService.FilterSystemMessagesToSend(dm?.SearchValue ?? ""); //Sortierung resultList = dm.ApplySorting(resultList); //Filter resultList = dm.ApplyFiltering(resultList, out var countFiltered); //Paging resultList = dm.ApplyPaging(resultList); var resultListVm = resultList.ToList().Select(item => _mapper.Map(item)).ToList(); foreach (var itemVm in resultListVm) { itemVm.SexText = itemVm.Sex.GetDisplayName(AnnotationsLocalizer); itemVm.AppUserTypeText = itemVm.AppUserType.GetDisplayName(AnnotationsLocalizer); } //FilterPreview? if (!dm.RequiresCounts) return Json(resultListVm); return Json(new { result = resultListVm, count = countFiltered }); } /// /// Anlegen einer Systemnachricht /// /// PartialView [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public async Task Create() { var model = new SystemMessageToSendCrudVm() { AppUserType = AppUserTypeVm.Both, Sex = SexVm.Undefined, VerifiedOnly = false, CountryName = _localizer["Common_All"], StateName = _localizer["Common_All"], }; return PartialView("_Create", model); } /// /// Anlegen einer Systemnachricht /// /// Model /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [ValidateAntiForgeryToken] [HttpPost] public async Task Create(SystemMessageToSendCrudVm model) { var result = new ResponseVm { Success = false }; if (ModelState.IsValid) { var item = _systemMessageService.CreateToSend(); _mapper.Map(model, item); item.CreatedBy = User.Identity.Name; //Zählen wie viele Nachrichten verschickt werden sollen item.AppUserCount = await _appUserService.CountForSystemMessageAsync(new SystemMessageAppUserQuery(){AppUserType = item.AppUserType, City = item.City, Country = item.Country, Sex = item.Sex, State = item.State, VerifiedOnly = item.VerifiedOnly, Zip = item.Zip}); _systemMessageService.AddToSend(item); await _systemMessageService.CommitAsync(User.Identity.Name); result.Data = item.ToCamelCaseJson(); result.Success = true; result.Html = string.Empty; return Json(result); } ModelState.Remove("CountryName"); var country = _countryService.GetCountry(model.Country); model.CountryName = country != null ? country.Name : _localizer["Common_All"].Value; ModelState.Remove("StateName"); var state = _countryService.GetState(model.Country, model.State); model.StateName = state != null ? state.Name : _localizer["Common_All"].Value; result.Html = await PartialView("_Create", model).ToStringAsync(ControllerContext); return Json(result); } /// /// Bearbeiten einer Systemnachricht /// /// Id der Systemnachricht /// PartialView [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public async Task Edit(long id) { var item = await _systemMessageService.GetToSendAsync(id); if (item != null) { var model = _mapper.Map(item); var country = _countryService.GetCountry(item.Country); model.CountryName = country != null ? country.Name : _localizer["Common_All"].Value; var state = _countryService.GetState(item.Country, item.State); model.StateName = state != null ? state.Name : _localizer["Common_All"].Value; return PartialView("_Edit", model); } return PartialView("_Error"); } /// /// Bearbeiten einer Systemnachricht /// /// Model /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [ValidateAntiForgeryToken] [HttpPost] public async Task Edit(SystemMessageToSendCrudVm model) { var result = new ResponseVm { Success = false }; if (ModelState.IsValid) { var item = await _systemMessageService.GetToSendAsync(model.Id); _mapper.Map(model, item); //Zählen wie viele Nachrichten verschickt werden sollen item.AppUserCount = await _appUserService.CountForSystemMessageAsync(new SystemMessageAppUserQuery() { AppUserType = item.AppUserType, City = item.City, Country = item.Country, Sex = item.Sex, State = item.State, VerifiedOnly = item.VerifiedOnly, Zip = item.Zip }); await _systemMessageService.CommitAsync(User.Identity.Name); result.Data = item.ToCamelCaseJson(); result.Success = true; result.Html = string.Empty; return Json(new { result.Success, result.Html, result.Data }); } ModelState.Remove("CountryName"); var country = _countryService.GetCountry(model.Country); model.CountryName = country != null ? country.Name : _localizer["Common_All"].Value; ModelState.Remove("StateName"); var state = _countryService.GetState(model.Country, model.State); model.StateName = state != null ? state.Name : _localizer["Common_All"].Value; result.Html = await PartialView("_Edit", model).ToStringAsync(ControllerContext); return Json(result); } /// /// Löschen von Systemnachrichten die zu senden sind /// /// Liste Id der Entität /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [HttpPost] public async Task Delete(List ids) { var batchErrorHeader = $"

{_localizer["Common_BatchDelete_Failed"].Value}

"; var batchResult = new BatchResponseVm(batchErrorHeader) { Success = true }; foreach (var id in ids) { var item = await _systemMessageService.GetToSendAsync(id); if (item != null) { //await _customerService.ResetTypeAsync(item.Id); //Spezial zurücksetzen wenn nötig var specialCount = 0; if (specialCount == 0) { batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = item.Id.ToString(), Name = item.Title, Success = true, NotFound = false, ErrorMessage = "" }); _systemMessageService.RemoveToSend(item); } else { if (specialCount != 0) { batchResult.Success = false; batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = id.ToString(), Name = item.Title, Success = false, NotFound = false, ErrorMessage = string.Format(_localizer["Common_BatchDelete_InUse"], $"{item.Title}", $"{specialCount}") + "
" }); } } } else { batchResult.Success = false; batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = id.ToString(), Name = "", Success = false, NotFound = true, ErrorMessage = string.Format(_localizer["Common_BatchDelete_NotFound"], $"{id}") + "
" }); } } if (batchResult.BatchResponseList.Any(c => c.Success)) await _systemMessageService.CommitAsync(User.Identity.Name); return Json(batchResult); } /// /// Senden von Systemnachrichten /// /// Id der Systemnachricht die gesendet werden soll /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.AppUsersManage, Permission.AppUsersSystemMessages)] [HttpPost] public async Task Send(long id) { var result = new ResponseVm { Success = false }; var item = await _systemMessageService.GetToSendAsync(id); if (item != null && item.HasBeenSent == false) { item.AppUserCount = await _appUserService.CountForSystemMessageAsync(new SystemMessageAppUserQuery() { AppUserType = item.AppUserType, City = item.City, Country = item.Country, Sex = item.Sex, State = item.State, VerifiedOnly = item.VerifiedOnly, Zip = item.Zip }); item.SentCount = item.AppUserCount; item.HasBeenSent = true; item.SentDate = DateTimeOffset.UtcNow; item.SentBy = User.Identity.Name; await _systemMessageService.CommitAsync(User.Identity.Name); var appUsers = await _appUserService.GetForSystemMessageAsync(new SystemMessageAppUserQuery() { AppUserType = item.AppUserType, City = item.City, Country = item.Country, Sex = item.Sex, State = item.State, VerifiedOnly = item.VerifiedOnly, Zip = item.Zip }); var sentCount = 0; foreach (var appUser in appUsers) { sentCount += 1; _systemMessageService.Add(appUser.Id, appUser.Type, item.Id.ToString(), DateTimeOffset.UtcNow.AddDays(14), item.Message); if (item.SendPushNotification) { await _pushNotificationService.SendNewTextMessageAsync(appUser.Id, item.Id.ToString()); } } if (sentCount > 0) { await _systemMessageService.CommitAsync(User.Identity.Name); } result.Success = true; return Json(result); } return Json(result); } } }