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

47 lines
2.4 KiB
C#

using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.ViewModels;
namespace PlotLine.Services.Context;
public sealed record IntentNotesSave(int BookID, int ChapterID, int? SceneID, string? Original, string? Notes);
public sealed record IntentSourceNote(string ThreadTitle, string? WritingNotes, string? PlanningChecklist, int? SceneID)
{
public IReadOnlyList<ThreadChecklistItem> Items => PlanningChecklist is null ? []
: JsonSerializer.Deserialize<List<ThreadChecklistItem>>(PlanningChecklist) ?? [];
}
public sealed record IntentSourceReference(int ReferenceID, string EntityType, int EntityID,
string Kind, string Note, string? Title, string? OriginalFileName, string Source, int? SceneID);
public sealed record IntentMaterial(IReadOnlyList<IntentSourceNote> Notes, IReadOnlyList<IntentSourceReference> References);
public sealed class ContextIntentMaterial(ISqlConnectionFactory connections, ICurrentUserService user,
ContextWorkspaceNotifications notifications)
{
public async Task<IntentMaterial> Read(int bookId, int chapterId, int? sceneId)
{
using var db = connections.CreateConnection();
using var result = await db.QueryMultipleAsync("dbo.ContextIntent_Material",
new { UserID = user.UserId!.Value, BookID = bookId, ChapterID = chapterId, SceneID = sceneId },
commandType: CommandType.StoredProcedure);
var notes = (await result.ReadAsync<IntentSourceNote>()).AsList();
var references = (await result.ReadAsync<IntentSourceReference>()).DistinctBy(row => row.ReferenceID).ToArray();
return new(notes, references);
}
public async Task SaveNotes(IntentNotesSave request)
{
ContextIntentPalette.Validate(new(request.BookID, request.ChapterID, request.SceneID));
if (request.Notes?.Length > 100_000)
throw new ArgumentException("Use 100,000 characters or fewer.");
var author = user.UserId ?? throw new UnauthorizedAccessException();
using var db = connections.CreateConnection();
var project = await db.QuerySingleAsync<int>("dbo.ContextIntent_SaveNotes",
new { UserID = author, request.BookID, request.ChapterID, request.SceneID, request.Original, request.Notes },
commandType: CommandType.StoredProcedure);
await notifications.Invalidate(author, request.BookID, request.ChapterID, request.SceneID, project, kind: "intent");
}
}