68 lines
12 KiB
C#
68 lines
12 KiB
C#
using Microsoft.AspNetCore.Mvc.Rendering;
|
|
using Microsoft.Data.SqlClient;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services.Context;
|
|
using PlotLine.ViewModels;
|
|
namespace PlotLine.Services;
|
|
public sealed class CharacterWorkspace(ICharacterRepository characters,IProjectRepository projects,IBookRepository books,ICurrentUserService user,ICharacterEnrichmentService enrichment,ICharacterWorkspaceReader reader,IContextRelationshipReader graphReader,ContextFamilyExploration families,ContextWorkspaceNotifications notifications,IProjectActivityService activity,ICharacterService canonical)
|
|
{
|
|
public static readonly string[] Tabs=["overview","relationships","evolution","appearances","knowledge"];
|
|
public static string Classification(int? importance)=>importance switch{>=8=>"Major",>=4=>"Supporting",>=1=>"Minor",_=>"Unclassified"};
|
|
public async Task<(Character Character,Project Project,bool CanEdit)> Scope(int id)
|
|
{
|
|
var author=user.UserId??throw new UnauthorizedAccessException();var character=await characters.GetCharacterAsync(id)??throw new UnauthorizedAccessException();var project=await projects.GetForUserAsync(character.ProjectID,author)??throw new UnauthorizedAccessException();return(character,project,ContextEditPolicy.CanEdit(project));
|
|
}
|
|
public static void Validate(CharacterWorkspaceQuery q)
|
|
{if(q.Tab=="relationships"&&!string.IsNullOrEmpty(q.Category)&&q.Category is not ("family" or "story"))throw new ArgumentException("Choose Family, Story or all definitions.");if(!Tabs.Contains(q.Tab)&&q.Tab is not ("history" or "scenes" or "gallery"))throw new ArgumentException("Choose a character workspace tab.");if(q.Page is <1 or >100000||q.Search?.Length>120||q.Category?.Length>100||q.DefinitionPage is <1 or >100000)throw new ArgumentException("Invalid workspace filter.");}
|
|
public async Task<CharacterDetailViewModel> Header(int id,string? tab,CancellationToken ct)
|
|
{
|
|
if(tab!=null&&!Tabs.Contains(tab))throw new ArgumentException("Choose a character workspace tab.");var scope=await Scope(id);var summary=await reader.Summary(id,user.UserId!.Value,ct);var age=CharacterAgeDisplayService.GetProfileAge(scope.Character,summary.Ages.Select(r=>r.Scene).ToArray(),summary.Ages.Where(r=>r.IsAppearance).Select(r=>new SceneCharacter{CharacterID=id,SceneID=r.SceneID}).ToArray());
|
|
return new(){Character=scope.Character,Project=scope.Project,WorkspaceCanEdit=scope.CanEdit,WorkspaceTab=tab,WorkspaceCounts=summary.Counts,DisplayAge=age.DisplayText,AgeContext=age.Context,AgeReferenceScene=age.ReferenceScene,CharacterAnalysis=await enrichment.GetCharacterStatusAsync(id,user.UserId.Value)??new(){CharacterID=id}};
|
|
}
|
|
public async Task<CharacterWorkspacePage> Page(int id,CharacterWorkspaceQuery q,CancellationToken ct)
|
|
{
|
|
Validate(q);var header=await Header(id,q.Tab is "gallery" or "history" or "scenes"?null:q.Tab,ct);var page=new CharacterWorkspacePage{Profile=header,Query=q};
|
|
if(q.SceneID.HasValue){var point=(await reader.Records(id,user.UserId!.Value,new(){Tab="point",SceneID=q.SceneID},ct)).Rows.SingleOrDefault();if(point==null)throw new UnauthorizedAccessException();page.PointLabel=$"{point.BookDisplayTitle} · Ch {point.ChapterNumber} · Scene {point.SceneNumber}: {point.SceneTitle}";}
|
|
if(q.Tab=="overview"){
|
|
header.Aliases=(await characters.ListAliasesAsync(id)).Take(50).ToArray();var gallery=await reader.Gallery(id,user.UserId!.Value,1,ct);page.Images=gallery.Images;
|
|
var records=await reader.Records(id,user.UserId.Value,q,ct);page.Entries=records.Rows.Take(3).ToArray();
|
|
}else if(q.Tab=="gallery"){var gallery=await reader.Gallery(id,user.UserId!.Value,q.Page,ct);page.Total=gallery.Total;page.Images=gallery.Images;}
|
|
else if(q.Tab=="relationships"){
|
|
var result=await reader.Relationships(id,header.Project.ProjectID,user.UserId!.Value,q,ct);var order=StoryStateService.OrderScenes(new(){Books=result.Data.Books,Chapters=result.Data.Chapters,Scenes=result.Data.Scenes}).Select((s,i)=>(s.SceneID,i)).ToDictionary(x=>x.SceneID,x=>x.i);
|
|
var projected=q.SceneID.HasValue?RelationshipMapService.BuildAtScene(result.Data,order,q.SceneID.Value).ToDictionary(r=>r.CharacterRelationshipID):null;
|
|
page.Total=result.Total;page.Relationships=result.Data.Relationships.Select(r=>{var events=result.Data.RelationshipEvents.Where(e=>e.CharacterRelationshipID==r.CharacterRelationshipID&&e.EvidenceState=="Verified"&&(!q.SceneID.HasValue||order.GetValueOrDefault(e.SceneID,int.MaxValue)<=order.GetValueOrDefault(q.SceneID.Value,-1))).OrderBy(e=>order.GetValueOrDefault(e.SceneID,-1)).ThenBy(e=>e.CreatedDate).ThenBy(e=>e.RelationshipEventID).ToArray();return new CurrentRelationshipViewModel{Relationship=r,Events=events,LatestEvent=q.SceneID.HasValue?(projected!.TryGetValue(r.CharacterRelationshipID,out var p)?new(){RelationshipStateName=p.CurrentStateName,Intensity=p.CurrentIntensity,Description=p.Notes}:new(){RelationshipStateName="Not established / ended at this point",Description="Author definition; no established selected-point state."}):events.LastOrDefault()};}).ToArray();
|
|
}else{var result=await reader.Records(id,user.UserId!.Value,q,ct);page.Total=result.Total;page.Entries=result.Rows;}
|
|
if(q.Tab is not ("overview" or "gallery"))page.Books=(await books.ListByProjectAsync(header.Project.ProjectID)).Take(2000).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();return page;
|
|
}
|
|
public async Task<ContextFamilyTree> Family(int id,int? focus,int[] expanded,CancellationToken ct)
|
|
{var scope=await Scope(id);return await families.ReadProjectTree(scope.Project.ProjectID,user.UserId!.Value,focus??id,new(){SceneID=0,ChapterID=0,SceneTitle="Author family reference"},scope.CanEdit,expanded,ct);}
|
|
public async Task<ContextLensGraph> Story(int id,int? sceneId,CancellationToken ct)
|
|
{
|
|
var scope=await Scope(id);var data=await graphReader.Read(scope.Project.ProjectID,user.UserId!.Value,sceneId??0,id,"story",3,[],ct);var order=StoryStateService.OrderScenes(new(){Books=data.Data.Books,Chapters=data.Data.Chapters,Scenes=data.Data.Scenes}).ToArray();
|
|
// An omitted point means the last canonical scene, explicitly labelled as author reference.
|
|
var selected=sceneId.HasValue?order.SingleOrDefault(s=>s.SceneID==sceneId):order.LastOrDefault();if(sceneId.HasValue&&selected==null)throw new UnauthorizedAccessException();
|
|
if(selected==null)return new("story",id,null,0,"No narrative scene recorded",scope.CanEdit,data.Truncated,[new(id,scope.Character.CharacterName,scope.Character.BirthDate,scope.Character.IsArchived,false,null)],[]);
|
|
return ContextRelationshipLenses.Compose(data,"story",new(){SceneID=selected.SceneID,ChapterID=selected.ChapterID,SceneTitle=selected.SceneTitle},scope.CanEdit);
|
|
}
|
|
public async Task<IReadOnlyList<object>> Lookup(int id,string search,CancellationToken ct)
|
|
{var scope=await Scope(id);if(search.Length is <2 or >120)return [];return (await graphReader.Lookup(scope.Project.ProjectID,user.UserId!.Value,search,ct)).Select(c=>(object)new{id=c.CharacterID,name=c.CharacterName}).ToArray();}
|
|
public async Task<CharacterWorkspaceOperation> Operation(int id,int relationship,int? eventID,string action,CancellationToken ct)
|
|
{
|
|
var scope=await Scope(id);if(!scope.CanEdit)throw new UnauthorizedAccessException();if(action is not ("definition" or "archive" or "event-edit" or "event-remove"))throw new ArgumentException("Unsupported relationship operation.");
|
|
(CharacterRelationshipFrame Relationship,CharacterWorkspaceEvent? Event) frame;try{frame=await reader.Frame(id,user.UserId!.Value,relationship,eventID,ct);}catch(SqlException error)when(error.Number==51020){throw new UnauthorizedAccessException();}if(action.StartsWith("event-")&&frame.Event==null)throw new UnauthorizedAccessException();var r=frame.Relationship.Relationship;var e=frame.Event?.Record;var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);
|
|
return new(){TypeID=r.RelationshipTypeID,Reciprocal=r.IsReciprocal,Permanent=r.IsPermanent,ReaderKnows=r.IsKnownToReader,Types=lookups.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray(),CharacterID=id,RelationshipID=relationship,EventID=eventID,Action=action,Version=frame.Relationship.Version,Record=frame.Relationship,Event=frame.Event,Notes=e?.Description??r.Notes,StateID=e?.RelationshipStateID??r.InitialRelationshipStateID,Intensity=e?.Intensity??r.InitialIntensity,Awareness=e?.IsKnownToOtherCharacter??r.ReaderInitiallyKnows,States=lookups.RelationshipStates.Select(s=>new SelectListItem(s.StateName,s.RelationshipStateID.ToString())).ToArray()};
|
|
}
|
|
public async Task Change(CharacterWorkspaceOperation input,CancellationToken ct)
|
|
{
|
|
var frame=await Operation(input.CharacterID,input.RelationshipID,input.EventID,input.Action,ct);if(input.Version!=frame.Version)throw new InvalidOperationException("This relationship or its history changed. Cancel and reopen to review current values.");if(input.Action is "archive" or "event-remove"&&!input.Confirmed)throw new ArgumentException("Confirm the identified removal.");if(input.Notes?.Length>4000||input.Intensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");
|
|
if(input.Action.StartsWith("event-")&&frame.Event?.ProtectedSource==true)throw new ArgumentException("This event has source/review dependencies. Manage it through its source workflow.");
|
|
try{await reader.Change(input,user.UserId!.Value,ct);}catch(SqlException ex)when(ex.Number==51020){throw new UnauthorizedAccessException();}catch(SqlException ex)when(ex.Number==51021){throw new InvalidOperationException(ex.Message);}catch(SqlException ex)when(ex.Number==51022){throw new ArgumentException(ex.Message);}
|
|
var scope=await Scope(input.CharacterID);await activity.RecordAsync(scope.Project.ProjectID,input.Action=="archive"?"Archived":input.Action=="event-remove"?"Deleted":"Updated","Relationship",input.RelationshipID,"Character workspace relationship operation");await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID);
|
|
}
|
|
public async Task<CharacterDetailViewModel> AddForm(int id,CancellationToken ct,InitialRelationshipEditViewModel? input=null)
|
|
{var model=await Header(id,null,ct);if(!model.WorkspaceCanEdit)throw new UnauthorizedAccessException();var lookup=await characters.GetLookupsAsync(model.Project.ProjectID);model.RelationshipTypeOptions=lookup.RelationshipTypes.Select(t=>new SelectListItem(t.RelationshipCategoryName+" · "+t.TypeName,t.RelationshipTypeID.ToString())).ToArray();model.RelationshipStateOptions=lookup.RelationshipStates.Select(t=>new SelectListItem(t.StateName,t.RelationshipStateID.ToString())).ToArray();model.BookOptions=(await books.ListByProjectAsync(model.Project.ProjectID)).Select(b=>new SelectListItem(b.BookDisplayTitle,b.BookID.ToString())).ToArray();if(input!=null){model.NewInitialRelationship=input;var target=await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value);if(target?.ProjectID==model.Project.ProjectID)model.CharacterOptions=[new(target.CharacterName,target.CharacterID.ToString())];}return model;}
|
|
public async Task Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct)
|
|
{var scope=await Scope(id);if(!scope.CanEdit||input.CharacterID!=id||input.CharacterRelationshipID!=0)throw new UnauthorizedAccessException();if((await characters.GetReferenceCharacterAsync(input.RelatedCharacterID,user.UserId!.Value))?.ProjectID!=scope.Project.ProjectID||input.RelatedCharacterID==id)throw new ArgumentException("Choose another character in this project.");if(input.Notes?.Length>4000||input.InitialIntensity is <1 or >10)throw new ArgumentException("Use valid notes and intensity.");var lookups=await characters.GetLookupsAsync(scope.Project.ProjectID);if(!lookups.RelationshipTypes.Any(t=>t.RelationshipTypeID==input.RelationshipTypeID)||(input.InitialRelationshipStateID.HasValue&&!lookups.RelationshipStates.Any(t=>t.RelationshipStateID==input.InitialRelationshipStateID)))throw new ArgumentException("Choose a recorded relationship type and state.");if(input.InitialBookID.HasValue&&!(await books.ListByProjectAsync(scope.Project.ProjectID)).Any(b=>b.BookID==input.InitialBookID))throw new UnauthorizedAccessException();input.ProjectID=scope.Project.ProjectID;input.ReturnCharacterID=id;await canonical.SaveInitialRelationshipAsync(input);await notifications.Invalidate(user.UserId.Value,projectId:scope.Project.ProjectID);}
|
|
}
|