PlotDirector/PlotLine/Controllers/WriterIntentImportController.cs

74 lines
3.3 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize]
[Route("Writer/ImportIntent")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class WriterIntentImportController(
IProjectAccessService access, IChapterRepository chapters, ContextIntentChecklist intent) : Controller
{
public sealed class ImportPage
{
public int BookID { get; set; }
public string? Text { get; set; }
public List<Mapping> Mappings { get; set; } = [];
public IReadOnlyList<Chapter> Chapters { get; set; } = [];
public IReadOnlyList<ContextIntentText.ChapterPasteSection> Sections { get; set; } = [];
}
public sealed record Mapping(int ChapterID, string? Mode);
[HttpGet]
public async Task<IActionResult> Index(int bookId)
{
if (!await access.CanAccessEntityAsync("Book", bookId)) return NotFound();
return View(new ImportPage { BookID = bookId });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ImportPage model, string? step)
{
if (!await access.CanAccessEntityAsync("Book", model.BookID)) return NotFound();
model.Chapters = (await chapters.ListByBookAsync(model.BookID)).Where(chapter => !chapter.IsArchived).ToArray();
try
{
model.Sections = ContextIntentText.ParseChapters(model.Text ?? "");
if (step != "save")
{
model.Mappings = model.Sections.Select(_ => new Mapping(0, "notes")).ToList();
ModelState.Clear();
return View(model);
}
if (!ModelState.IsValid || model.Mappings.Count != model.Sections.Count ||
model.Mappings.Any(row => row.Mode is not ("notes" or "checklist")
|| !model.Chapters.Any(chapter => chapter.ChapterID == row.ChapterID)))
throw new ArgumentException("Map every pasted section to an existing chapter and choose how to save it.");
var imports = model.Sections.Zip(model.Mappings, (section, mapping) =>
new ContextIntentChecklist.ChapterImport(mapping.ChapterID, section, mapping.Mode == "checklist")).ToArray();
await intent.AppendChapters(model.BookID, imports);
TempData["WriterWorkspaceMessage"] = "Pasted intentions added to the selected chapters.";
return RedirectToAction("Write", "Writer", new { bookId = model.BookID });
}
catch (ArgumentException ex) { ModelState.AddModelError(string.Empty, ex.Message); }
catch (InvalidOperationException ex) { ModelState.AddModelError(string.Empty, ex.Message); }
catch (UnauthorizedAccessException) { return Forbid(); }
catch (SqlException ex) when (ex.Number is 51010 or 51011 or 51012)
{
ModelState.AddModelError(string.Empty, "Intent changed or is unavailable. Review the mappings and try again.");
}
if (model.Mappings.Count != model.Sections.Count)
model.Mappings = model.Sections.Select(_ => new Mapping(0, "notes")).ToList();
return View(model);
}
}