diff --git a/Docs/Maps_Stage4.md b/Docs/Maps_Stage4.md
new file mode 100644
index 00000000..64426488
--- /dev/null
+++ b/Docs/Maps_Stage4.md
@@ -0,0 +1,40 @@
+# Maps Stage 4 — theme integration and reference images
+
+Stage 3 completed, including Development deployment, authenticated acceptance, final commits and a clean worktree, before Stage 4 began. Starting commit: `d439bf00eff9d6a943312aef21217a1435fae100`.
+
+## Architecture and behaviour
+
+Application chrome uses the existing `pd` theme tokens: panes, toolbar, breadcrumbs, status, inputs, menus, dialogs and Story controls. The map SVG owns separate palette variables. Changing the application theme does not change map data, revision or dirty state. A shared device-theme listener keeps the detached shell in sync with the main shell through the existing non-sensitive localStorage preference.
+
+Each map persists `AppearanceJson` and `ReferenceJson`, independent of its structured features and relationships. Existing maps default to the original blue water/cream land **Light** appearance, including inside a Dark application. **Paper**, **Dark** and **Custom** are also available; Custom exposes canvas/water and land colours. Derived ink, label halos, markers, routes, selection and Story colours keep those choices readable. Reference images remain visual references: no OCR, inferred Locations, routes, scale, travel time or geographical facts are created.
+
+The Map appearance inspector supports one active reference image per map, project-library selection/reuse, upload/replace/remove, show/hide, opacity, position, size, scale, rotation, fit and reset. A new reference starts faded and locked. Replacement retains placement and settings. Unlocked references have move/resize/rotate handles, keyboard controls and grouped Undo/Redo. Locked-image drags pan the map; foreground structured features retain their usual hit targets. Explore and Story expose read-only appearance information.
+
+Uploads deliberately create project resources; attaching them and changing their placement remain unsaved map edits. The inspector explains this distinction. Removing a reference from a map leaves it in the reusable project library. Unused images can be permanently deleted through the canonical application dialog; saved maps prevent deletion. This operation explicitly does not support Undo. Map duplication shares the resource instead of copying bytes. Deleting a project/account cascades its image data.
+
+## Storage, validation and backup
+
+Migration **212_MapAppearanceReferences.sql** adds the two per-map settings columns, project-owned immutable image blobs, and authorized Dapper stored-procedure operations. It updates Save/List/Get, the fifth Maps backup result set and project restore. It preserves the latest Stage 2 journey semantics and Stage 3 archived-scene restore behaviour. It was applied forward-only to `PlotDirector_Development` after verified copy-only CHECKSUM backups.
+
+Only PNG, JPEG and WebP inputs up to 10 MB and 16 megapixels are accepted. Full decoding must succeed; images are resized to at most 4096 pixels on their longest side and re-encoded as WebP, at most 8 MB. Filename paths are stripped. SVG and arbitrary executable content are not served. Content hashes deduplicate processed images within a project. Project-owner subscription storage allowance and `UserFile` accounting apply. CSRF, application authorization and stored-procedure authorization protect mutations. Image reads require project access, validate the image/project pair and return private/no-cache, nosniff, same-origin resource headers and content-hash ETags. No public filesystem paths or image data are embedded in normal map JSON.
+
+Full project backups contain the image bytes, metadata and map settings. Restore validates images and same-project references, restores exact encoded bytes, rebuilds storage accounting and invalidates stale map revisions. The normal restore service accepts backup versions 1.0 and 1.1; old backups lacking these fields restore to the default Light map with no image. A pre-restore safety backup remains mandatory.
+
+Floor Plans retains its existing upload paths, persistence, controls and cleanup. Only encoded-format inspection is shared with its existing background-image service. Maps uses database blobs because a project backup must be self-contained; copying Floor Plans' path-only approach would not satisfy portable image restoration. Database-owned resources are recognized by hard-delete cleanup and create no loose image files.
+
+## Navigation and accessibility
+
+Stage 3's canonical Save and continue / Discard changes / Keep editing dialog remains in use and now follows application themes. It retains the first requested action, coalesces repeated requests, awaits successful saves, and keeps edits after failures. Escape/X cancel the pending navigation. Reference and appearance changes participate in the same dirty state and Undo history; active adjustments complete before application navigation. Genuine browser unload retains standards-compliant `beforeunload` protection. Maps has no direct native `alert()` or `confirm()` calls.
+
+Controls have labels, keyboard-operable handles, visible focus, lock/visibility state, percentage opacity and text status/error feedback. The persistent SVG image node avoids reload/decoding during selection, theme changes or Story navigation. Maximise/Restore retains the document and view. Detached windows use the minimal shared shell and existing navigation/revision-conflict bridge. PWA uses the existing ribbon without duplicate Maximise controls; narrow layouts retain the established workspace behaviour.
+
+## Verification before deployment
+
+- Solution build: no warnings or errors. Full executable regression harness: **403 passing cases**.
+- Focused image/service/controller/backup validation and pure JavaScript appearance-engine tests pass.
+- Development SQL tests pass: processed-content deduplication, project access, storage accounting, unchanged structured geography, atomic foreign-reference rejection, used/unused deletion, exact-byte restore after deletion, stale revision invalidation and shared-resource map deletion.
+- Web and PWA Stage 4 browser tests pass across all seven themes: readable pane/menu contrast, independent canvas, custom colours, upload/replace/opacity/transforms, lock/pan, visibility/remove/Undo, themed unsaved dialog, maximise, persistence, detached theme sync and narrow layouts.
+- 500 scenes / 30 characters / 5,000 appearances: 50 Story navigation changes complete in approximately 0.8 seconds in each web/PWA run without image-node replacement or extra image reads. This is a fixture benchmark, not a universal latency guarantee.
+- Existing Maps Stage 1, Stage 2, Stage 3 and detached browser suites pass. Relationships ribbon and focus stability pass in web/PWA at 1440/1700/1920. Actual installed-PWA context-menu suite passes, including real clipboard operations and theme/keyboard/focus checks.
+
+Deployment, authenticated live acceptance, cleanup and final commit evidence are recorded below after completion.
diff --git a/PlotLine.Tests/Browser/maps-appearance-engine.cjs b/PlotLine.Tests/Browser/maps-appearance-engine.cjs
new file mode 100644
index 00000000..b06e98d0
--- /dev/null
+++ b/PlotLine.Tests/Browser/maps-appearance-engine.cjs
@@ -0,0 +1,12 @@
+const assert=require('node:assert/strict'),E=require('../../PlotLine/wwwroot/js/maps-appearance-engine.js');
+for(const preset of ['light','paper','dark','custom']){
+ const map={appearanceJson:JSON.stringify({preset,backgroundColor:'#123456',landColor:'#efefef'})},before=JSON.stringify(map),p=E.palette(map);assert.match(p.backgroundColor,/^#[0-9a-f]{6}$/);assert.equal(JSON.stringify(map),before);assert.equal(p.story.length,3);
+ if(preset!=='custom')assert.deepEqual([p.backgroundColor,p.landColor],[E.presets[preset].backgroundColor,E.presets[preset].landColor]);else assert.equal(p.backgroundColor,'#123456');
+}
+assert.equal(E.palette({}).backgroundColor,'#c9dfdf','Existing maps retain their working canvas independently of UI theme');
+const view={x:-600,y:-400,w:1200,h:800},image={imageID:'asset',width:1600,height:900},r=E.fit(image,view,45);
+assert.equal(r.isLocked,true);assert.equal(r.opacity,.35);const boundsW=r.width*Math.SQRT1_2+r.height*Math.SQRT1_2;assert(boundsW<=view.w*.8+1e-8);
+assert.deepEqual(E.transform(r,'move',[0,0],[20,30]),{...r,x:r.x+20,y:r.y+30});
+assert.equal(E.transform({...r,rotation:0},'rotate',[1,0],[0,1]).rotation,90);const scaled=E.transform(r,'scale',[r.x+10,r.y],[r.x+20,r.y]);assert.equal(scaled.width,r.width*2);assert.equal(scaled.height,r.height*2);
+assert.equal(E.reference({referenceJson:'{}'}),null);assert.equal(E.reference({referenceJson:JSON.stringify(r)}).imageID,'asset');
+console.log('PASS Maps appearance presets/custom isolation, immutable palette, reference transforms and locked fit defaults');
diff --git a/PlotLine.Tests/Browser/maps-appearance.cjs b/PlotLine.Tests/Browser/maps-appearance.cjs
new file mode 100644
index 00000000..f19ebdbd
--- /dev/null
+++ b/PlotLine.Tests/Browser/maps-appearance.cjs
@@ -0,0 +1,57 @@
+const {chromium}=require('playwright'),assert=require('node:assert/strict');
+const base=process.env.PD_MAPS_STAGE4_URL||'http://127.0.0.1:5251';
+(async()=>{const browser=await chromium.launch();try{
+ for(const pwa of [false,true]){
+ const context=await browser.newContext({viewport:{width:1800,height:1100}});if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
+ const page=await context.newPage(),errors=[];page.setDefaultTimeout(10000);page.on('pageerror',e=>errors.push(e.message));page.on('dialog',async d=>{errors.push('Unexpected native '+d.type());await d.dismiss();});
+ const png=await page.evaluate(()=>{const c=document.createElement('canvas');c.width=256;c.height=128;const x=c.getContext('2d');x.fillStyle='#fff';x.fillRect(0,0,256,128);x.strokeStyle='#222';x.strokeRect(20,20,180,75);return c.toDataURL('image/png').split(',')[1];}),buffer=Buffer.from(png,'base64');
+ const darkBuffer=Buffer.from(await page.evaluate(()=>{const c=document.createElement('canvas');c.width=256;c.height=128;const x=c.getContext('2d');x.fillStyle='#080b10';x.fillRect(0,0,256,128);x.strokeStyle='#fff';x.strokeRect(20,20,180,75);return c.toDataURL('image/png').split(',')[1];}),'base64');
+ let saved=null,images=[],uploads=0,imageReads=0,writes=0,fixture=await(await context.request.get(base+'/map-story-fixture')).json();
+ await context.route('**/fixture?page=maps&story=true*',async route=>{const response=await context.request.get(route.request().url());let html=await response.text();html=html.replace(/(";
+ surface += "";
}
surface += await Render("Shared/_ConfirmationDialog");
var initialTheme = appearance.ThemeKey ?? "warm-light";
@@ -364,7 +364,7 @@ internal static class ToolbarBrowserHost
PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default);
var contributions = contributionWriter.ToString();
context.Response.ContentType = "text/html; charset=utf-8";
- await context.Response.WriteAsync("
" + appearanceScript + "");
});
await app.RunAsync();
}
diff --git a/PlotLine/Controllers/MapsController.cs b/PlotLine/Controllers/MapsController.cs
index a268ee63..dc71b6ad 100644
--- a/PlotLine/Controllers/MapsController.cs
+++ b/PlotLine/Controllers/MapsController.cs
@@ -21,6 +21,7 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
if (id.HasValue && document is null) return NotFound();
if (detached) ViewData["DetachedWorkspace"] = true;
return View(new MapsViewModel { Project = project, Maps = await maps.ListAsync(projectId, UserID), Document = document,
+ ReferenceImages = await maps.ListImagesAsync(projectId, UserID),
Locations = await locations.ListByProjectAsync(projectId), FloorPlans = await floorPlans.ListByProjectAsync(projectId) });
}
[HttpGet]
@@ -79,4 +80,28 @@ public sealed class MapsController(MapRepository maps, IProjectRepository projec
catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); }
}
+ [HttpGet]
+ public async Task ReferenceImage(int projectId,Guid imageId)
+ {
+ if(!await access.CanAccessProjectAsync(projectId))return NotFound();
+ var image=await maps.GetImageAsync(projectId,UserID,imageId);if(image?.ImageData is null)return NotFound();
+ Response.Headers.CacheControl="private, no-cache";Response.Headers.XContentTypeOptions="nosniff";Response.Headers["Cross-Origin-Resource-Policy"]="same-origin";
+ return File(image.ImageData,image.ContentType,lastModified:null,entityTag:new Microsoft.Net.Http.Headers.EntityTagHeaderValue("\""+Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(image.ImageData))+"\""));
+ }
+ [HttpPost,ValidateAntiForgeryToken,RequestSizeLimit(11_000_000)]
+ public async Task UploadReference(int projectId,IFormFile? referenceImage,[FromServices]MapReferenceImageService images)
+ {
+ if(!await access.CanAccessProjectAsync(projectId))return NotFound();if(referenceImage is null)return BadRequest(new{message="Choose a reference image."});
+ try{return Json(await images.UploadAsync(projectId,UserID,referenceImage));}
+ catch(InvalidDataException ex){return BadRequest(new{message=ex.Message});}
+ catch(SqlException ex) when(ex.Number==51000){return Conflict(new{message=ex.Message});}
+ }
+ [HttpPost,ValidateAntiForgeryToken]
+ public async Task DeleteUnusedReference(int projectId,Guid imageId)
+ {
+ if(!await access.CanAccessProjectAsync(projectId))return NotFound();
+ try{await maps.DeleteImageAsync(projectId,UserID,imageId);return Json(new{ok=true});}
+ catch(SqlException ex) when(ex.Number==51000){return Conflict(new{message=ex.Message});}
+ }
+
}
diff --git a/PlotLine/Data/MapRepository.cs b/PlotLine/Data/MapRepository.cs
index 367c3668..1ea3921f 100644
--- a/PlotLine/Data/MapRepository.cs
+++ b/PlotLine/Data/MapRepository.cs
@@ -27,10 +27,42 @@ public sealed class MapRepository(ISqlConnectionFactory connections)
}
public async Task SaveAsync(MapDocument document, int userId)
{
+ document.Map.AppearanceJson=JsonSerializer.Serialize(MapAppearanceJson.Read(document.Map.AppearanceJson),new JsonSerializerOptions(JsonSerializerDefaults.Web));
+ document.Map.ReferenceJson=JsonSerializer.Serialize(MapAppearanceJson.Read(document.Map.ReferenceJson),new JsonSerializerOptions(JsonSerializerDefaults.Web));
using var db = connections.CreateConnection();
- await db.ExecuteAsync("dbo.StoryMap_Save", new { document.Map.ProjectID, document.Map.MapID, UserID = userId, document.Map.Revision, document.Map.Name, document.Map.Kind,
+ await db.ExecuteAsync("dbo.StoryMap_Save", new { document.Map.ProjectID, document.Map.MapID, UserID = userId, document.Map.Revision, document.Map.Name, document.Map.Kind, document.Map.AppearanceJson, document.Map.ReferenceJson,
Features = JsonSerializer.Serialize(document.Features), Relationships = JsonSerializer.Serialize(document.Relationships) }, commandType: CommandType.StoredProcedure);
}
+ public async Task> ListImagesAsync(int projectId,int userId)
+ {
+ using var db=connections.CreateConnection();
+ return (await db.QueryAsync("dbo.MapReferenceImage_List",new {ProjectID=projectId,UserID=userId},commandType:CommandType.StoredProcedure)).ToList();
+ }
+ public async Task GetImageAsync(int projectId,int userId,Guid imageId)
+ {
+ using var db=connections.CreateConnection();
+ return await db.QuerySingleOrDefaultAsync("dbo.MapReferenceImage_Get",new {ProjectID=projectId,UserID=userId,ImageID=imageId},commandType:CommandType.StoredProcedure);
+ }
+ public async Task FindImageAsync(int projectId,int userId,byte[] hash)
+ {
+ using var db=connections.CreateConnection();
+ return await db.QuerySingleOrDefaultAsync("dbo.MapReferenceImage_Find",new {ProjectID=projectId,UserID=userId,ContentHash=hash},commandType:CommandType.StoredProcedure);
+ }
+ public async Task ImageStorageOwnerAsync(int projectId,int userId)
+ {
+ using var db=connections.CreateConnection();
+ return await db.QuerySingleAsync("dbo.MapReferenceImage_Owner",new {ProjectID=projectId,UserID=userId},commandType:CommandType.StoredProcedure);
+ }
+ public async Task AddImageAsync(int projectId,int userId,MapReferenceImage image)
+ {
+ using var db=connections.CreateConnection();
+ return await db.QuerySingleAsync("dbo.MapReferenceImage_Create",new {ProjectID=projectId,UserID=userId,image.ImageID,image.OriginalFileName,image.Width,image.Height,image.ImageData},commandType:CommandType.StoredProcedure);
+ }
+ public async Task DeleteImageAsync(int projectId,int userId,Guid imageId)
+ {
+ using var db=connections.CreateConnection();
+ await db.ExecuteAsync("dbo.MapReferenceImage_DeleteUnused",new {ProjectID=projectId,UserID=userId,ImageID=imageId},commandType:CommandType.StoredProcedure);
+ }
public async Task DeleteAsync(int projectId, int mapId, int revision, int userId)
{
using var db = connections.CreateConnection();
diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs
index 9c3dcd9b..68d70008 100644
--- a/PlotLine/Data/ProjectBackupRepository.cs
+++ b/PlotLine/Data/ProjectBackupRepository.cs
@@ -86,6 +86,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
data.MapFeatures = (await mapRows.ReadAsync()).ToList();
data.MapRelationships = (await mapRows.ReadAsync()).ToList();
data.MapJourneyNotes = (await mapRows.ReadAsync()).ToList();
+ data.MapReferenceImages = (await mapRows.ReadAsync()).ToList();
}
var bookMetadata = (await connection.QueryAsync(
@@ -151,6 +152,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
nameof(data.LocationRelationships),
nameof(data.MapJourneyNotes),
nameof(data.StoryMaps),
+ nameof(data.MapReferenceImages),
nameof(data.MapFeatures),
nameof(data.MapRelationships),
nameof(data.FloorPlans),
diff --git a/PlotLine/Models/MapAppearanceModels.cs b/PlotLine/Models/MapAppearanceModels.cs
new file mode 100644
index 00000000..d556f9af
--- /dev/null
+++ b/PlotLine/Models/MapAppearanceModels.cs
@@ -0,0 +1,39 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+namespace PlotLine.Models;
+
+public sealed class MapCanvasAppearance
+{
+ public string Preset { get; set; } = "light";
+ public string BackgroundColor { get; set; } = "#c9dfdf";
+ public string LandColor { get; set; } = "#e9e4c5";
+}
+public sealed class MapReferencePlacement
+{
+ public Guid? ImageID { get; set; }
+ public double X { get; set; }
+ public double Y { get; set; }
+ public double Width { get; set; } = 800;
+ public double Height { get; set; } = 600;
+ public double Rotation { get; set; }
+ public double Opacity { get; set; } = .35;
+ public bool IsVisible { get; set; } = true;
+ public bool IsLocked { get; set; } = true;
+}
+public sealed class MapReferenceImage
+{
+ public Guid ImageID { get; set; }
+ public int ProjectID { get; set; }
+ public string OriginalFileName { get; set; } = "Reference image";
+ public string ContentType { get; set; } = "image/webp";
+ public int Width { get; set; }
+ public int Height { get; set; }
+ public long FileSizeBytes { get; set; }
+ public int UseCount { get; set; }
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public byte[]? ImageData { get; set; }
+}
+public static class MapAppearanceJson
+{
+ private static readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true };
+ public static T Read(string value) where T : new() => JsonSerializer.Deserialize(value, Options) ?? new T();
+}
diff --git a/PlotLine/Models/MapModels.cs b/PlotLine/Models/MapModels.cs
index 32b97ac7..1e7295d9 100644
--- a/PlotLine/Models/MapModels.cs
+++ b/PlotLine/Models/MapModels.cs
@@ -10,6 +10,8 @@ public sealed class StoryMap
[Required, StringLength(200)] public string Name { get; set; } = "New map";
[Required, StringLength(40)] public string Kind { get; set; } = "Region";
public int Revision { get; set; }
+ public string AppearanceJson { get; set; } = "{}";
+ public string ReferenceJson { get; set; } = "{}";
}
public sealed class MapFeature
{
@@ -64,5 +66,6 @@ public sealed class MapsViewModel
public IReadOnlyList Maps { get; set; } = [];
public IReadOnlyList Locations { get; set; } = [];
public IReadOnlyList FloorPlans { get; set; } = [];
+ public IReadOnlyList ReferenceImages { get; set; } = [];
public MapDocument? Document { get; set; }
}
diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs
index 5afb39ba..221a5205 100644
--- a/PlotLine/Models/ProjectBackupModels.cs
+++ b/PlotLine/Models/ProjectBackupModels.cs
@@ -13,6 +13,7 @@ public sealed class ProjectBackupExport
public sealed class ProjectBackupData
{
+ public IReadOnlyList MapReferenceImages { get; set; } = [];
public IReadOnlyList MapJourneyNotes { get; set; } = [];
public IReadOnlyList StoryMaps { get; set; } = [];
public IReadOnlyList MapFeatures { get; set; } = [];
diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs
index 5c9de12e..3282100e 100644
--- a/PlotLine/Program.cs
+++ b/PlotLine/Program.cs
@@ -142,6 +142,7 @@ public class Program
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+ builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
diff --git a/PlotLine/Services/FloorPlanBackgroundImageService.cs b/PlotLine/Services/FloorPlanBackgroundImageService.cs
index 0f172cd8..cfea2377 100644
--- a/PlotLine/Services/FloorPlanBackgroundImageService.cs
+++ b/PlotLine/Services/FloorPlanBackgroundImageService.cs
@@ -56,11 +56,7 @@ public sealed class FloorPlanBackgroundImageService(
try
{
- using var codec = SKCodec.Create(new MemoryStream(bytes)) ?? throw new InvalidDataException();
- if (codec.EncodedFormat is not (SKEncodedImageFormat.Jpeg or SKEncodedImageFormat.Png or SKEncodedImageFormat.Webp))
- {
- return new(false, ErrorMessage: "Background image must be a valid PNG, JPG, JPEG or WebP file.");
- }
+ RasterImageValidation.Inspect(bytes);
}
catch (Exception ex) when (ex is InvalidDataException or ArgumentException)
{
diff --git a/PlotLine/Services/HardDeleteFileCleanupService.cs b/PlotLine/Services/HardDeleteFileCleanupService.cs
index b506b3a4..1d4feb46 100644
--- a/PlotLine/Services/HardDeleteFileCleanupService.cs
+++ b/PlotLine/Services/HardDeleteFileCleanupService.cs
@@ -20,6 +20,8 @@ public sealed class HardDeleteFileCleanupService(
foreach (var storagePath in storagePaths)
{
+ // These registered assets live in the database and cascade with their project.
+ if(storagePath.StartsWith("db:map-reference/",StringComparison.Ordinal))continue;
var absolutePath = uploadStorage.TryResolvePublicPath(storagePath);
if (absolutePath is null)
{
diff --git a/PlotLine/Services/MapReferenceImageService.cs b/PlotLine/Services/MapReferenceImageService.cs
new file mode 100644
index 00000000..892a01e0
--- /dev/null
+++ b/PlotLine/Services/MapReferenceImageService.cs
@@ -0,0 +1,53 @@
+using System.Security.Cryptography;
+using PlotLine.Data;
+using PlotLine.Models;
+using SkiaSharp;
+namespace PlotLine.Services;
+
+// Shared encoded-format inspection; Floor Plans keeps its existing file/persistence workflow.
+public static class RasterImageValidation
+{
+ public static SKImageInfo Inspect(byte[] bytes, long maxPixels = long.MaxValue)
+ {
+ using var codec=SKCodec.Create(new MemoryStream(bytes));
+ if(codec is null||codec.EncodedFormat is not (SKEncodedImageFormat.Png or SKEncodedImageFormat.Jpeg or SKEncodedImageFormat.Webp)||codec.Info.Width<1||codec.Info.Height<1||(long)codec.Info.Width*codec.Info.Height>maxPixels)throw new InvalidDataException("Choose a valid PNG, JPEG or WebP image within the image size limit.");
+ return codec.Info;
+ }
+}
+public sealed class MapReferenceImageService(MapRepository maps,ISubscriptionService subscriptions)
+{
+ public const long MaxUploadBytes=10L*1024*1024;
+ public const int MaxStoredBytes=8*1024*1024;
+ public const long MaxPixels=16_777_216;
+ public static MapReferenceImage Normalize(byte[] bytes,string fileName)
+ {
+ if(bytes.LongLength is 0 or >MaxUploadBytes||!new[]{".png",".jpg",".jpeg",".webp"}.Contains(Path.GetExtension(fileName).ToLowerInvariant()))throw new InvalidDataException("Choose a PNG, JPEG or WebP image, 10 MB or smaller.");
+ var info=RasterImageValidation.Inspect(bytes,MaxPixels);
+ using var codec=SKCodec.Create(new MemoryStream(bytes))??throw new InvalidDataException("Invalid image.");
+ using var decoded=new SKBitmap(info.Width,info.Height,SKColorType.Bgra8888,SKAlphaType.Premul);
+ if(codec.GetPixels(decoded.Info,decoded.GetPixels())!=SKCodecResult.Success)throw new InvalidDataException("The image could not be completely decoded. Choose another image.");
+ var ratio=Math.Min(1,4096d/Math.Max(info.Width,info.Height));
+ using var scaled=decoded.Resize(new SKImageInfo(Math.Max(1,(int)Math.Round(info.Width*ratio)),Math.Max(1,(int)Math.Round(info.Height*ratio))),new SKSamplingOptions(SKFilterMode.Linear,SKMipmapMode.Linear))??throw new InvalidDataException("Image could not be resized.");
+ using var image=SKImage.FromBitmap(scaled);using var encoded=image.Encode(SKEncodedImageFormat.Webp,90);
+ if(encoded is null||encoded.Size>MaxStoredBytes)throw new InvalidDataException("The processed image is too large. Try a smaller reference image.");
+ var name=Path.GetFileName(fileName.Replace('\\','/'));if(name.Length>200)name=name[..200];
+ return new(){ImageID=Guid.NewGuid(),OriginalFileName=name,Width=scaled.Width,Height=scaled.Height,ImageData=encoded.ToArray(),FileSizeBytes=encoded.Size};
+ }
+ public async Task UploadAsync(int projectId,int userId,IFormFile upload)
+ {
+ if(upload.Length is <=0 or >MaxUploadBytes)throw new InvalidDataException("Choose an image, 10 MB or smaller.");
+ await using var source=upload.OpenReadStream();using var buffer=new MemoryStream();var chunk=new byte[81920];int read;
+ while((read=await source.ReadAsync(chunk))>0){if(buffer.Length+read>MaxUploadBytes)throw new InvalidDataException("Reference images must be 10 MB or smaller.");await buffer.WriteAsync(chunk.AsMemory(0,read));}
+ var image=Normalize(buffer.ToArray(),upload.FileName);
+ var existing=await maps.FindImageAsync(projectId,userId,SHA256.HashData(image.ImageData!));if(existing is not null)return existing;
+ var owner=await maps.ImageStorageOwnerAsync(projectId,userId);var quota=await subscriptions.CanUploadFileAsync(owner,image.FileSizeBytes);
+ if(!quota.Allowed)throw new InvalidDataException("This project's storage allowance would be exceeded. Remove unused references or review the project owner's subscription.");
+ return await maps.AddImageAsync(projectId,userId,image);
+ }
+ public static bool ValidBackupImage(MapReferenceImage image)
+ {
+ if(image.ImageID==Guid.Empty||image.ImageData is not {Length:>0 and <=MaxStoredBytes}||image.ContentType!="image/webp"||string.IsNullOrWhiteSpace(image.OriginalFileName)||image.OriginalFileName.Length>200)return false;
+ try{var info=RasterImageValidation.Inspect(image.ImageData,MaxPixels);using var codec=SKCodec.Create(new MemoryStream(image.ImageData));if(codec is null||codec.EncodedFormat!=SKEncodedImageFormat.Webp||info.Width!=image.Width||info.Height!=image.Height||info.Width>4096||info.Height>4096)return false;using var bitmap=new SKBitmap(info.Width,info.Height,SKColorType.Bgra8888,SKAlphaType.Premul);return codec.GetPixels(bitmap.Info,bitmap.GetPixels())==SKCodecResult.Success;}
+ catch(Exception e) when(e is InvalidDataException or ArgumentException){return false;}
+ }
+}
diff --git a/PlotLine/Services/MapValidation.cs b/PlotLine/Services/MapValidation.cs
index fe0e05ed..0c0cfd1a 100644
--- a/PlotLine/Services/MapValidation.cs
+++ b/PlotLine/Services/MapValidation.cs
@@ -10,6 +10,16 @@ public static class MapValidation
public static string? Validate(MapDocument d)
{
if (string.IsNullOrWhiteSpace(d.Map.Name) || d.Map.Name.Length > 200 || !Kinds.Contains(d.Map.Kind)) return "Choose a map name and kind.";
+ try
+ {
+ if(string.IsNullOrEmpty(d.Map.AppearanceJson)||string.IsNullOrEmpty(d.Map.ReferenceJson))return "Choose valid map appearance settings.";
+ if(d.Map.AppearanceJson.Length>1000||d.Map.ReferenceJson.Length>2000)return "Map appearance settings are too detailed.";
+ var appearance=MapAppearanceJson.Read(d.Map.AppearanceJson);
+ if(!new[]{"light","paper","dark","custom"}.Contains(appearance.Preset)||!System.Text.RegularExpressions.Regex.IsMatch(appearance.BackgroundColor??"","^#[0-9a-fA-F]{6}$")||!System.Text.RegularExpressions.Regex.IsMatch(appearance.LandColor??"","^#[0-9a-fA-F]{6}$"))return "Choose a map appearance and valid colours.";
+ var reference=MapAppearanceJson.Read(d.Map.ReferenceJson);
+ if(reference.ImageID==Guid.Empty||new[]{reference.X,reference.Y,reference.Width,reference.Height,reference.Rotation,reference.Opacity}.Any(v=>!double.IsFinite(v)||Math.Abs(v)>100000)||reference.Width<.001||reference.Height<.001||reference.Opacity<0||reference.Opacity>1)return "Check reference image position, size and opacity.";
+ }
+ catch(JsonException){return "Invalid map appearance or reference settings.";}
if (d.Features.Count > 3000 || d.Relationships.Count > 10000) return "This map has too many items. Consider a detailed child map.";
var ids = d.Features.Select(x => x.FeatureID).ToHashSet();
if (ids.Contains(Guid.Empty) || ids.Count != d.Features.Count) return "Feature identifiers must be unique.";
diff --git a/PlotLine/Services/ProjectRestoreService.cs b/PlotLine/Services/ProjectRestoreService.cs
index 501c557a..dc8d4dd6 100644
--- a/PlotLine/Services/ProjectRestoreService.cs
+++ b/PlotLine/Services/ProjectRestoreService.cs
@@ -102,7 +102,7 @@ public sealed class ProjectRestoreService(
return "Restore point format is not recognised. No project data was changed.";
}
- if (!string.Equals(backup.FormatVersion, "1.0", StringComparison.Ordinal))
+ if (backup.FormatVersion is not ("1.0" or "1.1"))
{
return "Restore point format version is not supported. No project data was changed.";
}
@@ -112,6 +112,9 @@ public sealed class ProjectRestoreService(
return "This restore point does not belong to the selected project. No project data was changed.";
}
+ if(backup.Data is null||backup.Data.StoryMaps is null||backup.Data.MapReferenceImages is null)return "Restore point data is invalid.";
+ foreach(var map in backup.Data.StoryMaps){if(map is null||map.ProjectID!=projectId||MapValidation.Validate(new(){Map=map}) is not null)return "Restore point contains invalid map appearance or placement settings.";map.AppearanceJson=JsonSerializer.Serialize(MapAppearanceJson.Read(map.AppearanceJson),new JsonSerializerOptions(JsonSerializerDefaults.Web));map.ReferenceJson=JsonSerializer.Serialize(MapAppearanceJson.Read(map.ReferenceJson),new JsonSerializerOptions(JsonSerializerDefaults.Web));}
+ if(backup.Data.MapReferenceImages.Any(image=>image is null||image.ProjectID!=projectId||!MapReferenceImageService.ValidBackupImage(image)))return "Restore point contains invalid reference images. No project data was changed.";
return null;
}
diff --git a/PlotLine/Sql/212_MapAppearanceReferences.sql b/PlotLine/Sql/212_MapAppearanceReferences.sql
new file mode 100644
index 00000000..acf18af9
--- /dev/null
+++ b/PlotLine/Sql/212_MapAppearanceReferences.sql
@@ -0,0 +1,422 @@
+SET ANSI_NULLS ON;
+SET QUOTED_IDENTIFIER ON;
+GO
+IF COL_LENGTH('dbo.StoryMaps','AppearanceJson') IS NULL ALTER TABLE dbo.StoryMaps ADD AppearanceJson nvarchar(1000) NOT NULL CONSTRAINT DF_StoryMaps_Appearance DEFAULT N'{}';
+IF COL_LENGTH('dbo.StoryMaps','ReferenceJson') IS NULL ALTER TABLE dbo.StoryMaps ADD ReferenceJson nvarchar(2000) NOT NULL CONSTRAINT DF_StoryMaps_Reference DEFAULT N'{}';
+GO
+IF OBJECT_ID('dbo.MapReferenceImages','U') IS NULL
+BEGIN
+ CREATE TABLE dbo.MapReferenceImages(ImageID uniqueidentifier NOT NULL PRIMARY KEY,ProjectID int NOT NULL REFERENCES dbo.Projects(ProjectID) ON DELETE CASCADE,
+ OriginalFileName nvarchar(200) NOT NULL,ContentType nvarchar(40) NOT NULL CONSTRAINT DF_MapImage_Type DEFAULT N'image/webp',Width int NOT NULL,Height int NOT NULL,ImageData varbinary(max) NOT NULL,
+ FileSizeBytes AS CONVERT(bigint,DATALENGTH(ImageData)) PERSISTED,ContentHash AS CONVERT(binary(32),HASHBYTES('SHA2_256',ImageData)) PERSISTED,
+ CONSTRAINT CK_MapImage_Size CHECK(DATALENGTH(ImageData) BETWEEN 1 AND 8388608 AND Width BETWEEN 1 AND 4096 AND Height BETWEEN 1 AND 4096 AND ContentType=N'image/webp'));
+ CREATE UNIQUE INDEX UX_MapReferenceImages_Content ON dbo.MapReferenceImages(ProjectID,ContentHash);
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.MapReferenceImage_Owner @ProjectID int,@UserID int
+AS
+BEGIN
+ SET NOCOUNT ON;EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1 ORDER BY ProjectUserAccessID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.MapReferenceImage_List @ProjectID int,@UserID int
+AS
+BEGIN
+ SET NOCOUNT ON;EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT i.ImageID,i.ProjectID,i.OriginalFileName,i.ContentType,i.Width,i.Height,i.FileSizeBytes,
+ (SELECT COUNT(*) FROM dbo.StoryMaps m WHERE m.ProjectID=@ProjectID AND TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.ReferenceJson,'$.imageID'))=i.ImageID) UseCount
+ FROM dbo.MapReferenceImages i WHERE i.ProjectID=@ProjectID ORDER BY i.OriginalFileName,i.ImageID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.MapReferenceImage_Get @ProjectID int,@UserID int,@ImageID uniqueidentifier
+AS
+BEGIN
+ SET NOCOUNT ON;EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,FileSizeBytes,ImageData FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID AND ImageID=@ImageID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.MapReferenceImage_Find @ProjectID int,@UserID int,@ContentHash binary(32)
+AS
+BEGIN
+ SET NOCOUNT ON;EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,FileSizeBytes FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID AND ContentHash=@ContentHash;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.MapReferenceImage_Create @ProjectID int,@UserID int,@ImageID uniqueidentifier,@OriginalFileName nvarchar(200),@Width int,@Height int,@ImageData varbinary(max)
+AS
+BEGIN
+ SET NOCOUNT ON;SET XACT_ABORT ON;BEGIN TRAN;
+ EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ DECLARE @lock int;SELECT @lock=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID;
+ DECLARE @hash binary(32)=HASHBYTES('SHA2_256',@ImageData),@existing uniqueidentifier;
+ SELECT @existing=ImageID FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID AND ContentHash=@hash;
+ IF @existing IS NOT NULL SET @ImageID=@existing;
+ ELSE
+ BEGIN
+ INSERT dbo.MapReferenceImages(ImageID,ProjectID,OriginalFileName,Width,Height,ImageData) VALUES(@ImageID,@ProjectID,@OriginalFileName,@Width,@Height,@ImageData);
+ DECLARE @owner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1 ORDER BY ProjectUserAccessID);
+ DECLARE @path nvarchar(1000)=N'db:map-reference/'+CONVERT(nvarchar(20),@ProjectID)+N'/'+CONVERT(nvarchar(36),@ImageID),@file nvarchar(300)=CONVERT(nvarchar(36),@ImageID)+N'.webp';
+ INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath)
+ VALUES(@owner,@ProjectID,N'MapReferenceImage',@ProjectID,@file,@OriginalFileName,N'image/webp',DATALENGTH(@ImageData),@path);
+ END;
+ COMMIT;
+ SELECT ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,FileSizeBytes FROM dbo.MapReferenceImages WHERE ImageID=@ImageID AND ProjectID=@ProjectID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.MapReferenceImage_DeleteUnused @ProjectID int,@UserID int,@ImageID uniqueidentifier
+AS
+BEGIN
+ SET NOCOUNT ON;SET XACT_ABORT ON;BEGIN TRAN;EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ DECLARE @lock int;SELECT @lock=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID;
+ IF NOT EXISTS(SELECT 1 FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID AND ImageID=@ImageID) THROW 51000,'Reference image unavailable.',1;
+ IF EXISTS(SELECT 1 FROM dbo.StoryMaps WHERE ProjectID=@ProjectID AND TRY_CONVERT(uniqueidentifier,JSON_VALUE(ReferenceJson,'$.imageID'))=@ImageID) THROW 51000,'This reference image is used by a saved map. Remove it from those maps and save first.',1;
+ DELETE dbo.MapReferenceImages WHERE ProjectID=@ProjectID AND ImageID=@ImageID;
+ UPDATE dbo.UserFile SET IsDeleted=1,DeletedDateUTC=SYSUTCDATETIME() WHERE ProjectID=@ProjectID AND EntityType=N'MapReferenceImage' AND StoragePath=N'db:map-reference/'+CONVERT(nvarchar(20),@ProjectID)+N'/'+CONVERT(nvarchar(36),@ImageID);
+ COMMIT;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.StoryMap_List @ProjectID int, @UserID int
+AS
+BEGIN
+ SET NOCOUNT ON;
+ EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision,AppearanceJson,ReferenceJson FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY Name,MapID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.StoryMap_Get @ProjectID int, @MapID int, @UserID int
+AS
+BEGIN
+ SET NOCOUNT ON;
+ EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision,AppearanceJson,ReferenceJson FROM dbo.StoryMaps WHERE MapID=@MapID AND ProjectID=@ProjectID;
+ SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.MapID=@MapID AND m.ProjectID=@ProjectID ORDER BY f.ZOrder,f.FeatureID;
+ SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.MapID=@MapID AND m.ProjectID=@ProjectID ORDER BY r.RelationshipID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.StoryMap_Save @ProjectID int,@MapID int,@UserID int,@Revision int,@Name nvarchar(200),@Kind nvarchar(40),@Features nvarchar(max),@Relationships nvarchar(max),@AppearanceJson nvarchar(1000)=N'{}',@ReferenceJson nvarchar(2000)=N'{}'
+AS
+BEGIN
+ SET NOCOUNT ON; SET XACT_ABORT ON;
+ BEGIN TRAN;
+ EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ DECLARE @lock int;SELECT @lock=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID;
+ IF ISJSON(@AppearanceJson)<>1 OR ISJSON(@ReferenceJson)<>1 THROW 51000,'Invalid map appearance settings.',1;
+ DECLARE @image uniqueidentifier=TRY_CONVERT(uniqueidentifier,JSON_VALUE(@ReferenceJson,'$.imageID'));
+ IF JSON_VALUE(@ReferenceJson,'$.imageID') IS NOT NULL AND (@image IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.MapReferenceImages WHERE ImageID=@image AND ProjectID=@ProjectID)) THROW 51000,'Choose a reference image in this project. Your edits remain here.',1;
+ IF NOT EXISTS(SELECT 1 FROM dbo.StoryMaps WITH(UPDLOCK,HOLDLOCK) WHERE MapID=@MapID AND ProjectID=@ProjectID AND Revision=@Revision) THROW 51000,'Map changed in another window. Reload before saving; your edits are still here.',1;
+ SELECT * INTO #f FROM OPENJSON(@Features) WITH (
+[FeatureID] uniqueidentifier '$.FeatureID',
+[Name] nvarchar(200) '$.Name',
+[Type] nvarchar(60) '$.Type',
+[GeometryClass] nvarchar(12) '$.GeometryClass',
+[Layer] nvarchar(30) '$.Layer',
+[X] float '$.X',
+[Y] float '$.Y',
+[Width] float '$.Width',
+[Height] float '$.Height',
+[Rotation] float '$.Rotation',
+[ZOrder] int '$.ZOrder',
+[IsPlaced] bit '$.IsPlaced',
+[IsProvisional] bit '$.IsProvisional',
+[IsLocked] bit '$.IsLocked',
+[ShowLabel] bit '$.ShowLabel',
+[LabelX] float '$.LabelX',
+[LabelY] float '$.LabelY',
+[LocationID] int '$.LocationID',
+[FloorPlanID] int '$.FloorPlanID',
+[StartFeatureID] uniqueidentifier '$.StartFeatureID',
+[EndFeatureID] uniqueidentifier '$.EndFeatureID',
+[GeometryJson] nvarchar(max) '$.GeometryJson',
+[Notes] nvarchar(4000) '$.Notes',CreateLocation bit '$.CreateLocation');
+ IF EXISTS(SELECT 1 FROM #f f WHERE LocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations l WHERE l.LocationID=f.LocationID AND l.ProjectID=@ProjectID)) THROW 51000,'Choose Locations in this project.',1;
+ IF EXISTS(SELECT 1 FROM #f f WHERE FloorPlanID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.FloorPlans l WHERE l.FloorPlanID=f.FloorPlanID AND l.ProjectID=@ProjectID)) THROW 51000,'Choose Floor Plans in this project.',1;
+ IF EXISTS(SELECT 1 FROM #f f WHERE (StartFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f x WHERE x.FeatureID=f.StartFeatureID AND x.GeometryClass='Marker')) OR (EndFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f x WHERE x.FeatureID=f.EndFeatureID AND x.GeometryClass='Marker'))) THROW 51000,'Route endpoints must be places on this map.',1;
+ -- Create only on explicit request, atomically with the map revision. Retry cannot duplicate a Location.
+ DECLARE @fid uniqueidentifier,@label nvarchar(200),@lid int;
+ DECLARE @created table(ID int);
+ DECLARE places CURSOR LOCAL FAST_FORWARD FOR SELECT FeatureID,Name FROM #f WHERE CreateLocation=1 AND LocationID IS NULL;
+ OPEN places; FETCH NEXT FROM places INTO @fid,@label;
+ WHILE @@FETCH_STATUS=0
+ BEGIN
+ DELETE FROM @created;
+ INSERT @created EXEC dbo.Location_Save @ProjectID=@ProjectID,@LocationName=@label;
+ SELECT @lid=ID FROM @created;
+ UPDATE #f SET LocationID=@lid WHERE FeatureID=@fid;
+ FETCH NEXT FROM places INTO @fid,@label;
+ END;
+ CLOSE places; DEALLOCATE places;
+ DELETE dbo.MapRelationships WHERE MapID=@MapID;
+ -- Detach links to removed parent features, preserving the detailed maps themselves.
+ UPDATE dbo.StoryMaps SET ParentFeatureID=NULL,Revision=Revision+1 WHERE ParentMapID=@MapID AND ParentFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM #f WHERE FeatureID=ParentFeatureID);
+ DELETE dbo.MapFeatures WHERE MapID=@MapID;
+ INSERT dbo.MapFeatures(MapID,[FeatureID],[Name],[Type],[GeometryClass],[Layer],[X],[Y],[Width],[Height],[Rotation],[ZOrder],[IsPlaced],[IsProvisional],[IsLocked],[ShowLabel],[LabelX],[LabelY],[LocationID],[FloorPlanID],[StartFeatureID],[EndFeatureID],[GeometryJson],[Notes]) SELECT @MapID,[FeatureID],[Name],[Type],[GeometryClass],[Layer],[X],[Y],[Width],[Height],[Rotation],[ZOrder],[IsPlaced],[IsProvisional],[IsLocked],[ShowLabel],[LabelX],[LabelY],[LocationID],[FloorPlanID],[StartFeatureID],[EndFeatureID],[GeometryJson],[Notes] FROM #f;
+ INSERT dbo.MapRelationships(MapID,[RelationshipID],[SourceID],[TargetID],[Direction],[RelativeDistance],[MeasuredDistance],[Unit],[TypicalTravelTime],[Notes]) SELECT @MapID,[RelationshipID],[SourceID],[TargetID],[Direction],[RelativeDistance],[MeasuredDistance],[Unit],[TypicalTravelTime],[Notes] FROM OPENJSON(@Relationships) WITH ([RelationshipID] uniqueidentifier '$.RelationshipID',[SourceID] uniqueidentifier '$.SourceID',[TargetID] uniqueidentifier '$.TargetID',[Direction] nvarchar(2) '$.Direction',[RelativeDistance] nvarchar(12) '$.RelativeDistance',[MeasuredDistance] decimal(18,3) '$.MeasuredDistance',[Unit] nvarchar(30) '$.Unit',[TypicalTravelTime] nvarchar(120) '$.TypicalTravelTime',[Notes] nvarchar(1000) '$.Notes');
+ UPDATE dbo.StoryMaps SET Name=@Name,Kind=@Kind,AppearanceJson=@AppearanceJson,ReferenceJson=@ReferenceJson,Revision=Revision+1,ModifiedDate=SYSUTCDATETIME() WHERE MapID=@MapID;
+ UPDATE dbo.MapJourneyNotes SET RouteFeatureID=NULL WHERE MapID=@MapID AND RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=@MapID AND f.FeatureID=RouteFeatureID);
+ COMMIT;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.StoryMap_Backup @ProjectID int,@UserID int=NULL
+AS
+BEGIN
+ SET NOCOUNT ON;
+ -- Same internal/null-user convention as ProjectBackup_Export; public export checks ownership first.
+ IF @UserID IS NOT NULL EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
+ SELECT MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision,AppearanceJson,ReferenceJson FROM dbo.StoryMaps WHERE ProjectID=@ProjectID ORDER BY MapID;
+ SELECT f.* FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID ORDER BY f.MapID,f.FeatureID;
+ SELECT r.* FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID ORDER BY r.MapID,r.RelationshipID;
+ SELECT n.* FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID;
+ SELECT ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,FileSizeBytes,ImageData FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID ORDER BY ImageID;
+END;
+GO
+CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson
+ @ProjectID int,
+ @SourceRestorePointID int = NULL,
+ @SafetyRestorePointID int = NULL,
+ @JsonData nvarchar(max)
+AS
+BEGIN
+ SET NOCOUNT ON;
+ SET XACT_ABORT ON;
+
+ IF ISJSON(@JsonData) <> 1
+ THROW 51001, 'Restore JSON is invalid.', 1;
+
+ IF JSON_VALUE(@JsonData, '$.Format') <> N'PlotDirector.ProjectBackup'
+ THROW 51002, 'Restore JSON format is not recognised.', 1;
+
+ IF JSON_VALUE(@JsonData, '$.FormatVersion') NOT IN (N'1.0', N'1.1')
+ THROW 51003, 'Restore JSON format version is not supported.', 1;
+
+ IF TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')) <> @ProjectID
+ THROW 51004, 'Restore point does not belong to this project.', 1;
+
+ DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY);
+ INSERT INTO @RestoreTables (TableName)
+ VALUES
+ (N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'),
+ (N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'),
+ (N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'),
+ (N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'),
+ (N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'),
+ (N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'),
+ (N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'),
+ (N'MapReferenceImages'), (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), (N'MapJourneyNotes'),
+ (N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'),
+ (N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'),
+ (N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'),
+ (N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'),
+ (N'ScenarioWarnings');
+
+ BEGIN TRANSACTION;
+ DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0);
+
+
+ DECLARE @TableName sysname;
+ DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables;
+ OPEN DisableCursor;
+ FETCH NEXT FROM DisableCursor INTO @TableName;
+ WHILE @@FETCH_STATUS = 0
+ BEGIN
+ DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;';
+ EXEC (@DisableSql);
+ FETCH NEXT FROM DisableCursor INTO @TableName;
+ END
+ CLOSE DisableCursor;
+ DEALLOCATE DisableCursor;
+
+ DELETE n FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID;
+ DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID;
+ DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID;
+ DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID;
+ DELETE dbo.MapReferenceImages WHERE ProjectID=@ProjectID;
+ UPDATE dbo.UserFile SET IsDeleted=1,DeletedDateUTC=SYSUTCDATETIME() WHERE ProjectID=@ProjectID AND EntityType=N'MapReferenceImage';
+
+ DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID;
+ DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID;
+ DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID;
+ DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID;
+
+ DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID;
+ DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID;
+
+ DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+
+ DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo
+ INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID
+ INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID
+ INNER JOIN dbo.Books b ON b.BookID = c.BookID
+ WHERE b.ProjectID = @ProjectID;
+
+ DELETE sd FROM dbo.SceneDependencies sd
+ LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID
+ LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID
+ LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID
+ LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID
+ LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID
+ LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID
+ WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID;
+
+ DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID;
+ DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID;
+ DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID;
+ DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID;
+ DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID;
+
+ DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID;
+ DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID;
+ DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID;
+ DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID;
+ DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID;
+ DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID;
+
+ DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID;
+ DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID;
+ DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID;
+ DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID;
+
+ DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID;
+ DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID;
+
+ DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID;
+ DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID;
+ DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID;
+
+ DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID;
+ DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID;
+ DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID;
+
+ DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID;
+ DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID;
+ DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID;
+
+ DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
+ DELETE FROM dbo.Books WHERE ProjectID = @ProjectID;
+ DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID;
+
+ UPDATE p
+ SET ProjectName = src.ProjectName,
+ Description = src.Description,
+ CreatedDate = src.CreatedDate,
+ UpdatedDate = SYSUTCDATETIME(),
+ IsArchived = src.IsArchived,
+ ArchivedDate = src.ArchivedDate,
+ ArchivedReason = src.ArchivedReason
+ FROM dbo.Projects p
+ CROSS APPLY OPENJSON(@JsonData, '$.Project')
+ WITH
+ (
+ ProjectID int '$.ProjectID',
+ ProjectName nvarchar(200) '$.ProjectName',
+ Description nvarchar(max) '$.Description',
+ CreatedDate datetime2 '$.CreatedDate',
+ IsArchived bit '$.IsArchived',
+ ArchivedDate datetime2 '$.ArchivedDate',
+ ArchivedReason nvarchar(1000) '$.ArchivedReason'
+ ) src
+ WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID;
+
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0;
+
+ -- Older backups contain no Maps sets. The automatic safety restore point preserves current geography.
+ IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ProjectID int '$.ProjectID') WHERE ProjectID IS NULL OR ProjectID<>@ProjectID) THROW 51005,'Reference images cross project boundaries.',1;
+ INSERT dbo.MapReferenceImages(ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,ImageData)
+ SELECT x.ImageID,@ProjectID,x.OriginalFileName,x.ContentType,x.Width,x.Height,CAST(N'' AS xml).value('xs:base64Binary(sql:column("x.ImageData"))','varbinary(max)')
+ FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ImageID uniqueidentifier '$.ImageID',OriginalFileName nvarchar(200) '$.OriginalFileName',ContentType nvarchar(40) '$.ContentType',Width int '$.Width',Height int '$.Height',ImageData nvarchar(max) '$.ImageData') x;
+ DECLARE @ImageOwner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1 ORDER BY ProjectUserAccessID);
+ INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath)
+ SELECT @ImageOwner,@ProjectID,N'MapReferenceImage',@ProjectID,CONVERT(nvarchar(36),ImageID)+N'.webp',OriginalFileName,ContentType,FileSizeBytes,N'db:map-reference/'+CONVERT(nvarchar(20),@ProjectID)+N'/'+CONVERT(nvarchar(36),ImageID) FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1;
+ IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID))
+ OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID))
+ THROW 51005,'Map backup contains features outside this project.',1;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0;
+ IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID)
+ OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID)
+ THROW 51005,'Map hierarchy or Location links cross projects.',1;
+ IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapJourneyNotes') WITH(MapID int '$.MapID',CharacterID int '$.CharacterID',FromSceneID int '$.FromSceneID',ToSceneID int '$.ToSceneID',RouteFeatureID uniqueidentifier '$.RouteFeatureID') n
+ WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=n.MapID AND m.ProjectID=@ProjectID)
+ OR NOT EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID)
+ OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@ProjectID AND s.SceneID IN(n.FromSceneID,n.ToSceneID))<>2
+ OR (n.RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID AND f.GeometryClass='Path')))
+ THROW 51005,'Journey annotations cross project or map boundaries.',1;
+ EXEC dbo.ProjectRestore_InsertJsonTable N'MapJourneyNotes',N'$.Data.MapJourneyNotes',@JsonData,@ProjectID,0;
+ IF EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.ProjectID=@ProjectID AND (ISJSON(m.AppearanceJson)<>1 OR ISJSON(m.ReferenceJson)<>1 OR (JSON_VALUE(m.ReferenceJson,'$.imageID') IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapReferenceImages i WHERE i.ProjectID=@ProjectID AND i.ImageID=TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.ReferenceJson,'$.imageID')))))) THROW 51005,'Invalid map appearance or foreign reference image.',1;
+ UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID;
+
+ DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables;
+ OPEN EnableCursor;
+ FETCH NEXT FROM EnableCursor INTO @TableName;
+ WHILE @@FETCH_STATUS = 0
+ BEGIN
+ DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;';
+ EXEC (@EnableSql);
+ FETCH NEXT FROM EnableCursor INTO @TableName;
+ END
+ CLOSE EnableCursor;
+ DEALLOCATE EnableCursor;
+
+ IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL
+ BEGIN
+ INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes)
+ VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.');
+ END;
+
+ COMMIT TRANSACTION;
+END;
+GO
diff --git a/PlotLine/Views/Maps/Index.cshtml b/PlotLine/Views/Maps/Index.cshtml
index 47a68260..397a67e1 100644
--- a/PlotLine/Views/Maps/Index.cshtml
+++ b/PlotLine/Views/Maps/Index.cshtml
@@ -20,6 +20,7 @@
Map actions
+
@@ -51,12 +52,12 @@
Your story, in place
Start with a few places, or build a landscape a piece at a time.