using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using PlotLine.Services; using PlotLine.Data; using PlotLine.ViewModels; using PlotLine.Models; using PlotLine.Services.Context; using Microsoft.Data.SqlClient; namespace PlotLine.Controllers; [Authorize] public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser, ContextSavedData savedData, LocationDetailsRepository details, ILocationRepository records, MapRepository maps, IProjectActivityService activity) : Controller { public async Task Index(int projectId) { if (currentUser.UserId is not int userId) return Unauthorized(); var project = await projects.GetForUserAsync(projectId, userId); return project is null ? NotFound() : View(new LocationListViewModel { Project = project }); } public async Task Create(int projectId) { var model = await locations.GetCreateAsync(projectId); return model is null ? NotFound() : View("Edit", model); } public async Task Edit(int id) { var model = await locations.GetEditAsync(id); return model is null ? NotFound() : View(model); } public async Task Details(int id, string? tab = null) { if (currentUser.UserId is not int userId) return Unauthorized(); var model = await locations.GetDetailAsync(id); if (model is null) return NotFound(); var project = await projects.GetForUserAsync(model.Project.ProjectID, userId); if (project is null) return NotFound(); ViewData["LocationTab"] = tab == "geography" ? "spatial" : tab; model.CanEdit = ContextEditPolicy.CanEdit(project) && !model.Location.IsArchived; var directory = model.Locations.ToDictionary(location => location.LocationID); var ancestors = new List(); var seen = new HashSet(); for (LocationItem? location = model.Location; location is not null && seen.Add(location.LocationID); location = directory.GetValueOrDefault(location.ParentLocationID.GetValueOrDefault())) { ancestors.Add(location.LocationID); } model.Usage = await details.ReadUsageAsync(project.ProjectID, id); model.Spatial = await details.ReadSpatialAsync(project.ProjectID, ancestors); return View(model); } [HttpGet] public async Task DetailRelationships(int id) { var location = await records.GetAsync(id); if (location is null) return NotFound(); var active = (await records.ListByProjectAsync(location.ProjectID)) .Where(item => !item.IsArchived).Select(item => item.LocationID).ToHashSet(); var relationships = (await records.ListRelationshipsByProjectAsync(location.ProjectID)) .Where(item => active.Contains(item.FromLocationID) && active.Contains(item.ToLocationID)); return Json(relationships); } [HttpPost, ValidateAntiForgeryToken] public async Task WriteDetailRelationship(LocationRelationshipEditViewModel model, DateTime? expectedUpdatedDate, bool archive) { if (currentUser.UserId is not int userId) return Unauthorized(); if (!ModelState.IsValid || model.ProjectID <= 0 || model.LocationRelationshipID < 0 || model.FromLocationID <= 0 || model.ToLocationID <= 0 || model.FromLocationID == model.ToLocationID || model.Strength is < 1 or > 10 || (!archive && model.LocationRelationshipTypeID <= 0)) { return BadRequest(new { error = "Check the locations, relationship type and strength." }); } try { var id = await details.WriteRelationshipAsync(userId, model, expectedUpdatedDate, archive); var verb = archive ? "Archived" : model.LocationRelationshipID == 0 ? "Created" : "Updated"; await activity.RecordAsync(model.ProjectID, verb, "Location Relationship", id, "Location relationship"); await savedData.Project(model.ProjectID, "locations", id, "Location Relationship"); return Json(new { id }); } catch (SqlException ex) when (ex.Number == 51010) { return Forbid(); } catch (SqlException ex) when (ex.Number == 51011) { return Conflict(new { error = ex.Message }); } } [HttpGet] public async Task SpatialMap(int id, int mapId, Guid featureId) { if (currentUser.UserId is not int userId) return Unauthorized(); var location = await records.GetAsync(id); if (location is null) return NotFound(); var project = await projects.GetForUserAsync(location.ProjectID, userId); if (project is null) return NotFound(); var document = await maps.GetAsync(project.ProjectID, mapId, userId); if (document is null || !document.Features.Any(feature => feature.FeatureID == featureId && feature.IsPlaced)) return NotFound(); ViewData["SpatialRenderer"] = true; ViewData["DetachedWorkspace"] = true; return View("~/Views/Maps/Index.cshtml", new MapsViewModel { Project = project, Maps = [document.Map], Document = document }); } public async Task Merge(int id) { var model = await locations.GetMergeAsync(id); return model is null ? NotFound() : View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task Merge([Bind(Prefix = "Form")] EntityMergeForm form) { if (ModelState.IsValid) { try { var result = await locations.MergeAsync(form); if (result is null) return NotFound(); TempData["LocationMessage"] = $"{result.SourceName} merged into {result.TargetName}."; return RedirectToAction(nameof(Details), new { id = result.TargetID }); } catch (InvalidOperationException ex) { ModelState.AddModelError(string.Empty, ex.Message); } } var model = await locations.GetMergeAsync(form.SourceID); if (model is null) return NotFound(); model.Form = form; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task Reparent(int projectId, int locationId, int parentLocationId, int? expectedParentLocationId) { if (!ModelState.IsValid) { if (IsAjaxRequest()) return BadRequest(new { error = "Invalid location selection. Please try again." }); TempData["LocationError"] = "Invalid location selection. Please try again."; return RedirectToAction(nameof(Index), new { projectId }); } try { await locations.ReparentAsync(projectId, locationId, parentLocationId, expectedParentLocationId); await savedData.Project(projectId, "locations", locationId, "Location"); TempData["GeographyMessage"] = await geography.SubmitAsync(projectId, locationId); if (IsAjaxRequest()) { var model = await locations.GetLocationsAsync(projectId); return model is null ? NotFound() : PartialView("_LocationTree", model); } TempData["LocationMessage"] = "Location moved to its new parent."; } catch (InvalidOperationException ex) { if (IsAjaxRequest()) return BadRequest(new { error = ex.Message }); TempData["LocationError"] = ex.Message; } return RedirectToAction(nameof(Index), new { projectId }); } [HttpPost] [ValidateAntiForgeryToken] public async Task Save(LocationEditViewModel model) { if (!ModelState.IsValid) return await InvalidEdit(model); try { var before = model.LocationID > 0 ? await locations.GetEditAsync(model.LocationID) : null; var locationId = await locations.SaveAsync(model); if ((model.ParentLocationID.HasValue && (before is null || before.ParentLocationID != model.ParentLocationID)) || (before is not null && (before.LocationName != model.LocationName || before.LocationTypeID != model.LocationTypeID))) TempData["LocationMessage"] = await geography.SubmitAsync(model.ProjectID, locationId); return RedirectToAction(nameof(Details), new { id = locationId }); } catch (InvalidOperationException ex) { ModelState.AddModelError(string.Empty, ex.Message); return await InvalidEdit(model); } } private async Task InvalidEdit(LocationEditViewModel model) { var editModel = model.LocationID == 0 ? await locations.GetCreateAsync(model.ProjectID) : await locations.GetEditAsync(model.LocationID); if (editModel is null) { return NotFound(); } editModel.ParentLocationID = model.ParentLocationID; editModel.LocationName = model.LocationName; editModel.Aliases = model.Aliases; editModel.LocationTypeID = model.LocationTypeID; editModel.Description = model.Description; editModel.ShowInQuickAddBar = model.ShowInQuickAddBar; editModel.ExcludeFromCompanionDetection = model.ExcludeFromCompanionDetection; editModel.DetectionPriority = model.DetectionPriority; return View("Edit", editModel); } [HttpPost] [ValidateAntiForgeryToken] public async Task SetPreferredName(int id, string preferredName) { try { await locations.SetPreferredNameAsync(id, preferredName); TempData["LocationMessage"] = $"Preferred name set to {preferredName}."; } catch (InvalidOperationException ex) { TempData["LocationMessage"] = ex.Message; } return RedirectToAction(nameof(Details), new { id }); } [HttpPost] [ValidateAntiForgeryToken] public async Task Archive(int id, int projectId) { await locations.ArchiveAsync(id); TempData["ArchiveMessage"] = "Location archived. You can restore it from Archived Items."; return RedirectToAction(nameof(Index), new { projectId }); } [HttpPost] [ValidateAntiForgeryToken] public async Task AddRelationship(LocationRelationshipEditViewModel model) { await locations.SaveRelationshipAsync(model); return RedirectToAction(nameof(Details), new { id = model.FromLocationID, tab = "relationships" }); } [HttpPost] [ValidateAntiForgeryToken] public async Task DropRelationship(LocationRelationshipEditViewModel model) { if (!ModelState.IsValid || model.FromLocationID == model.ToLocationID) { if (IsAjaxRequest()) return BadRequest(new { error = "Choose two different locations and a relationship type." }); return RedirectToAction(nameof(Index), new { projectId = model.ProjectID }); } try { await locations.SaveRelationshipAsync(model); if (IsAjaxRequest()) return Json(new { message = "Location relationship saved." }); } catch (InvalidOperationException ex) { if (IsAjaxRequest()) return BadRequest(new { error = ex.Message }); TempData["LocationError"] = ex.Message; } return RedirectToAction(nameof(Index), new { projectId = model.ProjectID }); } private bool IsAjaxRequest() => Request.Headers["X-Requested-With"] == "XMLHttpRequest"; [HttpPost] [ValidateAntiForgeryToken] public async Task ArchiveRelationship(int id, int returnLocationId) { var location = await locations.GetEditAsync(returnLocationId); await locations.ArchiveRelationshipAsync(id); if (location is not null) await savedData.Project(location.ProjectID, "locations", id, "Location Relationship"); TempData["ArchiveMessage"] = "Location relationship archived."; return RedirectToAction(nameof(Details), new { id = returnLocationId, tab = "relationships" }); } }