PlotDirector/PlotLine/Services/ContextSavedData.cs
2026-12-06 17:57:40 +00:00

54 lines
2.8 KiB
C#

using PlotLine.Data;
namespace PlotLine.Services;
// Called only after a canonical mutation succeeds. Scope comes from saved records,
// never from a navigation return URL or an unverified project/book form field.
public sealed class ContextSavedData(ContextWorkspaceNotifications notifications, ICurrentUserService user,
ISceneRepository scenes, IChapterRepository chapters, IBookRepository books,
IFloorPlanRepository plans, ILogger<ContextSavedData> logger)
{
private readonly HashSet<(int Id,string Kind)> recordedScenes=[];
public async Task Scene(int id, string kind = "structure") => await Safely(async () =>
{
if (!recordedScenes.Add((id,kind))) return;
var scene = await scenes.GetAsync(id);
if (scene is not null) await Chapter(scene.ChapterID, kind, id);
});
public async Task Chapter(int id, string kind = "structure", int? sceneId = null) => await Safely(async () =>
{
var chapter = await chapters.GetAsync(id);
var book = chapter is null ? null : await books.GetAsync(chapter.BookID);
if (book is not null && user.UserId is int author)
await notifications.Invalidate(author, book.BookID, id, sceneId, book.ProjectID, kind,
entityId: sceneId ?? id, entityType: sceneId.HasValue ? "Scene" : "Chapter");
});
public async Task FloorPlan(int id) => await Safely(async () =>
{
var plan = await plans.GetAsync(id);
if (plan is not null) await Project(plan.ProjectID, "floorplans", id, "Floor Plan");
});
public Task Project(int projectId, string kind, int? id, string entityType) =>
user.UserId is int author ? notifications.Invalidate(author, projectId: projectId, kind: kind, entityId: id, entityType: entityType) : Task.CompletedTask;
public Task Activity(int projectId, string entityType, int? entityId)
{
// Scene editors supply the changed category explicitly after their mutation.
if (entityType == "Scene") return Task.CompletedTask;
if (entityType == "Chapter") return Task.CompletedTask;
var kind = entityType switch
{
"Character" => "characters", "Relationship" => "relationships",
"Location" or "Location Relationship" => "locations",
"Plot Line" => "plotlines", "PlotThread" or "Thread" or "Thread Event" => "threads",
"Floor Plan" or "Floor Plan Transition" or "Floor Plan Background" => "floorplans",
"Asset" or "Asset Event" => "assets", _ => null
};
return kind is null ? Task.CompletedTask : Project(projectId, kind, entityId, entityType);
}
private async Task Safely(Func<Task> action)
{
try { await action(); }
catch (Exception exception) { logger.LogWarning("Context saved-data scope unavailable: {Category}", exception.GetType().Name); }
}
}