using AutoMapper; using gehGassi.Core.Interfaces; using gehGassi.Permissions; using gehGassi.Web.Auth.Attributes; using gehGassi.Web.Auth; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization; using gehGassi.Common.Data; using System.Collections.Generic; using System.Linq; using gehGassi.Domain.Common; using gehGassi.Web.Models; using System; using gehGassi.Core.Services; using gehGassi.External.Services; using gehGassi.Web.Helper; using System.IO; using System.Threading.Tasks; using gehGassi.Web.Services; namespace gehGassi.Web.Controllers { /// /// Controller für Abonnements /// [Authorize] public class SubscriptionController : BaseController { private readonly IMapper _mapper; private readonly IStringLocalizer _localizer; private readonly ILanguageService _languageService; private readonly ISubscriptionService _subscriptionService; private readonly IAppUserService _appUserService; /// /// Erstellt eine Instanz /// /// Instanz eines IMapper /// Instanz eines IStringLocalizer /// Instanz eines ILanguageService /// Instanz eines ISubscriptionService /// Instanz eines IAppUserService public SubscriptionController(IMapper mapper, IStringLocalizer localizer, ILanguageService languageService, ISubscriptionService subscriptionService, IAppUserService appUserService) { _mapper = mapper; _localizer = localizer; _languageService = languageService; _subscriptionService = subscriptionService; _appUserService = appUserService; } /// /// Gibt einen View für die Verwaltung von Abonnements zurück /// /// View [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsRead)] public IActionResult IndexSubscriptions() { 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.SubscriptionsManage, Permission.SubscriptionsRead)] [HttpPost] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult GetSubscriptions([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 == "length") whereFilterPredicate.value = (SubscriptionLength)((int)(whereFilterPredicate.value)); if (whereFilterPredicate.Field == "appMode") whereFilterPredicate.value = (AppMode)((int)(whereFilterPredicate.value)); } } } } var resultList = _subscriptionService.FilterWithNames(dm?.SearchValue ?? "", SelectedLanguage, FallbackLanguage, includeDeleted: false); //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.LengthText = itemVm.Length.GetDisplayName(AnnotationsLocalizer); itemVm.AppModeText = itemVm.AppMode.GetDisplayName(AnnotationsLocalizer); } //FilterPreview? if (!dm.RequiresCounts) return Json(resultListVm); return Json(new { result = resultListVm, count = countFiltered }); } /// /// Anlegen eines Abonnements /// /// PartialView [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsCreate)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult CreateSubscription() { var model = new SubscriptionVm() { Id = Guid.NewGuid().ToString("N"), TextVms = new List(), Code = string.Empty, Length = SubscriptionLength.OneMonth, Price = 0, AppMode = AppMode.DogOwner, Enabled = true, GracePeriodInDays = 7 }; foreach (var language in _languageService.GetAllIso2()) { model.TextVms.Add(new SubscriptionTextVm() { Id = model.Id, Language = language, Name = string.Empty, Description = string.Empty }); } return PartialView("_CreateSubscription", model); } /// /// Anlegen eines Abonnements /// /// Model /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsCreate)] [ValidateAntiForgeryToken] [HttpPost] public async Task CreateSubscription(SubscriptionVm model) { var result = new ResponseVm { Success = false }; if (ModelState.IsValid) { var item = _subscriptionService.Create(); _mapper.Map(model, item); item.UpdatedAt = DateTimeOffset.UtcNow; // Texte setzen foreach (var textVm in model.TextVms) { item.Set("Name", textVm.Language, textVm.Name); item.Set("Description", textVm.Language, textVm.Description); } _subscriptionService.Add(item); await _subscriptionService.CommitAsync(User.Identity.Name); result.Data = item.ToCamelCaseJson(); result.Success = true; result.Html = string.Empty; return Json(result); } result.Html = await PartialView("_CreateSubscription", model).ToStringAsync(ControllerContext); return Json(result); } /// /// Bearbeiten eines Abonnements /// /// Id des Abonnements /// PartialView [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsEdit)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public async Task EditSubscription(string id) { var item = await _subscriptionService.GetAsync(id); if (item != null) { var model = _mapper.Map(item); model.TextVms = new List(); foreach (var language in _languageService.GetAllIso2()) { model.TextVms.Add(new SubscriptionTextVm() { Id = item.Id, Language = language, Name = item.Get("Name", language, true), Description = item.Get("Description", language, true) }); } return PartialView("_EditSubscription", model); } return PartialView("_Error"); } /// /// Bearbeiten eines Abonnements /// /// Model /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsEdit)] [ValidateAntiForgeryToken] [HttpPost] public async Task EditSubscription(SubscriptionVm model) { var result = new ResponseVm { Success = false }; if (ModelState.IsValid) { var item = await _subscriptionService.GetAsync(model.Id); if (item is { Deleted: false }) { if (item.Version.SequenceEqual(model.Version)) { _mapper.Map(model, item); //Texte setzen foreach (var textVm in model.TextVms) { item.Set("Name", textVm.Language, textVm.Name); item.Set("Description", textVm.Language, textVm.Description); } item.UpdatedAt = DateTimeOffset.UtcNow; await _subscriptionService.CommitAsync(User.Identity.Name); result.Data = item.ToCamelCaseJson(); result.Success = true; result.Html = string.Empty; return Json(new { result.Success, result.Html, result.Data }); } else { ModelState.AddModelError("", _localizer["Err_Entity_Changed"].Value); } } else { ModelState.AddModelError("", _localizer["Err_Entity_Deleted"].Value); } } result.Html = await PartialView("_EditSubscription", model).ToStringAsync(ControllerContext); return Json(result); } /// /// Löschen eines Abonnements /// /// Liste Id der Entität /// Sollen die Daten physisch gelöscht werden? /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsDelete)] [HttpPost] public async Task DeleteSubscription(List ids, bool forceDelete = false) { var batchErrorHeader = $"

{_localizer["Common_BatchDelete_Failed"].Value}

"; var batchResult = new BatchResponseVm(batchErrorHeader) { Success = true }; foreach (var id in ids) { var item = await _subscriptionService.GetAsync(id); if (item != null) { //await _customerService.ResetTypeAsync(item.Id); //Spezial zurücksetzen wenn nötig var usedCount = 0; //var productsCount = await _productService.CountByAdvertisementCategoryAsync(item.Id); //usedCount += productsCount; if (usedCount == 0) { //TODO: Gibt es Resets die notwendig sind? //await _productService.ResetAdvertisementCategoryAsync(item.Id, true); batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = item.Id.ToString(), Name = item.Name, Success = true, NotFound = false, ErrorMessage = "" }); if (forceDelete) { _subscriptionService.Remove(item); } else { item.Deleted = true; item.UpdatedAt = DateTimeOffset.UtcNow; } } else { if (usedCount != 0) { batchResult.Success = false; batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = id.ToString(), Name = item.Name, Success = false, NotFound = false, ErrorMessage = string.Format(_localizer["Common_BatchDelete_InUse"], $"{item.Name}", $"{usedCount}") + "
" }); } } } 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 _subscriptionService.CommitAsync(User.Identity.Name); return Json(batchResult); } #region Bookings /// /// Gibt einen View für die Verwaltung von Abonnement-Buchungen zurück /// /// View [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsRead)] public IActionResult IndexBookings() { 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.SubscriptionsManage, Permission.SubscriptionsRead)] [HttpPost] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult GetBookings([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 == "appUserType") whereFilterPredicate.value = (AppUserType)((int)(whereFilterPredicate.value)); if (whereFilterPredicate.Field == "length") whereFilterPredicate.value = (SubscriptionLength)((int)(whereFilterPredicate.value)); if (whereFilterPredicate.Field == "appMode") whereFilterPredicate.value = (AppMode)((int)(whereFilterPredicate.value)); if (whereFilterPredicate.Field == "platform") whereFilterPredicate.value = (Platform)((int)(whereFilterPredicate.value)); } } } } var resultList = _subscriptionService.FilterAppUserSubscritionsWithNames(dm?.SearchValue ?? "", SelectedLanguage, FallbackLanguage); //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.AppUserTypeText = itemVm.AppUserType.GetDisplayName(AnnotationsLocalizer); itemVm.SubscriptionLengthText = itemVm.SubscriptionLength.GetDisplayName(AnnotationsLocalizer); itemVm.SubscriptionAppModeText = itemVm.SubscriptionAppMode.GetDisplayName(AnnotationsLocalizer); itemVm.PlatformText = itemVm.Platform.GetDisplayName(AnnotationsLocalizer); } //FilterPreview? if (!dm.RequiresCounts) return Json(resultListVm); return Json(new { result = resultListVm, count = countFiltered }); } /// /// Anlegen einer Abo Buchung /// /// PartialView [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsCreate)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult CreateBooking() { var model = new SubscriptionBookingCreateVm() { }; return PartialView("_CreateBooking", model); } /// /// Anlegen einer Abo Buchung /// /// Model /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsCreate)] [ValidateAntiForgeryToken] [HttpPost] public async Task CreateBooking(SubscriptionBookingCreateVm model) { var result = new ResponseVm { Success = false }; if (ModelState.IsValid) { //Der AppUser kann nur ein aktives Abo je AppMode haben!! var subscription = await _subscriptionService.GetAsync(model.SubscriptionId); //Prüfen ob ein Abo in dieer Kombination bereits existiert var existingItem = await _subscriptionService.AppUserHasActiveBookingAsync(model.AppUserId, subscription.AppMode); if (existingItem == false) { var item = _subscriptionService.CreateAppUserSubscription(); _mapper.Map(model, item); if (item.ExpirationDate == null) item.IsValid = true; else item.IsValid = item.ExpirationDate >= DateTimeOffset.UtcNow; if(item.ExpirationDate != null) item.ExpirationDateWithGrace = item.ExpirationDate.Value.AddDays(subscription.GracePeriodInDays); item.Manual = true; item.CreatedBy = User.Identity.Name; item.Created = DateTimeOffset.UtcNow; _subscriptionService.AddAppUserSubscription(item); await _subscriptionService.CommitAsync(User.Identity.Name); result.Data = item.ToCamelCaseJson(); result.Success = true; result.Html = string.Empty; return Json(result); } else { ModelState.AddModelError(string.Empty, _localizer["Err_SubscriptionBooking_Exists"]); } } result.Html = await PartialView("_CreateBooking", model).ToStringAsync(ControllerContext); return Json(result); } /// /// Bearbeiten einer Abo-Buchung /// /// Id des Abonnements /// PartialView [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsEdit)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public async Task EditBooking(long id) { var item = await _subscriptionService.GetAppUserSubscriptionAsync(id); if (item != null) { var model = _mapper.Map(item); var appUser = await _appUserService.GetAsync(item.AppUserId); model.AppUserName = $"{appUser.FirstName} {appUser.LastName} ({AnnotationsLocalizer["AppUserType_" + appUser.Type.ToString()]})"; var subscription = await _subscriptionService.GetAsync(item.SubscriptionId); model.SubscriptionName = subscription.Get("Name", SelectedLanguage, true); ViewBag.AppMode = subscription.AppMode; return PartialView("_EditBooking", model); } return PartialView("_Error"); } /// /// Bearbeiten einer Abo-Buchung /// /// Model /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsEdit)] [ValidateAntiForgeryToken] [HttpPost] public async Task EditBooking(SubscriptionBookingEditVm model) { var result = new ResponseVm { Success = false }; if (ModelState.IsValid) { var subscription = await _subscriptionService.GetAsync(model.SubscriptionId); var item = await _subscriptionService.GetAppUserSubscriptionAsync(model.Id); if (item != null) { _mapper.Map(model, item); if (item.ExpirationDate == null) item.IsValid = true; else item.IsValid = item.ExpirationDate >= DateTimeOffset.UtcNow; if (item.ExpirationDate != null) item.ExpirationDateWithGrace = item.ExpirationDate.Value.AddDays(subscription.GracePeriodInDays); item.LastUpdate = DateTimeOffset.UtcNow; await _subscriptionService.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("AppUserName"); var appUser = await _appUserService.GetAsync(model.AppUserId); model.AppUserName = $"{appUser.FirstName} {appUser.LastName} ({AnnotationsLocalizer["AppUserType_" + appUser.Type.ToString()]})"; ModelState.Remove("SubscriptionName"); var subscriptionLookup = await _subscriptionService.GetAsync(model.SubscriptionId); model.SubscriptionName = subscriptionLookup.Get("Name", SelectedLanguage, true); ViewBag.AppMode = subscriptionLookup.AppMode; result.Html = await PartialView("_EditBooking", model).ToStringAsync(ControllerContext); return Json(result); } /// /// Löschen einer Abonnement-Buchung /// /// Liste Id der Entität /// Json [Authorize(Policy = Policies.PowerUserOnly)] [HasPermission(Permission.SubscriptionsManage, Permission.SubscriptionsDelete)] [HttpPost] public async Task DeleteBooking(List ids) { var batchErrorHeader = $"

{_localizer["Common_BatchDelete_Failed"].Value}

"; var batchResult = new BatchResponseVm(batchErrorHeader) { Success = true }; foreach (var id in ids) { var item = await _subscriptionService.GetAppUserSubscriptionAsync(id); if (item != null) { //await _customerService.ResetTypeAsync(item.Id); //Spezial zurücksetzen wenn nötig var usedCount = 0; //var productsCount = await _productService.CountByAdvertisementCategoryAsync(item.Id); //usedCount += productsCount; if (usedCount == 0) { //TODO: Gibt es Resets die notwendig sind? //await _productService.ResetAdvertisementCategoryAsync(item.Id, true); batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = item.Id.ToString(), Name = item.AppUserId, Success = true, NotFound = false, ErrorMessage = "" }); _subscriptionService.RemoveAppUserSubscription(item); } else { if (usedCount != 0) { batchResult.Success = false; batchResult.BatchResponseList.Add(new BatchResponseItemVm() { Id = id.ToString(), Name = item.AppUserId, Success = false, NotFound = false, ErrorMessage = string.Format(_localizer["Common_BatchDelete_InUse"], $"{item.AppUserId}", $"{usedCount}") + "
" }); } } } 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 _subscriptionService.CommitAsync(User.Identity.Name); return Json(batchResult); } #endregion #region Helper /// /// Gibt eine Liste von App-Usern für LookUp zurück /// /// DataManager /// Soll "Keine(r)" integriert werden /// Liste [Authorize(Policy = Policies.PowerUserOnly)] public async Task Lookup([FromBody] DataManager dm, bool includeNone = false) { var filter = string.Empty; if (dm.Where?.FirstOrDefault() != null) { filter = dm.Where.First().value.ToString(); if (filter.IndexOf('(') > 0) { filter = filter.Substring(0, (filter.IndexOf('(') - 1)); filter = filter.TrimEnd(); } } var items = await _subscriptionService.SearchAsync(filter); var result = items.Select(item => new LookupItemVm() { Id = item.Id.ToString(), Name = $"{item.Name}" }).OrderBy(c => c.Name).ToList(); if (includeNone) result.Insert(0, new LookupItemVm() { Id = "", Name = _localizer["Common_None"].ToString() }); return Json(result); } /// /// Gibt eine Liste von App-Usern für LookUp zurück /// /// DataManager /// Soll "Keine(r)" integriert werden /// Liste [Authorize(Policy = Policies.PowerUserOnly)] public async Task LookupAppMode([FromBody] DataManager dm, AppMode appMode, bool includeNone = false) { var filter = string.Empty; if (dm.Where?.FirstOrDefault() != null) { filter = dm.Where.First().value.ToString(); if (filter.IndexOf('(') > 0) { filter = filter.Substring(0, (filter.IndexOf('(') - 1)); filter = filter.TrimEnd(); } } var items = await _subscriptionService.SearchAsync(filter); var result = items.Where(c => c.AppMode == appMode).Select(item => new LookupItemVm() { Id = item.Id.ToString(), Name = $"{item.Name}" }).OrderBy(c => c.Name).ToList(); if (includeNone) result.Insert(0, new LookupItemVm() { Id = "", Name = _localizer["Common_None"].ToString() }); return Json(result); } #endregion } }