PlotDirector/PlotLine/Controllers/RelationshipMapController.cs

143 lines
8.3 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Data;
using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize]
public sealed class RelationshipMapController(IRelationshipMapService relationshipMap, ICharacterRepository repository, ICharacterService characters, IProjectRepository projectAccess, ICurrentUserService user, ContextWorkspaceNotifications notifications) : Controller
{
public async Task<IActionResult> Index(int projectId, int? bookId, int? chapterId, int? sceneId, int? focusCharacterId, bool showFullNetwork = false)
{
var position = StoryPosition.FromTimelineSelection(projectId, bookId, chapterId, sceneId);
var model = position is null
? null
: await relationshipMap.GetAsync(position, null, true);
if (model is null) return NotFound();
model.FocusCharacterID = focusCharacterId;
model.ShowFullNetwork = showFullNetwork;
foreach (var node in model.Nodes) node.IsFocus = node.CharacterID == focusCharacterId;
return View(model);
}
[HttpGet]
public async Task<IActionResult> State(int projectId, int? bookId, int? sceneId)
{
var model = await relationshipMap.GetAsync(projectId, bookId, null, sceneId, null, true);
return model is null ? NotFound() : Json(model);
}
// Main workspace author-reference facts, independent of manuscript scene/POV visibility.
[HttpGet]
public async Task<IActionResult> Family(int projectId)
{
if (user.UserId is not int author) return Unauthorized();
var project = await projectAccess.GetForUserAsync(projectId, author);
if (project is null) return NotFound();
var data = await repository.GetRelationshipMapAsync(projectId);
var people = data.Characters.Where(c => !c.IsArchived).ToDictionary(c => c.CharacterID);
var sceneOrder = StoryStateService.OrderScenes(new TimelineData
{ Books = data.Books, Chapters = data.Chapters, Scenes = data.Scenes })
.Select((scene, index) => (scene.SceneID, index)).ToDictionary(s => s.SceneID, s => s.index);
var history = data.RelationshipEvents.ToLookup(e => e.CharacterRelationshipID);
var relationships = data.Relationships.Where(r => !r.IsArchived
&& people.ContainsKey(r.CharacterAID) && people.ContainsKey(r.CharacterBID)
&& PlotLine.Services.Context.ContextRelationshipLenses.Family(r.RelationshipCategoryName, r.RelationshipTypeName))
.Select(r => new RelationshipMapRelationshipViewModel
{
CharacterRelationshipID = r.CharacterRelationshipID,
CharacterAID = r.CharacterAID, CharacterBID = r.CharacterBID,
CharacterAName = people[r.CharacterAID].CharacterName, CharacterBName = people[r.CharacterBID].CharacterName,
RelationshipTypeName = r.RelationshipTypeName, RelationshipCategoryName = r.RelationshipCategoryName,
CssClass = r.RelationshipCategoryName == "Family" ? "relationship-category-family" : "relationship-category-romantic",
InitialStateEditable = r.IsInitialRelationship,
InitialStateName = r.InitialRelationshipStateName ?? r.RelationshipTypeName,
CurrentStateName = r.InitialRelationshipStateName ?? r.RelationshipTypeName,
InitialIntensity = r.InitialIntensity, CurrentIntensity = r.InitialIntensity,
IsReciprocal = r.IsReciprocal, Known = r.ReaderInitiallyKnows, Notes = r.Notes,
History = history[r.CharacterRelationshipID]
.OrderBy(e => sceneOrder.GetValueOrDefault(e.SceneID, int.MaxValue))
.ThenBy(e => e.CreatedDate).ThenBy(e => e.RelationshipEventID)
.Select(e => new RelationshipMapHistoryItemViewModel
{
SceneID = e.SceneID,
Label = $"{e.BookDisplayTitle} · Ch {e.ChapterNumber} · Scene {e.SceneNumber}: {e.SceneTitle}",
StateName = e.RelationshipStateName, Intensity = e.Intensity, Notes = e.Description
}).ToArray()
}).ToArray();
return Json(new
{
canEdit = PlotLine.Services.Context.ContextEditPolicy.CanEdit(project), relationships,
nodes = people.Values.Select(c => new { id = c.CharacterID, name = c.CharacterName, birthDate = c.BirthDate })
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Save(WorkspaceRelationshipEdit model)
{
if (!ModelState.IsValid) return BadRequest("Check the relationship fields.");
var data = await repository.GetRelationshipMapAsync(model.ProjectID);
var lookups = await repository.GetLookupsAsync(model.ProjectID);
if (model.SourceID == model.TargetID
|| !data.Characters.Any(x => x.CharacterID == model.SourceID)
|| !data.Characters.Any(x => x.CharacterID == model.TargetID)
|| !lookups.RelationshipTypes.Any(x => x.RelationshipTypeID == model.TypeID)
|| !lookups.RelationshipStates.Any(x => x.RelationshipStateID == model.StateID)
|| (model.SceneID.HasValue && !data.Scenes.Any(x => x.SceneID == model.SceneID)))
return BadRequest("Choose valid characters, type, state and scene from this project.");
var matches = data.Relationships.Where(x => !x.IsArchived && x.RelationshipTypeID == model.TypeID
&& ((x.CharacterAID == model.SourceID && x.CharacterBID == model.TargetID)
|| (x.IsReciprocal && x.CharacterAID == model.TargetID && x.CharacterBID == model.SourceID))).ToList();
if (matches.Count > 1) return Conflict("Multiple matching relationships exist. Review them in the character details before editing.");
var existing = matches.SingleOrDefault();
if (model.SceneID.HasValue)
{
var previous = data.RelationshipEvents.Where(x => x.CharacterRelationshipID == existing?.CharacterRelationshipID && x.SceneID == model.SceneID)
.OrderByDescending(x => x.RelationshipEventID).FirstOrDefault();
var change = new RelationshipEventCreateViewModel
{
RelationshipEventID = previous?.RelationshipEventID ?? 0,
CharacterRelationshipID = existing?.CharacterRelationshipID,
SceneID = model.SceneID.Value, CharacterAID = model.SourceID, CharacterBID = model.TargetID,
RelationshipTypeID = model.TypeID, RelationshipStateID = model.StateID, Intensity = model.Intensity,
IsReciprocal = model.Mutual, Description = model.Notes, IsKnownToOtherCharacter = model.Known, ReturnProjectID = model.ProjectID
};
if (previous is null) await characters.AddRelationshipEventAsync(change);
else await characters.UpdateRelationshipEventAsync(change);
}
else
{
await characters.SaveInitialRelationshipAsync(new InitialRelationshipEditViewModel
{
CharacterRelationshipID = existing?.CharacterRelationshipID ?? 0,
ProjectID = model.ProjectID, CharacterID = existing?.CharacterAID ?? model.SourceID,
RelatedCharacterID = existing?.CharacterBID ?? model.TargetID, RelationshipTypeID = model.TypeID,
InitialBookID = existing?.InitialBookID, InitialRelationshipStateID = model.StateID,
InitialIntensity = model.Intensity, IsReciprocal = model.Mutual, ReaderInitiallyKnows = model.Known, Notes = model.Notes
});
}
if (user.UserId is int author) await notifications.Invalidate(author, projectId: model.ProjectID, kind: "relationships");
return Ok();
}
}
public sealed class WorkspaceRelationshipEdit
{
public int ProjectID { get; set; }
public int SourceID { get; set; }
public int TargetID { get; set; }
public int TypeID { get; set; }
public int StateID { get; set; }
public int? SceneID { get; set; }
[System.ComponentModel.DataAnnotations.Range(1, 10)]
public int? Intensity { get; set; }
public bool Mutual { get; set; }
public bool Known { get; set; }
[System.ComponentModel.DataAnnotations.StringLength(4000)]
public string? Notes { get; set; }
}