Fix geographical lookup accounting, hierarchy submission and inspectable map preview

This commit is contained in:
Nick Beckley 2026-11-13 16:17:51 +00:00
parent efc28808f3
commit dad70a1e32
26 changed files with 519 additions and 56 deletions

View File

@ -4,9 +4,9 @@ Implementation and qualification record, 13 November 2026. This feature extends
## Author workflow and triggers
Creating a location **never submits a geographical request**, including creation with a parent. Existing-name and type edits invalidate affected coordinates but do not request new lookup. Moving an existing location beneath a recognised geographical root requests resolution for that branch. Editing an existing location's parent follows the same path. For an already arranged hierarchy, Location Details offers **Resolve this arranged hierarchy (up to 20 places)** as a deliberate request. There is no database-wide enrichment or periodic refresh. The 30-second worker only drains these finite persisted requests.
Creating an unparented location does not submit lookup. Saving an explicit parent assignment, including creating a child beneath a recognised root, establishes/changes a hierarchy and automatically requests eligible work for that branch. Name/type edits to an existing location also re-evaluate identifying context. Reparenting follows the same path. The Resolve button is recovery, not mandatory setup. Maps can explicitly request its unsubmitted linked locations. There is no database-wide enrichment or periodic provider refresh.
Admission is deliberately conservative: up to 20 locations per branch, one batch per author per hour and six batches per application per hour. Retry and explicit replacement use the same admission limit. Larger branches must be arranged/requested in smaller portions; multiple quick hierarchy edits may hit the hourly limit. Hierarchy edits still save when lookup admission is declined; the Locations tree explains the outcome. Confirmation does not spend a provider request or batch allowance.
Admission charges newly required uncached location work: up to 20 new eligible locations per submission, 20 per author in a rolling hour and 120 application-wide in that hour. This preserves the original maximum capacity of one 20-location author batch and six application batches while removing their per-click lockouts. Cached responses, confirmed/resolved locations, already-requested jobs and duplicates are not billed. Failed admissions roll back without charging. Multiple small parent-assignment actions can use the remaining allowance. Real HTTP requests have a separate persistent application counter and remain serialized, at least 15 seconds apart, and capped at 200/day. Bounded error retries and one optional context fallback consume that HTTP budget, not separate author hierarchy actions.
Location Details shows status, candidate name/administrative context/country/coordinates and source attribution. Selecting a candidate sends its index and the observed generation, never client-supplied coordinates. Confirmed matches persist until identifying context changes or the author explicitly chooses replacement/exclusion. Authors can exclude lookup and later re-enable it; re-enabling waits for a deliberate hierarchy request.
@ -55,6 +55,8 @@ The Locations trigger invalidates changed locations and descendants on name/type
Jobs persist across restarts. A single per-location row deduplicates work. A two-minute processing lease supports crash recovery; a 25-second HTTP timeout keeps normal calls within that lease. Provider reservations serialize all external requests across application processes, with a persistent next-request timestamp, daily budget and cross-author request-key lease. The designated-host check prevents external processing on a second machine. Persistent request-key caching prevents repeats, including empty results; no TTL refresh is scheduled. Provider/endpoint plus country/subdivision and the complete available ancestor context form the request hash. Different Newtown contexts cannot reuse coordinates based on name alone.
If a full hierarchy query returns no geographical match, the worker queues at most one country-scoped fallback. It uses a separate persistent cache key and passes through the same external reservation gate. Its generation-bound stage survives restart and resets automatically when identifying context changes. A relaxed-context result always requires author confirmation; geographical parentage need not match the provider's administrative boundaries.
Shared cache entries contain provider-returned public geographical candidates: provider/OSM identity, canonical display name, coordinates, country, administrative context, attribution and resolution time. They contain no project, account, private description, manuscript text or original hierarchy. Per-author confirmation remains on that author's Location record; an ambiguous choice by one author is not silently promoted into another author's confirmed match. Identical candidate sets may be reused, with confirmation still required.
Provider failures have four bounded attempts and 60/120/240/480-second backoff. Rate reservation failures defer work without consuming a provider failure. HTTP 403/429 also apply an application-wide cooldown, respecting Retry-After subject to safe bounds. No provider error body/query/credential is logged. Only bounded error-type operational events are logged. Stale completion checks both generation and lease; a confirmed coordinate cannot be overwritten by a worker.
@ -65,11 +67,11 @@ Provider failures have four bounded attempts and 60/120/240/480-second backoff.
This is a local projection, not a claim that every pairwise spherical distance is exactly preserved. Extents beyond 15 degrees from the centre (roughly 1,650 km) are refused to avoid a misleading global arrangement. Labels and markers may overlap in dense clusters; authors can adjust them afterwards.
The existing canvas renders a preview while the working document remains unchanged. The dialog identifies moves, skipped statuses/locks and attribution. Cancel/Escape preserve the complete document. Apply adds one existing Undo/Redo checkpoint; Save uses the established map revision/permission/persistence path. No objects are deleted/recreated. Manual canvas dragging cannot alter geographical coordinates. Repositioning is always explicit.
At least two distinct resolved, unlocked locations are required; a single marker is never centred and presented as a successful geographical arrangement. The actual proposed canvas is rendered inside a larger confirmation dialog, including unchanged surroundings, with north-up orientation, statuses and recovery links. The working document remains unchanged during preview. The dialog identifies moves, skipped statuses/locks and attribution. Cancel/Escape preserve the complete document. Apply adds one existing Undo/Redo checkpoint; Save uses the established map revision/permission/persistence path. No objects are deleted/recreated. Manual canvas dragging cannot alter geographical coordinates. Repositioning is always explicit.
## Database rollout
New tables/procedures are in 253, 254, 255 and 256. Apply **253, 255, 254, 256**, not a blind numeric replay. During Development qualification, 254 exposed that a new job-state label exceeded the original 24-character column; 255 is the forward-only width repair, preserving the applied scripts. 254 then completed successfully. 256 indexes the durable queue and batch-time lookup.
Original tables/procedures are in 253, 254, 255 and 256. Corrections 257 and 258 implement work-based accounting, detailed queue state and the bounded context fallback; apply them after 256. Apply **253, 255, 254, 256**, not a blind numeric replay. During Development qualification, 254 exposed that a new job-state label exceeded the original 24-character column; 255 is the forward-only width repair, preserving the applied scripts. 254 then completed successfully. 256 indexes the durable queue and batch-time lookup.
Development was verified as `PlotDirector_Development` before applying changes. A copy-only compressed CHECKSUM backup was successfully created and its nonempty container file verified at `/var/opt/mssql/backup/PlotDirector_Development_geography_20261113_142234.bak`. An additional RESTORE VERIFYONLY attempt was unavailable to the application principal (CREATE DATABASE permission); no restore was attempted. The backup is not a tested restore. Existing unrelated manuscript/Word work is preserved.

View File

@ -0,0 +1,76 @@
/* Explicit Development acceptance. Uses real forms, real cached Nominatim results and normal persistence.
Provision/clean up a dedicated identity with --dev-browser-identity. Never use a human account. */
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
const identityPath=process.argv[2];
if(!identityPath?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated Development identity required.');
const identity=JSON.parse(fs.readFileSync(identityPath,'utf8'));
if(identity.Database!=='PlotDirector_Development'||!identity.Email.startsWith('pwa-browser-'))throw Error('Wrong identity scope.');
const base='https://dev.plotdirector.com';
(async()=>{
const browser=await chromium.launch();
try{
const context=await browser.newContext({viewport:{width:1700,height:1100}}),page=await context.newPage(),errors=[];
page.on('pageerror',e=>errors.push(e.message));page.on('dialog',d=>d.accept());
await page.goto(base+'/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);
await Promise.all([page.waitForURL('**/Projects'),page.locator('form[action="/Account/Login"] button[type=submit]').click()]);
await page.goto(base+'/Projects/Create');await page.locator('#ProjectName').fill('Geography live acceptance '+Date.now());
await page.getByRole('button',{name:'Save project',exact:true}).click();await page.waitForURL(/\/Projects(?:\/Details)?\//);
const projectId=Number(page.url().match(/\/(\d+)(?:\?|$)/)[1]);identity.ProjectID=projectId;fs.writeFileSync(identityPath,JSON.stringify(identity));
async function state(){const r=await context.request.get(base+'/Geography/State?projectId='+projectId);assert.equal(r.status(),200);return r.json();}
async function location(name,type,parent){
await page.goto(base+'/Locations/Create?projectId='+projectId);await page.locator('#LocationName').fill(name);await page.locator('#LocationTypeID').selectOption({label:type});
if(parent)await page.locator('#ParentLocationID').selectOption(String(parent));
await Promise.all([page.waitForURL(/\/Locations\/Details\/\d+/),page.getByRole('button',{name:'Save location',exact:true}).click()]);
const id=Number(new URL(page.url()).pathname.match(/\/(\d+)$/)[1]),s=(await state()).find(s=>s.locationID===id);
if(parent)assert.notEqual(s.jobState,'Awaiting hierarchy request','explicit parent assignment automatically requests eligible lookup');
else assert.equal(s.jobState,'Awaiting hierarchy request','unparented creation does not request lookup');
return id;
}
const uk=await location('United Kingdom','Country'),birmingham=await location('Birmingham','Town',uk),rubery=await location('Rubery','Village',birmingham),northfield=await location('Northfield','Town',birmingham),redditch=await location('Redditch','Town',uk);
console.log('PASS automatic eligible parent-assignment submission; no manual Resolve action used.');
const ids=[birmingham,rubery,northfield,redditch];let rows;
const deadline=Date.now()+150000;
while(Date.now()<deadline){rows=await state();if(ids.every(id=>['Resolved','Needs confirmation'].includes(rows.find(s=>s.locationID===id)?.status)))break;await new Promise(r=>setTimeout(r,2000));}
assert(ids.every(id=>['Resolved','Needs confirmation'].includes(rows.find(s=>s.locationID===id)?.status)),'finite worker queue must advance to real coordinates/candidates');
for(const [name,id]of [['Birmingham',birmingham],['Rubery',rubery],['Northfield',northfield],['Redditch',redditch]]){
const s=rows.find(s=>s.locationID===id);if(s.status==='Resolved')continue;
const candidates=JSON.parse(s.candidatesJson),matching=candidates.filter(c=>c.Provider==='Nominatim'&&c.PlaceID.startsWith('node:')&&c.Name.startsWith(name+',')&&c.CountryCode==='GB');
assert.equal(matching.length,1,'acceptance author selects the named point location, not an administrative centroid');
await page.goto(base+'/Locations/Details/'+id);await page.locator('[data-geography-location] summary').click();
await page.locator('[data-geography-body] button').filter({hasText:matching[0].Name}).filter({hasText:'Point location'}).click();
await page.waitForFunction(()=>document.querySelector('[data-geography-status]').textContent==='Resolved');
}
rows=await state();const geographical=Object.fromEntries(ids.map(id=>[id,rows.find(s=>s.locationID===id).matchJson]));
assert(ids.every(id=>JSON.parse(geographical[id]).Provider==='Nominatim'),'all coordinates are genuine provider data');
await page.goto(base+'/Maps?projectId='+projectId);await page.locator('#mapsNew').click();await page.locator('#mapsNewForm [name=Name]').fill('Birmingham live acceptance');await page.locator('#mapsNewForm [name=Starter]').selectOption('island');
await Promise.all([page.waitForURL(/&id=\d+/),page.locator('#mapsNewForm button[type=submit]').click()]);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
const mapURL=page.url();identity.MapURL=mapURL;fs.writeFileSync(identityPath,JSON.stringify(identity));
await page.evaluate(({ids,names})=>{
const W=window.PlotDirectorMapWorkspace,E=window.PlotDirectorMaps;
W.edit(()=>{
ids.forEach((id,i)=>{const f=E.makeFeature('Town',-850+i*220,80-i*100,crypto.randomUUID());Object.assign(f,{name:names[i],locationID:id,isProvisional:false,createLocation:false});W.document.features.push(f);});
const lock=E.makeFeature('Town',150,160,crypto.randomUUID());Object.assign(lock,{name:'Locked duplicate',locationID:ids[0],isLocked:true,isProvisional:false});W.document.features.push(lock);
const road=E.makeFeature('Road',100,200,crypto.randomUUID());W.document.features.push(road);
});W.fit();
},{ids,names:['Birmingham','Rubery','Northfield','Redditch']});
async function save(){await page.locator('#mapsSave').click();await page.waitForFunction(()=>document.getElementById('mapsStatus').textContent==='Saved');}
await save();const read=()=>page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features));const before=await read();
await page.locator('#mapsGeographic').click();await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});
assert(await page.locator('#mapsGeographicPreview svg').isVisible());assert.equal(await page.locator('#mapsGeographicPreview [data-feature-id]').count(),0);
assert.equal(await read(),before);await page.locator('#mapsGeographicCancel').click();assert.equal(await read(),before);
await page.locator('#mapsGeographic').click();await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});assert(await page.locator('#mapsGeographicApply').isEnabled());await page.locator('#mapsGeographicApply').click();
assert(!await page.locator('#mapsGeographicDialog').isVisible(),'Apply closes dialog');const applied=await read();assert.notEqual(applied,before);
const features=JSON.parse(applied),by=id=>features.find(f=>f.locationID===id&&!f.isLocked);
assert(by(rubery).x<by(birmingham).x&&by(rubery).y>by(birmingham).y,'Rubery southwest of Birmingham');assert(by(redditch).y>by(northfield).y,'Redditch south of Northfield');
assert.deepEqual(features.filter(f=>!ids.includes(f.locationID)||f.isLocked),JSON.parse(before).filter(f=>!ids.includes(f.locationID)||f.isLocked),'locks, island and road untouched');
await page.locator('#mapsUndo').click();assert.equal(await read(),before);await page.locator('#mapsRedo').click();assert.equal(await read(),applied);
await save();await page.reload();await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);assert.equal(await read(),applied,'real Save/reload persists positions');
const afterGeo=await state();for(const id of ids)assert.equal(afterGeo.find(s=>s.locationID===id).matchJson,geographical[id]);
const pwa=await browser.newContext({viewport:{width:1700,height:1100},storageState:await context.storageState()});await pwa.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const app=await pwa.newPage();app.on('pageerror',e=>errors.push(e.message));await app.goto(mapURL);await app.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
const action=app.locator('[data-pwa-context-controls] [data-command-identity="handler:mapsGeographic"]'),menu=action.locator('xpath=ancestor::details[1]');
if(await menu.count()&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();await action.click();assert(await app.locator('#mapsGeographicPreview svg').isVisible());await app.locator('#mapsGeographicCancel').click();
assert.deepEqual(errors,[]);console.log('PASS authenticated Development: real Nominatim candidates/confirmation, visible preview, Apply closure/movement, Undo/Redo, real Save/reload, independent coordinates, untouched locks/drawings and actual PWA action.');
await pwa.close();await context.close();
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -13,7 +13,7 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=r
await page.getByRole('button',{name:/Newtown/}).click();
await page.waitForFunction(()=>document.querySelector('[data-geography-status]').textContent==='Resolved');
assert.deepEqual(chosen,{projectId:'7',locationId:'11',generation:'4',candidateIndex:'0'});
assert(await page.getByText('Newtown <script>unsafe()</script> · Powys, Wales · GB',{exact:true}).isVisible(),'metadata is rendered as text');
assert(await page.getByText('Newtown <script>unsafe()</script> · Point location · Powys, Wales · GB',{exact:true}).isVisible(),'metadata is rendered as text');
assert.equal(await page.locator('script').count(),1,'no candidate HTML injection');
assert(await page.getByRole('button',{name:'Change geographical match'}).isVisible());
console.log('PASS Location candidate context, index-only confirmation, generation protection and safe text rendering; no external calls.');

View File

@ -15,9 +15,14 @@ assert.equal(r.skipped.length,2);
for(const coords of [[[52,0]],[[52,0],[52,0]],[[52,0],[52,1]],[[0,179.9],[0,-179.9]],[[89,0],[89,1]]]){
const result=position(coords.map((_,i)=>marker(i+1)),coords.map((p,i)=>state(i+1,...p)),box);
assert(result.features.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y)),'single/two/coincident/antimeridian/polar points finite');
if(coords.length===1)assert.deepEqual([result.features[0].x,result.features[0].y],[600,400]);
if(coords.length===1){assert.equal(result.canApply,false);assert.deepEqual([result.features[0].x,result.features[0].y],[10,10],'one place never moves');}
}
assert.throws(()=>position([marker(1),marker(2)],[state(1,0,0),state(2,0,160)],box),/too large|too much/);
assert.equal(position([marker(1)],[{locationID:1,status:'Needs confirmation'}],box).positioned.length,0);
assert.equal(position([marker(1)],[state(1,NaN,0)],box).positioned.length,0);
console.log('PASS geographical projection direction, proportional distances, aspect ratio, padding, antimeridian, polar/single/coincident cases, extent refusal, locks and preservation.');
const single=position([marker(1),marker(2)],[state(1,52,0),{locationID:2,status:'Pending',jobState:'Awaiting hierarchy request'}],box);
assert.equal(single.canApply,false);assert.equal(single.skipped[0].reason,'Not requested');assert(single.skipped[0].canRequest);
assert.deepEqual(single.features,[marker(1),marker(2)]);
const duplicate=position([marker(1),marker(1,{featureID:'copy'})],[state(1,52,0)],box);assert.equal(duplicate.canApply,false,'copies of one location are not two places');

View File

@ -8,10 +8,11 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238';
const context=await browser.newContext({viewport:{width:1700,height:1100}});
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
let saves=0;
let saves=0,lookupRequests=0;
await page.route('**/Maps/Save',r=>{saves++;const d=r.request().postDataJSON();d.map.revision++;return r.fulfill({json:d});});
const states=[[11,52.486,-1.89],[12,52.391,-2.016]].map(([id,lat,lon])=>({locationID:id,status:'Resolved',matchJson:JSON.stringify({Latitude:lat,Longitude:lon,Attribution:'Synthetic fixture; no provider calls'})}));
states.push({locationID:13,status:'Needs confirmation'});
await page.route('**/Geography/RequestLocations',r=>{lookupRequests++;const data=new URLSearchParams(r.request().postData());assert.deepEqual(data.getAll('locationIds'),['12']);states[1].jobState='Queued';return r.fulfill({json:{message:'1 place queued'}});});
await page.route('**/Geography/State?*',r=>r.fulfill({json:states}));
await page.goto(base+'/fixture?page=maps&theme='+theme);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
await page.evaluate(()=>{
@ -32,6 +33,18 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238';
await proxy.click();
}else await page.evaluate(id=>document.getElementById(id).click(),id);
}
states[1].status='Pending';states[1].jobState='Awaiting hierarchy request';
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});
assert(await page.locator('#mapsGeographicApply').isDisabled(),'one location must not be an applicable arrangement');
assert.match(await page.locator('#mapsGeographicMessage').innerText(),/At least two/);
assert.match(await page.locator('#mapsGeographicSummary').innerText(),/Rubery — Not requested/);
assert(await page.locator('#mapsGeographicPreview svg').isVisible(),'proposal is visible inside the dialog');
assert.equal(await page.locator('#mapsGeographicPreview [data-feature-id]').count(),0,'preview clone is not editable or selectable');
assert.equal(await read(),before);
await command('mapsGeographicRequest');await page.waitForFunction(()=>document.getElementById('mapsGeographicRequest').hidden);
assert.equal(lookupRequests,1);assert.match(await page.locator('#mapsGeographicSummary').innerText(),/Rubery — Queued/);
states[1].status='Resolved';await command('mapsGeographicRefresh');await page.waitForFunction(()=>!document.getElementById('mapsGeographicApply').disabled);
await command('mapsGeographicCancel');assert.equal(await read(),before);
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});
assert.equal(await read(),before,'preview never mutates saved/working document');
assert.match(await page.locator('#mapsGeographicSummary').innerText(),/Newtown — Needs confirmation/);
@ -40,6 +53,7 @@ const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238';
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});await page.keyboard.press('Escape');
assert.equal(await page.locator('#mapsGeographicDialog').isVisible(),false,'Escape cancels');assert.equal(await read(),before);
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});await command('mapsGeographicApply');
assert.equal(await page.locator('#mapsGeographicDialog').isVisible(),false,'Apply closes its dialog');
const applied=await read();assert.notEqual(applied,before);
const features=JSON.parse(applied),prior=JSON.parse(before);
assert(features[1].x<features[0].x&&features[1].y>features[0].y,'Rubery is southwest of Birmingham');

View File

@ -0,0 +1,69 @@
// Explicit operator-only Development acceptance command. Never runs in the normal regression harness.
using System.Data;
using System.Diagnostics;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class GeographyLiveRecovery
{
public static async Task Run(string[] args)
{
if(args.Length!=3 || !int.TryParse(args[1],out var project)||!int.TryParse(args[2],out var location))throw new InvalidOperationException("Use --geography-live-recovery projectId locationId; Development only, one previously empty lookup.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
using var process=Process.Start(start)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();
if(process.ExitCode!=0)throw new InvalidOperationException("Development settings unavailable.");
var connectionString=environment.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Development only.");
using var db=new SqlConnection(connectionString);await db.OpenAsync();
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong effective database.");
var settingsStart=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
foreach(var arg in new[]{"-n","cat","/srv/apps/plotdirector-dev/current/appsettings.Development.json"})settingsStart.ArgumentList.Add(arg);
using var settingsProcess=Process.Start(settingsStart)!;var settingsJson=await settingsProcess.StandardOutput.ReadToEndAsync();await settingsProcess.WaitForExitAsync();
if(settingsProcess.ExitCode!=0)throw new InvalidOperationException("Development provider settings unavailable.");
using var settingsStream=new MemoryStream(System.Text.Encoding.UTF8.GetBytes(settingsJson));
var settings=new ConfigurationBuilder().AddJsonStream(settingsStream).AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();
if(new Uri(settings["Geography:Endpoint"]!).Host!="nominatim.openstreetmap.org")throw new InvalidOperationException("This acceptance command is restricted to the explicitly selected public Nominatim provider.");
var services=new ServiceCollection();services.AddLogging();services.Configure<GeocodingOptions>(settings.GetSection("Geography"));
services.AddHttpClient("Geocoding",client=>client.Timeout=TimeSpan.FromSeconds(25)).RemoveAllLoggers().ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler{AllowAutoRedirect=false});
services.AddSingleton<IGeocodingProvider,NominatimGeocodingProvider>();
using var serviceProvider=services.BuildServiceProvider();var provider=serviceProvider.GetRequiredService<IGeocodingProvider>();
if(!provider.Enabled)throw new InvalidOperationException("Provider disabled or wrong worker host.");
var repository=new GeographyRepository(new SqlConnectionFactory(settings));
var rules=new GeographicRules(Path.GetFullPath("PlotLine/Data/Reference/Geography"));var chain=await repository.ChainAsync(location);
if(chain.Count==0||chain[0].ProjectID!=project||rules.Query(chain) is null)throw new InvalidOperationException("The explicit recovery target must be an eligible location in the selected project.");
var baseline=await db.ExecuteScalarAsync<int>("SELECT COALESCE((SELECT DailyRequests FROM dbo.GeographicProviderGate WHERE Provider='Geocoding.External'),0)");
GeographicJob job;
using(var transaction=db.BeginTransaction())
{
var generation=await db.QuerySingleOrDefaultAsync<long?>("SELECT Generation FROM dbo.LocationGeography WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@location AND Status='Unresolved' AND CandidatesJson='[]' AND Confirmed=0",new{location},transaction);
if(generation is null)throw new InvalidOperationException("Recovery requires an observed, unconfirmed empty full-context result; refusing to replace newer work.");
var user=await db.QuerySingleAsync<int>("SELECT MIN(UserID) FROM dbo.ProjectUserAccess WHERE ProjectID=@project AND IsActive=1",new{project},transaction);
await db.ExecuteAsync("dbo.Geography_Retry",new{ProjectID=project,UserID=user,LocationID=location,Generation=generation.Value},transaction,commandType:CommandType.StoredProcedure);
// The full query has already returned an empty result. Resume exactly this durable job at its one fallback stage.
job=await db.QuerySingleAsync<GeographicJob>("UPDATE dbo.LocationGeography SET RelaxedGeneration=Generation,JobState='Processing',Lease=NEWID(),LeaseUntil=DATEADD(minute,2,SYSUTCDATETIME()) OUTPUT inserted.LocationID,inserted.Generation,inserted.Attempts,inserted.Lease,CAST(1 AS bit) RelaxedContext WHERE LocationID=@location",new{location},transaction);
transaction.Commit();
}
await new GeographicProcessor(new HeldJob(repository,job),rules,provider).ProcessOneAsync(default);
var result=await db.QuerySingleAsync<(string Status,string JobState,int Attempts,string? CandidatesJson)>("SELECT Status,JobState,Attempts,CandidatesJson FROM dbo.LocationGeography WHERE LocationID=@location",new{location});
var requests=await db.ExecuteScalarAsync<int>("SELECT DailyRequests FROM dbo.GeographicProviderGate WHERE Provider='Geocoding.External'");
Console.WriteLine($"LIVE Development recovery: location {location}, status {result.Status}, worker state {result.JobState}, failures {result.Attempts}, candidates {JsonSerializer.Deserialize<List<GeographicCandidate>>(result.CandidatesJson??"[]")!.Count}, actual provider reservations {baseline} → {requests}.");
if(result.Status!="Needs confirmation"||requests-baseline>1)throw new InvalidOperationException("Bounded live recovery did not return confirmation candidates; inspect queue state.");
}
sealed class HeldJob(GeographyRepository repository,GeographicJob job):IGeographicQueue
{
public Task<GeographicJob?> ClaimAsync(bool enabled)=>Task.FromResult<GeographicJob?>(job);
public Task<IReadOnlyList<LocationItem>> ChainAsync(int id)=>repository.ChainAsync(id);
public Task<string?> CacheAsync(string key)=>repository.CacheAsync(key);
public Task<bool> ReserveAsync(string provider,TimeSpan interval,string key,Guid lease)=>repository.ReserveAsync(provider,interval,key,lease);
public Task ReleaseAsync(Guid lease,int cooldownSeconds=0)=>repository.ReleaseAsync(lease,cooldownSeconds);
public Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0,bool relaxContext=false)
=>repository.CompleteAsync(job,status,jobState,key,candidates,match,message,failure,delay,relaxContext);
}
}

View File

@ -53,6 +53,13 @@ internal static class GeographyTests
Check(NominatimGeocodingProvider.Parse(query! with{Name="Newtown",SubdivisionCode="GB-WLS",Ancestors=["Wales","Powys"]},response.RootElement).Single().UniqueWithinContext,"Exact place plus matching county/constituent context resolves deterministically.");
Check(NominatimGeocodingProvider.Parse(query!,response.RootElement).Count==0,"Reject results outside explicit subdivision.");
}
var fallbackQueue=new QueueFake([Place("Test settlement","Village",2),Place("Nearby city","Town",3),Place("UK","Country")]);
var emptyProvider=new ProviderFake([]);
await new GeographicProcessor(fallbackQueue,rules,emptyProvider).ProcessOneAsync(default);
Check(fallbackQueue.Job.RelaxedContext&&fallbackQueue.Status=="Pending"&&fallbackQueue.Delay>=15,"Empty full-context lookup schedules one durable, rate-limited fallback.");
fallbackQueue.Cached=null;fallbackQueue.Requeue();
await new GeographicProcessor(fallbackQueue,rules,emptyProvider).ProcessOneAsync(default);
Check(fallbackQueue.Status=="Unresolved"&&emptyProvider.Calls==2,"Country fallback is bounded to one additional request.");
var denied=new GeographyController(null!,new DeniedAccess(),null!,null!,null!);
Check(await denied.State(7,null) is NotFoundResult,"Cross-account state rejected before repository.");
Check(await denied.Confirm(7,1,1,0) is NotFoundResult,"Cross-account coordinate confirmation rejected.");
@ -107,7 +114,7 @@ internal static class GeographyTests
public Task<string?> CacheAsync(string key)=>Task.FromResult(Cached);
public Task<bool> ReserveAsync(string provider,TimeSpan interval,string key,Guid lease)=>Task.FromResult(AllowReservation);
public Task ReleaseAsync(Guid lease,int cooldownSeconds=0)=>Task.CompletedTask;
public Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0)
{Status=status;State=jobState;Match=match;Delay=delay;if(candidates!=null)Cached=candidates;ready=jobState=="Queued";return Task.CompletedTask;}
public Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0,bool relaxContext=false)
{Status=status;State=jobState;Match=match;if(relaxContext)Job.RelaxedContext=true;Delay=delay;if(candidates!=null)Cached=candidates;ready=jobState=="Queued";return Task.CompletedTask;}
}
}

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--geography-live-recovery")){await GeographyLiveRecovery.Run(args);return;}
if(args.Contains("--geography-database")){await GeographyDatabaseTests.Run();return;}
if(args.Contains("--geography")){await GeographyTests.Run();return;}
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}

View File

@ -25,7 +25,7 @@ BEGIN TRY
IF (SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Child)<>@Generation+2 THROW 51000,'Reparent did not invalidate',1;
UPDATE dbo.LocationGeography SET JobState='Done'; -- Rollback-only isolation from pre-existing jobs.
UPDATE dbo.LocationGeography SET JobState='Queued' WHERE LocationID=@Child;
DECLARE @Jobs table(LocationID int,Generation bigint,Attempts int,Lease uniqueidentifier);
DECLARE @Jobs table(LocationID int,Generation bigint,Attempts int,Lease uniqueidentifier,RelaxedContext bit);
INSERT @Jobs EXEC dbo.Geography_Claim @Enabled=1;
IF (SELECT COUNT(*) FROM @Jobs)<>1 THROW 51000,'Claim failed',1;
DECLARE @Lease uniqueidentifier=(SELECT Lease FROM @Jobs),@Current bigint=(SELECT Generation FROM @Jobs);

View File

@ -3,11 +3,12 @@ IF DB_NAME()<>'PlotDirector_Development' THROW 51000,'Development only.',1;
BEGIN TRANSACTION;
BEGIN TRY
DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Name nvarchar(200)=CONCAT('Hierarchy event fixture ',NEWID());
DELETE dbo.GeographicAuthorBatch WHERE UserID=@User; -- rollback-only quota isolation
EXEC dbo.Project_Save @ProjectName=@Name,@UserID=@User;
DECLARE @Project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@Name);
INSERT dbo.Locations(ProjectID,LocationName)VALUES(@Project,'United Kingdom');
INSERT dbo.Locations(ProjectID,LocationName,LocationTypeID)SELECT @Project,'United Kingdom',LocationTypeID FROM dbo.LocationTypes WHERE TypeName='Country';
DECLARE @Root int=SCOPE_IDENTITY();
INSERT dbo.Locations(ProjectID,ParentLocationID,LocationName)VALUES(@Project,@Root,'Birmingham');
INSERT dbo.Locations(ProjectID,ParentLocationID,LocationName,LocationTypeID)SELECT @Project,@Root,'Birmingham',LocationTypeID FROM dbo.LocationTypes WHERE TypeName='Town';
DECLARE @Child int=SCOPE_IDENTITY();
IF EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID IN(@Root,@Child) AND JobState<>'Awaiting hierarchy request') THROW 51000,'Creation enqueued lookup',1;
UPDATE dbo.Locations SET LocationName='England' WHERE LocationID=@Root;
@ -16,15 +17,10 @@ BEGIN TRY
EXEC dbo.Geography_SubmitHierarchy @ProjectID=@Project,@UserID=@User,@LocationID=@Root,@Generation=@Generation;
IF (SELECT COUNT(*) FROM dbo.LocationGeography WHERE LocationID IN(@Root,@Child) AND JobState='Queued')<>2 THROW 51000,'Explicit hierarchy request did not queue finite scope',1;
IF (SELECT COUNT(*) FROM dbo.GeographicAuthorBatch WHERE UserID=@User)<>1 THROW 51000,'Batch admission missing',1;
DECLARE @Denied bit=0;
BEGIN TRY
EXEC dbo.Geography_SubmitHierarchy @ProjectID=@Project,@UserID=@User,@LocationID=@Root,@Generation=@Generation;
END TRY BEGIN CATCH
IF ERROR_NUMBER()=51000 SET @Denied=1; ELSE THROW;
END CATCH;
IF @Denied=0 THROW 51000,'Author batch quota bypassed',1;
IF (SELECT COUNT(*) FROM dbo.GeographicAuthorBatch WHERE UserID=@User)<>1 THROW 51000,'Duplicate hierarchy charged twice',1;
IF XACT_STATE()<>0 ROLLBACK;
SELECT 'PASS creation and rename do not geocode; explicit hierarchy event queues finite branch; repeat author batches rejected';
SELECT 'PASS creation and rename do not geocode; explicit hierarchy event queues finite branch; duplicate hierarchy requests are free';
END TRY BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK;
THROW;

View File

@ -0,0 +1,37 @@
SET NOCOUNT ON; SET XACT_ABORT ON;
IF DB_NAME()<>'PlotDirector_Development' THROW 51000,'Development only.',1;
BEGIN TRANSACTION;
BEGIN TRY
DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Title nvarchar(200)=CONCAT('Geography accounting rollback ',NEWID());
DELETE dbo.GeographicAuthorBatch; -- rollback-only isolation; no live quota changes survive.
EXEC dbo.Project_Save @ProjectName=@Title,@UserID=@User;
DECLARE @Project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@Title),@Town int=(SELECT LocationTypeID FROM dbo.LocationTypes WHERE TypeName='Town');
INSERT dbo.Locations(ProjectID,LocationName,LocationTypeID)VALUES(@Project,'resolved',@Town),(@Project,'queued',@Town),(@Project,'fresh',@Town),(@Project,'cached',@Town);
DECLARE @Resolved int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@Project AND LocationName='resolved'),@Queued int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@Project AND LocationName='queued'),@Fresh int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@Project AND LocationName='fresh'),@Cached int=(SELECT LocationID FROM dbo.Locations WHERE ProjectID=@Project AND LocationName='cached');
DECLARE @Key char(64)=CONVERT(char(64),HASHBYTES('SHA2_256',CONVERT(varchar(36),NEWID())),2);
INSERT dbo.GeographicCache(RequestKey,CandidatesJson)VALUES(@Key,'[]');
UPDATE dbo.LocationGeography SET Status='Resolved',JobState='Done',Confirmed=1 WHERE LocationID=@Resolved;
UPDATE dbo.LocationGeography SET JobState='Queued' WHERE LocationID=@Queued;
DECLARE @Json nvarchar(max)=(SELECT LocationID,Generation,CASE WHEN LocationID=@Cached THEN @Key ELSE NULL END RequestKey FROM dbo.LocationGeography WHERE LocationID IN(@Resolved,@Queued,@Fresh,@Cached) FOR JSON PATH);
EXEC dbo.Geography_SubmitLocations @ProjectID=@Project,@UserID=@User,@Locations=@Json;
IF (SELECT COUNT(*) FROM dbo.LocationGeography WHERE LocationID IN(@Queued,@Fresh,@Cached) AND JobState='Queued')<>3 THROW 51000,'Resolved/queued/cache accounting failed',1;
IF (SELECT SUM(LocationCount) FROM dbo.GeographicAuthorBatch WHERE UserID=@User)<>1 THROW 51000,'Incorrect billed work',1;
EXEC dbo.Geography_SubmitLocations @ProjectID=@Project,@UserID=@User,@Locations=@Json;
IF (SELECT COUNT(*) FROM dbo.GeographicAuthorBatch WHERE UserID=@User)<>1 THROW 51000,'Duplicate created an admission record',1;
-- Another small author action is allowed inside the hour; only new work is charged.
INSERT dbo.Locations(ProjectID,LocationName,LocationTypeID)VALUES(@Project,'next action',@Town);
DECLARE @Next int=SCOPE_IDENTITY();
SET @Json=(SELECT LocationID,Generation FROM dbo.LocationGeography WHERE LocationID=@Next FOR JSON PATH);
EXEC dbo.Geography_SubmitLocations @ProjectID=@Project,@UserID=@User,@Locations=@Json;
IF (SELECT SUM(LocationCount) FROM dbo.GeographicAuthorBatch WHERE UserID=@User)<>2 THROW 51000,'Second small action blocked or mischarged',1;
EXEC dbo.Geography_BatchPermit @UserID=@User,@LocationCount=18;
DECLARE @Denied bit=0;
BEGIN TRY EXEC dbo.Geography_BatchPermit @UserID=@User,@LocationCount=1; END TRY BEGIN CATCH IF ERROR_NUMBER()=51000 SET @Denied=1; ELSE THROW; END CATCH;
IF @Denied=0 THROW 51000,'Author work budget not enforced',1;
IF XACT_STATE()<>0 ROLLBACK;
SELECT 'PASS accurate accounting: cached/resolved/queued/duplicates free; successive small actions permitted; 20 new locations/hour enforced; rollback fixtures only';
END TRY BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK;
THROW;
END CATCH;

View File

@ -67,4 +67,11 @@ public sealed class GeographyController(GeographyRepository repository,IProjectA
if(!ModelState.IsValid) return BadRequest();
return Json(new {message=await hierarchy.SubmitAsync(projectId,locationId)});
}
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> RequestLocations(int projectId,int[] locationIds,[FromServices] GeographicHierarchyService hierarchy)
{
if(!await access.CanAccessProjectAsync(projectId))return NotFound();
if(!ModelState.IsValid || locationIds is not {Length:>=1 and <=20})return BadRequest();
return Json(new {message=await hierarchy.SubmitLocationsAsync(projectId,locationIds.Distinct().ToArray())});
}
}

View File

@ -118,7 +118,8 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
var before = model.LocationID > 0 ? await locations.GetEditAsync(model.LocationID) : null;
var locationId = await locations.SaveAsync(model);
if (before is not null && before.ParentLocationID != model.ParentLocationID)
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 });
}

View File

@ -10,7 +10,7 @@ public interface IGeographicQueue
Task<string?> CacheAsync(string requestKey);
Task<bool> ReserveAsync(string provider,TimeSpan interval,string requestKey,Guid lease);
Task ReleaseAsync(Guid lease,int cooldownSeconds=0);
Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0);
Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0,bool relaxContext=false);
}
public sealed class GeographyRepository(ISqlConnectionFactory connections) : IGeographicQueue
@ -40,10 +40,10 @@ public sealed class GeographyRepository(ISqlConnectionFactory connections) : IGe
using var db=connections.CreateConnection();
return await db.QuerySingleAsync<bool>("dbo.Geography_Reserve",new {Provider=provider,RequestKey=requestKey,Lease=lease,IntervalMs=(int)Math.Clamp(interval.TotalMilliseconds,0,86400000)},commandType:CommandType.StoredProcedure);
}
public async Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0)
public async Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0,bool relaxContext=false)
{
using var db=connections.CreateConnection();
await db.ExecuteAsync("dbo.Geography_Complete",new {job.LocationID,job.Generation,job.Lease,Status=status,JobState=jobState,RequestKey=key,CandidatesJson=candidates,MatchJson=match,Message=message,Failure=failure,DelaySeconds=delay},commandType:CommandType.StoredProcedure);
await db.ExecuteAsync("dbo.Geography_Complete",new {job.LocationID,job.Generation,job.Lease,Status=status,JobState=jobState,RequestKey=key,CandidatesJson=candidates,MatchJson=match,Message=message,Failure=failure,DelaySeconds=delay,RelaxContext=relaxContext},commandType:CommandType.StoredProcedure);
}
public async Task ChooseAsync(int projectId,int userId,int locationId,long generation,int candidateIndex)
{
@ -70,4 +70,9 @@ public sealed class GeographyRepository(ISqlConnectionFactory connections) : IGe
using var db=connections.CreateConnection();
await db.ExecuteAsync("dbo.Geography_ProviderRelease",new {Lease=lease,CooldownSeconds=cooldownSeconds},commandType:CommandType.StoredProcedure);
}
public async Task<GeographicSubmission> SubmitLocationsAsync(int projectId,int userId,IEnumerable<GeographicLookupRequest> requests)
{
using var db=connections.CreateConnection();
return await db.QuerySingleAsync<GeographicSubmission>("dbo.Geography_SubmitLocations",new {ProjectID=projectId,UserID=userId,Locations=System.Text.Json.JsonSerializer.Serialize(requests)},commandType:CommandType.StoredProcedure);
}
}

View File

@ -1,7 +1,7 @@
namespace PlotLine.Models;
public sealed record GeographicRoot(string CountryCode, string? SubdivisionCode = null);
public sealed record GeographicQuery(string Name, string CountryCode, string? SubdivisionCode, string[] Ancestors);
public sealed record GeographicQuery(string Name, string CountryCode, string? SubdivisionCode, string[] Ancestors, bool RelaxedContext = false);
public sealed record GeographicCandidate(string Provider, string PlaceID, string Name, double Latitude, double Longitude,
string CountryCode, string[] AdministrativeNames, string Attribution, bool UniqueWithinContext = false);
public sealed class LocationGeography
@ -9,6 +9,10 @@ public sealed class LocationGeography
public int LocationID { get; set; }
public long Generation { get; set; }
public string Status { get; set; } = "Pending";
public string JobState { get; set; } = "Awaiting hierarchy request";
public int Attempts { get; set; }
public DateTime NextAttempt { get; set; }
public DateTime? LeaseUntil { get; set; }
public string? CandidatesJson { get; set; }
public string? MatchJson { get; set; }
public bool Confirmed { get; set; }
@ -21,4 +25,13 @@ public sealed class GeographicJob
public Guid Lease { get; set; }
public long Generation { get; set; }
public int Attempts { get; set; }
public bool RelaxedContext { get; set; }
}
public sealed record GeographicLookupRequest(int LocationID,long Generation,string RequestKey);
public sealed class GeographicSubmission
{
public int Queued { get; set; }
public int Cached { get; set; }
public int Charged { get; set; }
}

View File

@ -1,18 +1,50 @@
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services;
public sealed class GeographicHierarchyService(GeographyRepository repository,GeographicRules rules,IProjectAccessService access,ICurrentUserService currentUser)
public sealed class GeographicHierarchyService(GeographyRepository repository,GeographicRules rules,IProjectAccessService access,
ICurrentUserService currentUser,ILocationRepository locations,IGeocodingProvider provider)
{
public async Task<string> SubmitAsync(int projectId,int locationId)
{
if(!await access.CanAccessProjectAsync(projectId))return "Project access is required.";
var chain=await repository.ChainAsync(locationId);
if(chain.Count==0 || chain[0].ProjectID!=projectId)return "Location is unavailable.";
if(rules.Query(chain) is null)return "This hierarchy is not eligible for geographical lookup. Use geographical types beneath a recognised root.";
var state=(await repository.GetAsync(projectId,currentUser.UserId!.Value,locationId)).SingleOrDefault();
if(state is null)return "Geographical state is unavailable.";
try {await repository.SubmitAsync(projectId,currentUser.UserId!.Value,locationId,state.Generation);return "Geographical hierarchy lookup requested (at most 20 places). External processing requires the configured provider to be enabled.";}
var all=await locations.ListByProjectAsync(projectId);
if(!all.Any(l=>l.LocationID==locationId))return "Location is unavailable.";
var scope=new HashSet<int>{locationId};
for(var depth=0;depth<100;depth++)
{
var added=false;
foreach(var l in all)if(l.ParentLocationID is int parent && scope.Contains(parent))added|=scope.Add(l.LocationID);
if(!added)break;
}
return await SubmitLocationsAsync(projectId,scope.ToArray(),all);
}
public async Task<string> SubmitLocationsAsync(int projectId,IReadOnlyCollection<int> ids,IReadOnlyList<LocationItem>? projectLocations=null)
{
if(!await access.CanAccessProjectAsync(projectId))return "Project access is required.";
var all=(projectLocations ?? await locations.ListByProjectAsync(projectId)).ToDictionary(l=>l.LocationID);
var states=await repository.GetAsync(projectId,currentUser.UserId!.Value);
var requests=new List<GeographicLookupRequest>();
foreach(var state in states.Where(s=>ids.Contains(s.LocationID)&&!s.IsExcluded && !s.Confirmed && s.Status!="Resolved" && s.JobState=="Awaiting hierarchy request"))
{
var chain=new List<LocationItem>();var seen=new HashSet<int>();var id=state.LocationID;
while(all.TryGetValue(id,out var place)&&seen.Add(id)&&chain.Count<=100)
{
chain.Add(place);
if(place.ParentLocationID is not int parent)break;
id=parent;
}
var query=rules.Query(chain);
if(query is not null)requests.Add(new(state.LocationID,state.Generation,GeographicRules.CacheKey(query,provider.Name)));
}
if(requests.Count==0)return "No new lookups required. Eligible places are already resolved or requested; unsuitable places are excluded.";
if(requests.Count>20)return "Choose a smaller branch: at most 20 new eligible places can be requested at a time.";
try
{
var result=await repository.SubmitLocationsAsync(projectId,currentUser.UserId!.Value,requests);
return $"{result.Queued} places queued ({result.Cached} cached; {result.Charged} new lookups). The worker processes requests at a maximum of four per minute. Refresh status to see progress.";
}
catch(SqlException ex) when(ex.Number==51000){return ex.Message;}
}
}

View File

@ -59,7 +59,7 @@ public sealed class GeographicRules
chain.Skip(1).Reverse().Select(l => l.LocationName).ToArray());
}
public static string CacheKey(GeographicQuery query, string source = "") => Convert.ToHexString(SHA256.HashData(
Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Source = source, Name = query.Name.Trim().ToUpperInvariant(), query.CountryCode,
Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Source = query.RelaxedContext ? source+":context-fallback" : source, Name = query.Name.Trim().ToUpperInvariant(), query.CountryCode,
query.SubdivisionCode, Ancestors = query.Ancestors.Select(x => x.Trim().ToUpperInvariant()).ToArray() }))));
public static IReadOnlyList<GeographicCandidate> Candidates(GeographicQuery query, IEnumerable<GeographicCandidate> candidates)
=> candidates.Where(c => c.CountryCode.Equals(query.CountryCode, StringComparison.OrdinalIgnoreCase)

View File

@ -28,12 +28,13 @@ public sealed class GeographicWorker(IServiceScopeFactory scopes, ILogger<Geogra
}
}
public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRules rules,IGeocodingProvider provider)
public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRules rules,IGeocodingProvider provider,ILogger<GeographicProcessor>? logger=null)
{
public async Task<bool> ProcessOneAsync(CancellationToken cancellationToken)
{
var job=await repository.ClaimAsync(provider.Enabled);
if(job is null) return false;
logger?.LogInformation("Geographical job {LocationID} generation {Generation} claimed at attempt {Attempt}.",job.LocationID,job.Generation,job.Attempts+1);
var cooldown=0;
try
{
@ -44,6 +45,7 @@ public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRu
await repository.CompleteAsync(job,"Not eligible","Done",message:"Use geographical types beneath a recognised country or qualified region.");
return true;
}
query=query with {RelaxedContext=job.RelaxedContext};
var key=GeographicRules.CacheKey(query,provider.Name);
var cached=await repository.CacheAsync(key);
IReadOnlyList<GeographicCandidate> candidates;
@ -65,7 +67,13 @@ public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRu
candidates=await provider.SearchAsync(query,timeout.Token);
}
candidates=GeographicRules.Candidates(query,candidates);
logger?.LogInformation("Geographical job {LocationID} generation {Generation}: {Count} candidates; cache hit {CacheHit}.",job.LocationID,job.Generation,candidates.Count,cached is not null);
var json=JsonSerializer.Serialize(candidates);
if(candidates.Count==0 && query.Ancestors.Length>1 && !query.RelaxedContext)
{
await repository.CompleteAsync(job,"Pending","Queued",key,json,message:"Full hierarchy context had no match; a country-scoped lookup is queued for confirmation.",delay:Math.Max(15,(int)provider.MinimumInterval.TotalSeconds),relaxContext:true);
return true;
}
// Provider adapters must establish uniqueness independently of their result limit/ranking.
var resolved=candidates.Count==1 && candidates[0].UniqueWithinContext;
await repository.CompleteAsync(job,candidates.Count==0?"Unresolved":resolved?"Resolved":"Needs confirmation","Done",key,json,
@ -81,6 +89,7 @@ public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRu
{
if(ex is GeocodingHttpException http)
cooldown=http.StatusCode is 403 or 429 ? Math.Clamp((int)(http.RetryAfter?.TotalSeconds ?? 3600),900,86400) : 60;
logger?.LogWarning("Geographical job {LocationID} generation {Generation} failed ({ErrorType}, HTTP {Status}); cooldown {CooldownSeconds}s.",job.LocationID,job.Generation,ex.GetType().Name,(ex as GeocodingHttpException)?.StatusCode,cooldown);
var exhausted=job.Attempts>=3;
await repository.CompleteAsync(job,exhausted?"Unresolved":"Pending",exhausted?"Done":"Queued",
message:exhausted?"Provider lookup failed after four attempts. You can retry later.":"Provider temporarily unavailable.",

View File

@ -32,7 +32,7 @@ public sealed class NominatimGeocodingProvider(IOptionsMonitor<GeocodingOptions>
var config=options.CurrentValue;
if(!Enabled)throw new InvalidOperationException("Geocoding is disabled or this host is not the designated worker.");
// Only public place names and geographical ancestors, never descriptions or story content.
var text=string.Join(", ",new[]{query.Name}.Concat(query.Ancestors.Reverse()));
var text=string.Join(", ",new[]{query.Name}.Concat(query.RelaxedContext?query.Ancestors.Take(1):query.Ancestors.Reverse()));
var uri=config.Endpoint+"?format=jsonv2&addressdetails=1&namedetails=1&limit=10&dedupe=1&countrycodes="
+Uri.EscapeDataString(query.CountryCode.ToLowerInvariant())+"&accept-language=en&q="+Uri.EscapeDataString(text);
using var request=new HttpRequestMessage(HttpMethod.Get,uri);
@ -81,7 +81,7 @@ public sealed class NominatimGeocodingProvider(IOptionsMonitor<GeocodingOptions>
}
var valid=GeographicRules.Candidates(query,candidates);
// Ranked results alone are insufficient. Never auto-select a saturated result set or multiple candidates.
if(valid.Count==1 && response.GetArrayLength()<10 && reliable.Contains(valid[0].PlaceID))
if(!query.RelaxedContext && valid.Count==1 && response.GetArrayLength()<10 && reliable.Contains(valid[0].PlaceID))
return new[]{valid[0] with {UniqueWithinContext=true}};
return valid;
}

View File

@ -0,0 +1,79 @@
-- Charge newly required external lookup work, never a button click or the size of a private hierarchy.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.Geography_Get @ProjectID int,@UserID int,@LocationID int=NULL AS
BEGIN
SET NOCOUNT ON;
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
SELECT g.LocationID,g.Generation,g.Status,g.JobState,g.Attempts,g.NextAttempt,g.LeaseUntil,
g.Confirmed,g.IsExcluded,g.CandidatesJson,g.MatchJson,g.Message
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND (@LocationID IS NULL OR l.LocationID=@LocationID);
END;
GO
CREATE OR ALTER PROCEDURE dbo.Geography_BatchPermit @UserID int,@LocationCount int AS
BEGIN
SET NOCOUNT ON;
IF @@TRANCOUNT=0 THROW 51000,'Batch admission requires a transaction.',1;
DECLARE @Lock int;
EXEC @Lock=sys.sp_getapplock @Resource='PlotDirector.Geography.AuthorBatches',@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=1000;
IF @Lock<0 THROW 51000,'Geographical lookup is busy. Try later.',1;
IF @LocationCount NOT BETWEEN 0 AND 20 THROW 51000,'Request at most 20 new geographical lookups at a time.',1;
IF @LocationCount=0 RETURN;
DECLARE @Since datetime2=DATEADD(hour,-1,SYSUTCDATETIME()),@Author int,@Application int;
SELECT @Author=COALESCE(SUM(LocationCount),0) FROM dbo.GeographicAuthorBatch WHERE UserID=@UserID AND RequestedAt>@Since;
SELECT @Application=COALESCE(SUM(LocationCount),0) FROM dbo.GeographicAuthorBatch WHERE RequestedAt>@Since;
IF @Author+@LocationCount>20 OR @Application+@LocationCount>120
BEGIN
DECLARE @Message nvarchar(200)=CONCAT('New lookup allowance reached: ',@Author,'/20 for your account and ',@Application,'/120 application-wide in the past hour. Cached, resolved and queued places do not count.');
THROW 51000,@Message,1;
END;
DELETE dbo.GeographicAuthorBatch WHERE RequestedAt<DATEADD(day,-90,SYSUTCDATETIME());
INSERT dbo.GeographicAuthorBatch(UserID,LocationCount)VALUES(@UserID,@LocationCount);
END;
GO
CREATE OR ALTER PROCEDURE dbo.Geography_SubmitLocations @ProjectID int,@UserID int,@Locations nvarchar(max) AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
IF ISJSON(@Locations)<>1 THROW 51000,'Invalid geographical lookup request.',1;
DECLARE @Requested table(LocationID int PRIMARY KEY,Generation bigint,RequestKey char(64));
INSERT @Requested SELECT LocationID,Generation,RequestKey FROM OPENJSON(@Locations) WITH(LocationID int,Generation bigint,RequestKey char(64));
IF (SELECT COUNT(*) FROM @Requested)>20 THROW 51000,'Choose at most 20 eligible locations.',1;
BEGIN TRANSACTION;
DECLARE @Lock int;
EXEC @Lock=sys.sp_getapplock @Resource='PlotDirector.Geography.AuthorBatches',@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=1000;
IF @Lock<0 THROW 51000,'Geographical lookup is busy. Try later.',1;
IF EXISTS(SELECT 1 FROM @Requested r LEFT JOIN dbo.Locations l ON l.LocationID=r.LocationID AND l.ProjectID=@ProjectID AND l.IsArchived=0
LEFT JOIN dbo.LocationGeography g WITH(UPDLOCK,HOLDLOCK) ON g.LocationID=l.LocationID AND g.Generation=r.Generation
WHERE g.LocationID IS NULL) THROW 51000,'A location changed or is unavailable. Refresh the hierarchy.',1;
SELECT g.LocationID,r.RequestKey INTO #New FROM @Requested r JOIN dbo.LocationGeography g ON g.LocationID=r.LocationID
WHERE g.JobState='Awaiting hierarchy request' AND g.Confirmed=0 AND g.IsExcluded=0 AND g.Status<>'Resolved';
DECLARE @Queued int=(SELECT COUNT(*) FROM #New),@Cached int=(SELECT COUNT(*) FROM #New n JOIN dbo.GeographicCache c ON c.RequestKey=n.RequestKey),@Charged int;
SET @Charged=@Queued-@Cached;
EXEC dbo.Geography_BatchPermit @UserID,@Charged;
UPDATE g SET Status='Pending',JobState='Queued',NextAttempt=SYSUTCDATETIME(),Message='Hierarchy lookup queued; waiting for the geographical worker.',RequestKey=n.RequestKey
FROM dbo.LocationGeography g JOIN #New n ON n.LocationID=g.LocationID;
COMMIT;
SELECT @Queued Queued,@Cached Cached,@Charged Charged;
END;
GO
-- Compatibility for older callers during rollout. The application supplies cache keys through SubmitLocations.
CREATE OR ALTER PROCEDURE dbo.Geography_SubmitHierarchy @ProjectID int,@UserID int,@LocationID int,@Generation bigint AS
BEGIN
SET NOCOUNT ON;
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
IF NOT EXISTS(SELECT 1 FROM dbo.Locations l JOIN dbo.LocationGeography g ON g.LocationID=l.LocationID
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND l.LocationID=@LocationID AND g.Generation=@Generation)
THROW 51000,'Hierarchy changed. Refresh before requesting lookup.',1;
;WITH tree AS(
SELECT LocationID FROM dbo.Locations WHERE LocationID=@LocationID AND ProjectID=@ProjectID AND IsArchived=0
UNION ALL SELECT l.LocationID FROM dbo.Locations l JOIN tree p ON l.ParentLocationID=p.LocationID WHERE l.ProjectID=@ProjectID AND l.IsArchived=0
) SELECT g.LocationID,g.Generation,g.RequestKey INTO #Scope FROM tree t JOIN dbo.Locations l ON l.LocationID=t.LocationID
JOIN dbo.LocationTypes lt ON lt.LocationTypeID=l.LocationTypeID JOIN dbo.LocationGeography g ON g.LocationID=l.LocationID
WHERE lt.TypeName IN('Country','Region','State','County','City','Town','Village') OPTION(MAXRECURSION 100);
DECLARE @Json nvarchar(max)=(SELECT * FROM #Scope FOR JSON PATH);
EXEC dbo.Geography_SubmitLocations @ProjectID,@UserID,@Json;
END;
GO

View File

@ -0,0 +1,59 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF COL_LENGTH('dbo.LocationGeography','RelaxedGeneration') IS NULL
ALTER TABLE dbo.LocationGeography ADD RelaxedGeneration bigint NULL;
GO
CREATE OR ALTER PROCEDURE dbo.Geography_Claim @Enabled bit AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
DECLARE @Now datetime2=SYSUTCDATETIME(),@Lease uniqueidentifier=NEWID();
;WITH job AS(SELECT TOP(1) * FROM dbo.LocationGeography WITH(UPDLOCK,READPAST,ROWLOCK)
WHERE (JobState='Queued' OR (JobState='Waiting configuration' AND @Enabled=1) OR (JobState='Processing' AND LeaseUntil<@Now))
AND NextAttempt<=@Now ORDER BY NextAttempt,LocationID)
UPDATE job SET JobState='Processing',Lease=@Lease,LeaseUntil=DATEADD(minute,2,@Now)
OUTPUT inserted.LocationID,inserted.Generation,inserted.Attempts,inserted.Lease,
CONVERT(bit,CASE WHEN inserted.RelaxedGeneration=inserted.Generation THEN 1 ELSE 0 END) RelaxedContext;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Geography_Complete
@LocationID int,@Generation bigint,@Lease uniqueidentifier,@Status varchar(24),@JobState varchar(24),
@RequestKey char(64)=NULL,@CandidatesJson nvarchar(max)=NULL,@MatchJson nvarchar(max)=NULL,
@Message nvarchar(200)=NULL,@Failure bit=0,@DelaySeconds int=0,@RelaxContext bit=0
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
BEGIN TRANSACTION;
DELETE dbo.GeographicLookupLease WHERE Lease=@Lease;
UPDATE dbo.LocationGeography SET Status=@Status,JobState=@JobState,RequestKey=@RequestKey,CandidatesJson=@CandidatesJson,
MatchJson=@MatchJson,Message=@Message,Attempts=Attempts+CONVERT(int,@Failure),
NextAttempt=DATEADD(second,@DelaySeconds,SYSUTCDATETIME()),Lease=NULL,LeaseUntil=NULL,
RelaxedGeneration=CASE WHEN @RelaxContext=1 THEN Generation ELSE RelaxedGeneration END
WHERE LocationID=@LocationID AND Generation=@Generation AND Lease=@Lease AND Confirmed=0;
IF @@ROWCOUNT=1 AND @RequestKey IS NOT NULL AND @CandidatesJson IS NOT NULL
BEGIN
UPDATE dbo.GeographicCache WITH(UPDLOCK,SERIALIZABLE) SET CandidatesJson=@CandidatesJson,ResolvedAt=SYSUTCDATETIME() WHERE RequestKey=@RequestKey;
IF @@ROWCOUNT=0 INSERT dbo.GeographicCache(RequestKey,CandidatesJson)VALUES(@RequestKey,@CandidatesJson);
END;
COMMIT;
END;
GO
-- Recovery reuses cached responses without charging the location allowance again.
CREATE OR ALTER PROCEDURE dbo.Geography_Retry @ProjectID int,@UserID int,@LocationID int,@Generation bigint,@ReplaceConfirmed bit=0 AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
BEGIN TRANSACTION;
DECLARE @Key char(64),@Valid bit=0;
SELECT @Key=g.RequestKey,@Valid=1 FROM dbo.LocationGeography g WITH(UPDLOCK,HOLDLOCK) JOIN dbo.Locations l ON l.LocationID=g.LocationID
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND g.LocationID=@LocationID AND g.Generation=@Generation AND g.IsExcluded=0
AND (g.Confirmed=0 OR @ReplaceConfirmed=1) AND g.Status IN('Unresolved','Needs confirmation','Resolved');
IF @Valid=0 THROW 51000,'Retry is unavailable. Refresh the geographical status.',1;
DECLARE @Cost int=CASE WHEN EXISTS(SELECT 1 FROM dbo.GeographicCache WHERE RequestKey=@Key) THEN 0 ELSE 1 END;
EXEC dbo.Geography_BatchPermit @UserID,@Cost;
UPDATE dbo.LocationGeography SET Status='Pending',JobState='Queued',Attempts=0,NextAttempt=SYSUTCDATETIME(),Lease=NULL,LeaseUntil=NULL,
Generation=Generation+1,Confirmed=0,CandidatesJson=NULL,MatchJson=NULL,Message='Recovery lookup queued; cached responses will be reused.',LastRetry=SYSUTCDATETIME()
WHERE LocationID=@LocationID AND Generation=@Generation;
COMMIT;
END;
GO

View File

@ -66,7 +66,16 @@
</div>
<dialog id="mapsNewDialog"><form id="mapsNewForm"><h2>New map</h2><label>Name <input name="Name" maxlength="200" required autofocus /></label><label>What are you mapping? <select name="Kind">@foreach(var kind in PlotLine.Services.MapValidation.Kinds){<option>@kind</option>}</select></label><label>How would you like to begin? <select name="Starter"><option value="blank">Blank map</option><option value="land">Single land mass</option><option value="island">Large island</option><option value="islands">Island group</option><option value="two">Two land masses</option><option value="inland">Inland region</option><option value="local">City / local area</option></select></label><label>Parent map <select name="ParentMapID"><option value="">None</option>@foreach(var map in Model.Maps){<option value="@map.MapID">@map.Name</option>}</select></label><p>Starter layouts contain editable shapes only. You name and define your world.</p><div><button type="button" id="mapsNewCancel">Cancel</button><button type="submit">Create map</button></div></form></dialog>
<dialog id="mapsArrangeDialog"><h2>Arrange from relationships</h2><p>Preview an arrangement using directions and relative distances. Known distances never control spacing.</p><label><input type="checkbox" id="mapsOnlyNew" /> Arrange unplaced / new items only</label><p id="mapsArrangeWarnings"></p><button type="button" id="mapsArrangeCancel">Cancel</button><button type="button" id="mapsArrangeApply">Apply arrangement</button></dialog>
<dialog id="mapsGeographicDialog"><h2>Position geographically</h2><p>Preview shown on the map. Listed location markers will move; all other map objects retain their positions. North is up. Relative distances use one scale in both directions. Coincident places overlap.</p><div id="mapsGeographicSummary"></div><p>Apply adds one Undo step. Use Save to persist the map. You can drag markers afterwards.</p><button type="button" id="mapsGeographicCancel">Cancel</button><button type="button" id="mapsGeographicApply">Apply positions</button></dialog>
<dialog id="mapsGeographicDialog" aria-labelledby="mapsGeographicTitle">
<h2 id="mapsGeographicTitle">Position geographically</h2>
<p id="mapsGeographicMessage" role="status"></p>
<div id="mapsGeographicPreview" aria-label="Proposed geographical arrangement"></div>
<p>Preview only · North ↑ · One geographical scale in both directions. Coincident places overlap.</p>
<details id="mapsGeographicList"><summary>Locations and lookup status</summary><div id="mapsGeographicSummary"></div></details>
<p id="mapsGeographicRequestStatus" role="status"></p>
<div class="maps-geographic-actions"><button type="button" id="mapsGeographicRequest">Request missing lookups</button><button type="button" id="mapsGeographicRefresh">Refresh status</button><button type="button" id="mapsGeographicCancel">Cancel</button><button type="button" id="mapsGeographicApply">Apply positions</button></div>
<p>Apply closes this preview and adds one Undo step. Use Save to persist the map; you can drag markers afterwards.</p>
</dialog>
</section>
@Html.AntiForgeryToken()
<script id="mapsBootstrap" type="application/json">@Html.Raw(JsonSerializer.Serialize(new { projectId = Model.Project.ProjectID, maps = Model.Maps, locations = Model.Locations, floorPlans = Model.FloorPlans, referenceImages = Model.ReferenceImages, document = Model.Document }, new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>

View File

@ -37,3 +37,11 @@ html[data-standalone=true]:has(#mapsApp) .pd-ribbon-panel:not([hidden]){min-heig
.maps-reference-image:focus-visible{outline:2px solid var(--maps-selection,#136883);outline-offset:3px}
#mapsDefine{width:100%;margin-bottom:5px}
/* Keep the proposal visible inside the confirmation surface instead of behind its backdrop. */
.maps-app #mapsGeographicDialog{width:min(1000px,96vw);max-width:96vw;max-height:94dvh;overflow:auto;padding:18px}
#mapsGeographicPreview{height:clamp(180px,42dvh,430px);border:1px solid var(--map-line);border-radius:6px;overflow:hidden;background:var(--maps-canvas-bg,#c9dfdf)}
#mapsGeographicPreview svg{width:100%;height:100%;display:block;pointer-events:none}
#mapsGeographicSummary{max-height:160px;overflow:auto}
#mapsGeographicSummary p{margin:4px 0}
.maps-geographic-actions{display:flex;flex-wrap:wrap;gap:6px;position:sticky;bottom:0;background:var(--map-panel);padding:6px 0}

View File

@ -10,23 +10,24 @@
const result=await response.json().catch(()=>null);
if(!response.ok||response.redirected)throw Error(result?.message||'Could not update geographical match.');
await load();
if(result?.message)status.textContent=result.message;
if(result?.message){const p=document.createElement('p');p.setAttribute('role','status');p.textContent=result.message;body.prepend(p);}
}
function button(label,action){const b=document.createElement('button');b.type='button';b.className='btn btn-outline-secondary btn-sm';b.textContent=label;b.onclick=async()=>{b.disabled=true;try{await action();}catch(e){status.textContent=e.message;b.disabled=false;}};body.append(b);}
function kind(m){return m.PlaceID?.startsWith('node:')?'Point location':/^(way|relation):/.test(m.PlaceID||'')?'Area location':'';}
function line(text){const p=document.createElement('p');p.textContent=text;body.append(p);}
async function load(){
const response=await fetch('/Geography/State?'+new URLSearchParams({projectId,locationId}),{cache:'no-store'});
if(!response.ok||response.redirected)throw Error('Geographical status unavailable.');
const rows=await response.json(),state=rows[0];
status.textContent=state?.status||'Pending';body.replaceChildren();
status.textContent=state?.status==='Pending'?({'Awaiting hierarchy request':'Not requested','Queued':state.attempts?'Retry scheduled':'Queued','Processing':'Looking up','Waiting configuration':'Lookup disabled'}[state.jobState]||'Pending'):(state?.status||'Not requested');body.replaceChildren();
if(!state){line('Awaiting geographical classification.');return;}
if(state.message)line(state.message);
if(!state.isExcluded)button('Resolve this arranged hierarchy (up to 20 places)',()=>change('Hierarchy',{}));
button(state.isExcluded?'Enable automatic geographical lookup':'Exclude automatic geographical lookup',()=>change('Exclude',{generation:state.generation,isExcluded:!state.isExcluded}));
if(state.matchJson){const m=JSON.parse(state.matchJson);line(`${m.Name} · ${m.AdministrativeNames.join(', ')} · ${m.CountryCode}`);line(`${m.Latitude}, ${m.Longitude}`);line(m.Attribution);}
if(state.matchJson){const m=JSON.parse(state.matchJson);line(`${m.Name}${kind(m)?' · '+kind(m):''} · ${m.AdministrativeNames.join(', ')} · ${m.CountryCode}`);line(`${m.Latitude}, ${m.Longitude}`);line(m.Attribution);}
if(state.status==='Needs confirmation'){
const candidates=JSON.parse(state.candidatesJson||'[]');
candidates.forEach((m,index)=>button(`${m.Name} · ${m.AdministrativeNames.join(', ')} · ${m.CountryCode} (${m.Latitude}, ${m.Longitude}) — ${m.Attribution}`,()=>change('Confirm',{generation:state.generation,candidateIndex:index})));
candidates.forEach((m,index)=>button(`${m.Name}${kind(m)?' · '+kind(m):''} · ${m.AdministrativeNames.join(', ')} · ${m.CountryCode} (${m.Latitude}, ${m.Longitude}) — ${m.Attribution}`,()=>change('Confirm',{generation:state.generation,candidateIndex:index})));
}
if(state.status==='Resolved')button('Change geographical match',()=>change('Retry',{generation:state.generation,replaceConfirmed:true}));
if(['Unresolved','Needs confirmation'].includes(state.status))button('Retry geographical lookup',()=>change('Retry',{generation:state.generation}));

View File

@ -10,12 +10,14 @@
if(!f.locationID)continue;
const state=states.find(s=>s.locationID===f.locationID);
let match=null;try{match=JSON.parse(state?.matchJson||'null');}catch{}
const reason=f.isLocked?'Locked':f.geometryClass!=='Marker'?'Only location markers can be positioned':state?.status!=='Resolved'?(state?.status||'Pending'):!match?'Unresolved':null;
if(reason){skipped.push({name:f.name,reason});continue;}
const pendingLabel=state?.status==='Pending'?({'Awaiting hierarchy request':'Not requested','Queued':state.attempts?'Retry scheduled':'Queued','Processing':'Looking up','Waiting configuration':'Lookup disabled'}[state.jobState]||'Pending'):state?.status;
const reason=f.isLocked?'Locked':f.geometryClass!=='Marker'?'Only location markers can be positioned':state?.status!=='Resolved'?(pendingLabel||'Pending'):!match?'Unresolved':null;
if(reason){skipped.push({name:f.name,reason,locationID:f.locationID,message:state?.message,canRequest:reason==='Not requested'});continue;}
if(!Number.isFinite(match.Latitude)||!Number.isFinite(match.Longitude)||Math.abs(match.Latitude)>90||Math.abs(match.Longitude)>180){skipped.push({name:f.name,reason:'Invalid geographical coordinates'});continue;}
points.push({feature:f,lat:match.Latitude*rad,lon:match.Longitude*rad,attribution:match.Attribution});
}
if(!points.length)return {features:output,positioned:[],skipped};
const positioned=points.map(p=>({name:p.feature.name,locationID:p.feature.locationID,featureID:p.feature.featureID,attribution:p.attribution}));
if(new Set(positioned.map(p=>p.locationID)).size<2)return {features:output,positioned,skipped,canApply:false,message:'At least two different resolved, unlocked locations are required. Request unsubmitted lookups or confirm matches in Location Details, then refresh status.'};
const sin=points.reduce((s,p)=>s+Math.sin(p.lon),0),cos=points.reduce((s,p)=>s+Math.cos(p.lon),0);
if(Math.hypot(sin,cos)<1e-9)throw Error('These locations span too much of the world. Use separate regional maps.');
const lon0=Math.atan2(sin,cos),lat0=points.reduce((s,p)=>s+p.lat,0)/points.length;
@ -30,7 +32,8 @@
const pad=Math.min(80,bounds.w*.12,bounds.h*.12),w=bounds.w-2*pad,h=bounds.h-2*pad;
const scale=Math.min(right-left>1e-6?w/(right-left):Infinity,bottom-top>1e-6?h/(bottom-top):Infinity);
for(const p of points){p.feature.x=bounds.x+bounds.w/2+(p.x-(left+right)/2)*(Number.isFinite(scale)?scale:0);p.feature.y=bounds.y+bounds.h/2+(p.y-(top+bottom)/2)*(Number.isFinite(scale)?scale:0);p.feature.isPlaced=true;}
return {features:output,positioned:points.map(p=>({name:p.feature.name,attribution:p.attribution})),skipped};
const changes=points.filter(p=>{const before=features.find(f=>f.featureID===p.feature.featureID);return Math.abs(before.x-p.feature.x)>1e-6||Math.abs(before.y-p.feature.y)>1e-6||!before.isPlaced;}).length;
return {features:output,positioned,skipped,canApply:changes>0,message:changes?`${changes} location markers will move. Other map objects retain their positions.`:'These places are already in the proposed positions. No changes are needed.'};
}
root.PlotDirectorGeography={position};
if(typeof module!=='undefined')module.exports={position};

View File

@ -308,8 +308,8 @@
$('mapsRename').onclick=async()=>{if(!doc)return;const answer=await window.PlotDirectorDialogs.choose({title:'Rename map',message:'Choose a name for this map.',input:{label:'Map name',value:doc.map.name},actions:[{label:'Rename',value:'rename',className:'btn-primary'},{label:'Cancel',value:'cancel'}]});if(answer?.value==='rename'&&answer.input.trim())safeEdit(()=>{doc.map.name=answer.input.trim().slice(0,200);crumbs();});};
$('mapsDuplicate').onclick=async()=>{if(!doc||busy||preview)return;if(dirty){requestLeave(()=>$('mapsDuplicate').click());return;}try{const result=await request('Create',{ProjectID:boot.projectId,Name:doc.map.name+' copy',Kind:doc.map.kind,...(doc.map.parentMapID?{ParentMapID:doc.map.parentMapID}:{})});const d=clone(doc);d.map.mapID=result.id;d.map.name+=' copy';d.map.revision=0;d.features.forEach(f=>f.createLocation=false);await request('Save',d,true);dirty=false;location.href=url(result.id);}catch(error){status(error.message,true);}};
$('mapsDelete').onclick=async()=>{if(!doc||busy||preview)return;const answer=await window.PlotDirectorDialogs.choose({title:'Delete map?',message:`Delete “${doc.map.name}”? Detailed child maps will become top-level maps. Story Locations, Floor Plans and project reference images are kept.`,actions:[{label:'Delete map',value:'delete',className:'btn-danger'},{label:'Cancel',value:'cancel'}]});if(answer?.value!=='delete')return;try{await request('Delete',{projectId:boot.projectId,id:doc.map.mapID,revision:doc.map.revision});dirty=false;location.href=url();}catch(error){status(error.message,true);}};
$('mapsGeographic').onclick=async()=>{
if(!doc||busy||preview||drag||mode!=='create'||window.PlotDirectorMapAppearance?.adjusting)return;
async function geographicPreview(){
if(!doc||busy||drag||mode!=='create'||window.PlotDirectorMapAppearance?.adjusting)return;
busy=true;updateButtons();const before=snapshot();
try{
const response=await fetch('/Geography/State?projectId='+boot.projectId,{cache:'no-store'});
@ -318,23 +318,53 @@
if(snapshot()!==before)throw Error('The map changed while loading. Try positioning again.');
const result=window.PlotDirectorGeography.position(doc.features,states,view);
const summary=$('mapsGeographicSummary');summary.replaceChildren();
const add=text=>{const p=document.createElement('p');p.textContent=text;summary.append(p);};
add(result.positioned.length+' location markers will move.');
for(const item of result.positioned)add('Move: '+item.name);
for(const item of result.skipped)add('Keep: '+item.name+' — '+item.reason);
const add=(text,id)=>{const p=document.createElement('p');p.textContent=text;if(id){const link=document.createElement('a');link.href='/Locations/Details/'+id;link.target='_blank';link.rel='noopener';link.textContent=' Inspect location';p.append(link);}summary.append(p);};
$('mapsGeographicMessage').textContent=result.message+(result.skipped.length?' '+result.skipped.length+' linked locations will stay unchanged; see their status below.':'');
for(const item of result.positioned)add((result.canApply?'Move: ':'Ready: ')+item.name);
for(const item of result.skipped)add('Keep: '+item.name+' — '+item.reason,item.locationID);
for(const attribution of new Set(result.positioned.map(p=>p.attribution).filter(Boolean)))add(attribution);
preview=result;render();$('mapsGeographicApply').disabled=!result.positioned.length;
$('mapsGeographicDialog').showModal();
}catch(error){status(error.message,true);}finally{busy=false;updateButtons();}
preview=result;render();
// Render the actual proposed canvas inside the dialog. It remains a visual clone, never editable state.
const drawing=svg.cloneNode(true),ids=new Map();
for(const node of [drawing,...drawing.querySelectorAll('[id]')])if(node.id){ids.set(node.id,'geographic-preview-'+node.id);node.id='geographic-preview-'+node.id;}
for(const node of [drawing,...drawing.querySelectorAll('*')]){
node.removeAttribute('tabindex');node.removeAttribute('data-feature-id');
for(const attribute of [...node.attributes]){
let value=attribute.value;
for(const [id,replacement]of ids){value=value.replaceAll('url(#'+id+')','url(#'+replacement+')');if(value==='#'+id)value='#'+replacement;}
if(value!==attribute.value)node.setAttribute(attribute.name,value);
}
}
drawing.setAttribute('viewBox',`${view.x} ${view.y} ${view.w} ${view.h}`);drawing.setAttribute('role','img');drawing.setAttribute('aria-label','Proposed positions, north up');
$('mapsGeographicPreview').replaceChildren(drawing);
$('mapsGeographicApply').disabled=!result.canApply;
$('mapsGeographicRequest').hidden=!result.skipped.some(p=>p.canRequest);
$('mapsGeographicList').open=!result.canApply||result.skipped.length>0;
if(!$('mapsGeographicDialog').open)$('mapsGeographicDialog').showModal();
}catch(error){preview=null;render();$('mapsGeographicApply').disabled=true;$('mapsGeographicPreview').replaceChildren();status(error.message,true);$('mapsGeographicRequestStatus').textContent=error.message;}finally{busy=false;updateButtons();}
}
$('mapsGeographic').onclick=()=>{if(preview)return;$('mapsGeographicRequestStatus').textContent='';geographicPreview();};
$('mapsGeographicRefresh').onclick=geographicPreview;
$('mapsGeographicRequest').onclick=async()=>{
if(busy||!preview)return;
const ids=[...new Set(preview.skipped.filter(p=>p.canRequest).map(p=>p.locationID))];
if(!ids.length)return;
busy=true;$('mapsGeographicRequest').disabled=true;
try{
const data=new URLSearchParams({projectId:boot.projectId});ids.forEach(id=>data.append('locationIds',id));
const response=await fetch('/Geography/RequestLocations',{method:'POST',headers:{RequestVerificationToken:token},body:data});
const result=await response.json().catch(()=>null);if(!response.ok||response.redirected||!result)throw Error(result?.message||'Could not request these lookups.');
$('mapsGeographicRequestStatus').textContent=result.message;
}catch(error){$('mapsGeographicRequestStatus').textContent=error.message;}finally{busy=false;$('mapsGeographicRequest').disabled=false;await geographicPreview();}
};
function cancelGeographic(){preview=null;$('mapsGeographicDialog').close();render();updateButtons();}
function cancelGeographic(){if(busy)return;preview=null;$('mapsGeographicDialog').close();$('mapsGeographicPreview').replaceChildren();render();updateButtons();}
$('mapsGeographicCancel').onclick=cancelGeographic;
$('mapsGeographicDialog').oncancel=e=>{e.preventDefault();cancelGeographic();};
$('mapsGeographicApply').onclick=()=>{
if(!preview?.positioned?.length||busy||mode!=='create')return;
if(!preview?.canApply||busy||mode!=='create')return;
const result=preview;preview=null;checkpoint();doc.features=result.features;
changed('Geographical positions applied. Save to persist; Undo restores previous positions.');
$('mapsGeographicDialog').close();render();details();updateButtons();
$('mapsGeographicDialog').close();$('mapsGeographicPreview').replaceChildren();render();details();updateButtons();
};
$('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;previewArrange();$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange;
function cancelArrange(){preview=null;$('mapsArrangeDialog').close();render();updateButtons();}