78 lines
2.9 KiB
C#
78 lines
2.9 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Data.SqlClient;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
|
|
namespace PlotLine.Controllers;
|
|
|
|
[Authorize]
|
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
|
public sealed class WriterGroupsController(WriterPlanningRepository planning, IChapterRepository chapters) : Controller
|
|
{
|
|
private int Actor => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
|
|
|
public sealed class GroupPage
|
|
{
|
|
public int BookID { get; set; }
|
|
public int GroupID { get; set; }
|
|
[Required, StringLength(200)] public string Name { get; set; } = "";
|
|
public bool IsCurrent { get; set; }
|
|
public int[] ChapterIDs { get; set; } = [];
|
|
public IReadOnlyList<WriterWorkingGroup> Groups { get; set; } = [];
|
|
public IReadOnlyList<Chapter> Chapters { get; set; } = [];
|
|
}
|
|
|
|
[HttpGet]
|
|
public async Task<IActionResult> Index(int bookId, int? groupId)
|
|
{
|
|
try
|
|
{
|
|
var model = new GroupPage { BookID = bookId };
|
|
await Populate(model);
|
|
if (groupId.HasValue)
|
|
{
|
|
var group = model.Groups.SingleOrDefault(row => row.GroupID == groupId);
|
|
if (group is null) return NotFound();
|
|
model.GroupID = group.GroupID;
|
|
model.Name = group.Name;
|
|
model.IsCurrent = group.IsCurrent;
|
|
model.ChapterIDs = group.ChapterIDs.ToArray();
|
|
}
|
|
return View(model);
|
|
}
|
|
catch (SqlException ex) when (ex.Number == 51000) { return NotFound(); }
|
|
}
|
|
|
|
[HttpPost, ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Index(GroupPage model)
|
|
{
|
|
try { await Populate(model); }
|
|
catch (SqlException ex) when (ex.Number == 51000) { return NotFound(); }
|
|
if (model.ChapterIDs.Length == 0)
|
|
ModelState.AddModelError(nameof(model.ChapterIDs), "Choose at least one chapter.");
|
|
|
|
if (!ModelState.IsValid) return View(model);
|
|
try
|
|
{
|
|
await planning.SaveWorkingGroup(Actor, model.BookID, model.GroupID, model.Name.Trim(),
|
|
model.IsCurrent, model.ChapterIDs);
|
|
TempData["WriterWorkspaceMessage"] = "Working group saved.";
|
|
return RedirectToAction(nameof(Index), new { bookId = model.BookID });
|
|
}
|
|
catch (SqlException ex) when (ex.Number == 51000)
|
|
{
|
|
ModelState.AddModelError(string.Empty, "The group or selected chapters are no longer available.");
|
|
return View(model);
|
|
}
|
|
}
|
|
|
|
private async Task Populate(GroupPage model)
|
|
{
|
|
model.Groups = await planning.WorkingGroups(Actor, model.BookID);
|
|
model.Chapters = (await chapters.ListByBookAsync(model.BookID)).Where(chapter => !chapter.IsArchived).ToArray();
|
|
}
|
|
}
|