2026-12-06 17:57:40 +00:00

104 lines
6.9 KiB
C#

using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services.Context;
public sealed record ContextThreadRow(int PlotThreadID, int PlotLineID, string Title, string PlotLineName,
bool Linked, bool CanRemove, IReadOnlyList<PlotLineWorkspaceAttributionRow> PreviousScenes, bool AssignedElsewhere, bool IncludedInChapter, bool IncludedInScene,
string? SceneBlock, string? ChapterBlock, bool Assigned, string? AssignmentLabel, bool HasManuscriptAssociation);
public sealed record ContextThreadPlacement(int PlotThreadID, int? AssignedSceneID, int? AssignedChapterID,
string? SceneBlock = null, string? ChapterBlock = null, string? AssignmentLabel = null);
public sealed record ContextThreadsPanel(SpatialScope Scope, IReadOnlyList<ContextThreadRow> Threads);
public sealed record ContextThreadSelection(int BookID, int? SceneID, int[] ThreadIDs, bool Chapter = false, int? ChapterID = null);
public sealed record ContextThreadRemoval(int BookID, int? SceneID, int ThreadID, bool Chapter = false, int? ChapterID = null);
public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRepository workspace,
ISqlConnectionFactory connections, ICurrentUserService user, ContextWorkspaceNotifications notifications)
{
public async Task<SpatialScope> Scope(int book, int? scene, int? chapter)
{
if (scene.HasValue)
{
var scope = await spatial.Scope(book, scene.Value);
if (chapter.HasValue && scope.ChapterID != chapter) throw new ArgumentException("Choose a scene in this chapter.");
return scope;
}
using var db = connections.CreateConnection();
return await db.QuerySingleOrDefaultAsync<SpatialScope>("dbo.ContextThreads_Chapter",
new { BookID = book, ChapterID = chapter, UserID = user.UserId!.Value },
commandType: CommandType.StoredProcedure) ?? throw new UnauthorizedAccessException();
}
public async Task<ContextThreadsPanel> Read(int book, int? scene, int? chapter)
{
var scope = await Scope(book, scene, chapter);
var data = await workspace.GetAsync(scope.ProjectID, book, null);
using var db = connections.CreateConnection();
var links = await db.QueryAsync<SceneThread>("dbo.SceneThread_ListByBook",
new { BookID = book, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure);
var placements = await db.QueryAsync<ContextThreadPlacement>("dbo.ContextThreads_List",
new { BookID = book, SceneID = scene, ChapterID = scope.ChapterID, UserID = user.UserId!.Value }, commandType: CommandType.StoredProcedure);
return Build(scope, data, links, placements);
}
public static ContextThreadsPanel Build(SpatialScope scope, PlotLineWorkspaceData data, IEnumerable<SceneThread> links,
IEnumerable<ContextThreadPlacement> planning)
{
var scenes = data.AttributionScenes.Where(s => s.BookID == scope.BookID).ToDictionary(s => s.SceneID);
if (!scenes.TryGetValue(scope.SceneID, out var current) && scope.SceneID > 0) throw new ArgumentException("Scene order is unavailable.");
var lines = data.PlotLines.Where(l => l.ProjectID == scope.ProjectID && (l.BookID == null || l.BookID == scope.BookID)).ToDictionary(l => l.PlotLineID);
var plans = planning.ToDictionary(p => p.PlotThreadID);
var associations = links.Select(l => (l.PlotThreadID, l.SceneID)).ToHashSet();
associations.UnionWith(data.Contributions.Where(c => c.BookID == scope.BookID).Select(c => (c.PlotThreadID, c.SceneID)));
// Established milestones are authoritative associations too. A planned resolution
// alone is a future intention, not a scene where the thread has been picked up.
foreach (var thread in data.Threads)
{
if (thread.IntroducedSceneID is int introduced) associations.Add((thread.PlotThreadID, introduced));
if (thread.ActualResolutionSceneID is int resolved) associations.Add((thread.PlotThreadID, resolved));
}
var rows = data.Threads.Where(t => lines.ContainsKey(t.PlotLineID)).Select(t =>
{
var placement = plans.GetValueOrDefault(t.PlotThreadID);
var includedInScene = placement?.AssignedSceneID == scope.SceneID;
var includedInChapter = scope.ChapterID > 0 && placement?.AssignedChapterID == scope.ChapterID;
var assigned = placement?.AssignedChapterID is not null || placement?.AssignedSceneID is not null;
var recordedHere = associations.Contains((t.PlotThreadID, scope.SceneID));
var history = scenes.Values.Where(s => current is not null && s.NarrativeOrder < current.NarrativeOrder
&& associations.Contains((t.PlotThreadID, s.SceneID)))
.OrderBy(s => s.NarrativeOrder).ToArray();
return new ContextThreadRow(t.PlotThreadID, t.PlotLineID, t.ThreadTitle, lines[t.PlotLineID].PlotLineName,
recordedHere || includedInScene, scope.CanEdit && (includedInScene || includedInChapter), history,
assigned && !includedInScene && !includedInChapter, includedInChapter, includedInScene,
placement?.SceneBlock, placement?.ChapterBlock, assigned, placement?.AssignmentLabel, recordedHere);
}).OrderBy(t => t.PlotLineName, StringComparer.CurrentCultureIgnoreCase)
.ThenBy(t => t.Title, StringComparer.CurrentCultureIgnoreCase).ToArray();
return new(scope, rows);
}
public async Task Add(ContextThreadSelection input)
{
if (input.ThreadIDs is not { Length: > 0 and <= 200 } || input.ThreadIDs.Any(id => id <= 0))
throw new ArgumentException("Choose between 1 and 200 threads.");
using var db = connections.CreateConnection();
var project = await db.QuerySingleAsync<int>("dbo.ContextThreads_Change",
new { input.BookID, input.SceneID, input.ChapterID, input.Chapter, UserID = user.UserId ?? throw new UnauthorizedAccessException(), ThreadIDs = JsonSerializer.Serialize(input.ThreadIDs.Distinct()), Remove = false },
commandType: CommandType.StoredProcedure);
// Any earlier scene can affect history in all later scenes of the same book.
await notifications.Invalidate(user.UserId!.Value, projectId: project, bookId: input.BookID, kind: "threads");
}
public async Task Remove(ContextThreadRemoval input)
{
var userId = user.UserId ?? throw new UnauthorizedAccessException();
using var db = connections.CreateConnection();
var project = await db.QuerySingleAsync<int>("dbo.ContextThreads_Change",
new { input.BookID, input.SceneID, input.ChapterID, input.Chapter, UserID = userId, ThreadIDs = JsonSerializer.Serialize(new[] { input.ThreadID }), Remove = true },
commandType: CommandType.StoredProcedure);
await notifications.Invalidate(userId, projectId: project, bookId: input.BookID, kind: "threads");
}
}