PlotDirector/PlotLine.Tests/Browser/geography-development.cjs

77 lines
8.8 KiB
JavaScript

/* 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;});