using System.Data; using System.Text.Json; using Dapper; using PlotLine.Models; using PlotLine.ViewModels; namespace PlotLine.Data; public sealed class WriterPlanningRepository(ISqlConnectionFactory factory) { private sealed record GroupRow(int GroupID, string Name, bool IsCurrent, int? ChapterID); public async Task> WorkingGroups(int userId, int bookId) { using var connection = factory.CreateConnection(); var rows = await connection.QueryAsync("dbo.WriterWorkingGroups_Manage", new { UserID = userId, BookID = bookId }, commandType: CommandType.StoredProcedure); return rows.GroupBy(row => (row.GroupID, row.Name, row.IsCurrent)) .Select(group => new WriterWorkingGroup(group.Key.GroupID, group.Key.Name, group.Key.IsCurrent, group.Where(row => row.ChapterID.HasValue).Select(row => row.ChapterID!.Value).ToArray())) .ToArray(); } public async Task SaveWorkingGroup(int userId, int bookId, int groupId, string name, bool isCurrent, int[] chapters) { using var connection = factory.CreateConnection(); await connection.ExecuteAsync("dbo.WriterWorkingGroups_Manage", new { UserID = userId, BookID = bookId, GroupID = groupId, Name = name, IsCurrent = isCurrent, Chapters = JsonSerializer.Serialize(chapters) }, commandType: CommandType.StoredProcedure); } public async Task> ReviewCandidates(WritingPlanViewModel plan) { using var connection = factory.CreateConnection(); return (await connection.QueryAsync("dbo.WriterScheduleReviewCandidates", new { plan.UserID, plan.ProjectID, plan.BookID, plan.IncludeBlockedScenes }, commandType: CommandType.StoredProcedure)).AsList(); } public async Task SaveNewSchedule(WritingPlanViewModel plan, WritingScheduleSetupViewModel setup, IReadOnlyList allocations) { using var connection = factory.CreateConnection(); connection.Open(); using var transaction = connection.BeginTransaction(); var existing = await connection.QuerySingleAsync("dbo.WriterScheduleFindSaved", new { plan.UserID, setup.CreationToken, CreationFingerprint = setup.ReviewFingerprint }, transaction, commandType: CommandType.StoredProcedure); if (existing.HasValue) { transaction.Commit(); return existing.Value; } var id = await connection.QuerySingleAsync("dbo.CreateWritingPlan", new { plan.UserID, plan.ProjectID, plan.BookID, plan.PlanName, plan.GoalType, plan.StartDate, plan.DeadlineDate, plan.AvailableDaysJson, plan.SessionLengthMinutes, plan.IncludeBlockedScenes, plan.RebalanceMode, plan.IsActive }, transaction, commandType: CommandType.StoredProcedure); await connection.ExecuteAsync("dbo.WriterScheduleSaveReviewSettings", new { plan.UserID, WritingPlanID = id, setup.ContingencyPercent, setup.DraftingWordsPerHour, setup.CreationToken, CreationFingerprint = setup.ReviewFingerprint }, transaction, commandType: CommandType.StoredProcedure); await connection.ExecuteAsync("dbo.WriterPlanning", new { Action = "save", plan.UserID, WritingPlanID = id, Items = JsonSerializer.Serialize(allocations) }, transaction, commandType: CommandType.StoredProcedure); transaction.Commit(); return id; } public async Task Recalculate(int userId, WritingPlanSettingsEditViewModel plan, DateTime start, IReadOnlyList pending, IReadOnlyList allocations, int contingencyPercent) { using var connection = factory.CreateConnection(); var parameters = new DynamicParameters(new { UserID = userId, plan.WritingPlanID, ContingencyPercent = contingencyPercent, StartDate = start, ExpectedPending = JsonSerializer.Serialize(pending.Select(row => row.ActivityID)), Allocations = JsonSerializer.Serialize(allocations) }); parameters.Add("ExpectedModifiedUtc", plan.ModifiedDateUtc, DbType.DateTime2); await connection.ExecuteAsync("dbo.WriterScheduleRecalculate", parameters, commandType: CommandType.StoredProcedure); } public async Task ObservedDraftingRate(int userId, int bookId) { using var connection = factory.CreateConnection(); return await connection.QuerySingleAsync("dbo.WriterScheduleObservedDrafting", new { UserID = userId, BookID = bookId }, commandType: CommandType.StoredProcedure); } public async Task> DailyFocus(int userId, int bookId) { using var connection = factory.CreateConnection(); return (await connection.QueryAsync("dbo.WriterScheduleDailyFocus", new { UserID = userId, BookID = bookId, UtcDate = DateTime.UtcNow.Date }, commandType: CommandType.StoredProcedure)).AsList(); } public async Task> CapacityOverlap(int userId, int? planId, IReadOnlyList allocations) { if (allocations.Count == 0) return []; using var connection = factory.CreateConnection(); var dates = allocations.Select(row => DateOnly.FromDateTime(row.ScheduledDate)).Distinct(); return (await connection.QueryAsync("dbo.WriterScheduleCapacityOverlap", new { UserID = userId, WritingPlanID = planId, Dates = JsonSerializer.Serialize(dates) }, commandType: CommandType.StoredProcedure)).AsList(); } public async Task> Read(int user,int plan,string action="list") {using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterPlanning",new{Action=action,UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure)).ToArray();} public async Task Context(int user,int plan) {using var db=factory.CreateConnection();return await db.QuerySingleAsync("dbo.WriterPlanning",new{Action="context",UserID=user,WritingPlanID=plan},commandType:CommandType.StoredProcedure);} public async Task Save(int user,int plan,IReadOnlyList items) {using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action="save",UserID=user,WritingPlanID=plan,Items=JsonSerializer.Serialize(items)},commandType:CommandType.StoredProcedure);} public async Task Complete(int user,int plan,int activity,bool skip=false) {using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterPlanning",new{Action=skip?"skip":"complete",UserID=user,WritingPlanID=plan,ActivityID=activity},commandType:CommandType.StoredProcedure);} public async Task> Upcoming(int user,int book) {using var db=factory.CreateConnection();return(await db.QueryAsync("dbo.WriterPlanningUpcoming",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} }