Enforce hierarchy integrity in traditional location saves and qualify release

This commit is contained in:
Nick Beckley 2026-11-27 12:13:28 +00:00
parent 6a90a71e73
commit 7e27aba3ce
18 changed files with 196 additions and 37 deletions

View File

@ -20,7 +20,10 @@ Migration **335_LocationsWorkspace.sql** adds nullable classification (Real/Fict
NULL is Unclassified), four compatible canonical types (Planet, District, Natural Feature, City),
and targeted workspace procedures. No existing type or classification is replaced. Quick Add and
Word Companion exclusion are existing quick switches; detection priority remains in Edit.
The project export selector and `LocationItem` retain classification through backup/restore.
Migration **336_LocationSaveHierarchyIntegrity.sql** also closes the traditional full-form/import
writer’s cycle and cross-project loophole, using the same project-first lock order. Unchanged
historical parents remain intact. The project export selector and `LocationItem` retain
classification through backup/restore.
The established merge now also preserves maps and conflicting descriptions, including when
opened through the traditional Details page. The workspace adds conflict review and version checks.
No AI processing or geocoding is invoked by these workspace commands.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 226 KiB

After

Width:  |  Height:  |  Size: 227 KiB

View File

@ -2,10 +2,10 @@
"status": "passed",
"runs": [
{
"clone": 4,
"clone": 6,
"starting_schema_sha256": "dc6afafb8c25fd63d98a97d016402ddda7474fdfa296a18722b3ddc2569ecb91",
"resulting_schema_sha256": "53a1d38ea01c4a0c6f601dc280a3dbdf706060b05b3ce9e9dd45ca83312ccbd4",
"executed": 1,
"resulting_schema_sha256": "5ae0ab8cfee2759dd2a1e967e888b277855b93efd8a56dfca15d2eb4e75ca946",
"executed": 2,
"unchanged_original_tables": 208,
"existing_canonical_types_unchanged": true,
"only_data_addition": "four canonical location types",
@ -15,10 +15,10 @@
}
},
{
"clone": 5,
"clone": 7,
"starting_schema_sha256": "dc6afafb8c25fd63d98a97d016402ddda7474fdfa296a18722b3ddc2569ecb91",
"resulting_schema_sha256": "53a1d38ea01c4a0c6f601dc280a3dbdf706060b05b3ce9e9dd45ca83312ccbd4",
"executed": 1,
"resulting_schema_sha256": "5ae0ab8cfee2759dd2a1e967e888b277855b93efd8a56dfca15d2eb4e75ca946",
"executed": 2,
"unchanged_original_tables": 208,
"existing_canonical_types_unchanged": true,
"only_data_addition": "four canonical location types",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 189 KiB

View File

@ -5,3 +5,7 @@ PASS cross-project parent rejection
PASS stale write rejection
PASS unauthorized mutation rejection
PASS transactional merge preserves conflicting descriptions, source, classification, children, map geometry, floor-plan links, scene assignments, aliases and non-hierarchical relationships
PASS traditional save rejects descendant cycles
PASS traditional save rejects self-parent assignment
PASS traditional save rejects mismatched location/project
PASS traditional save preserves unchanged archived-parent references, classification and import transaction

Binary file not shown.

Before

Width:  |  Height:  |  Size: 175 KiB

After

Width:  |  Height:  |  Size: 180 KiB

View File

@ -46,6 +46,11 @@ A stale receipt cannot overwrite later edits. The browser updates its directory,
without navigating/reloading. Live invalidations refresh other windows; dirty descriptions defer
refresh. Explicit Save/Cancel and discard confirmation protect unsaved descriptions.
Migration 336 gives the traditional `Location_Save` procedure the same project-first locking,
project membership and cycle checks, while preserving unchanged historical archived-parent references.
Its alias writes stay transactional; import callers retain their outer transaction. Full-form validation
errors return the posted draft with an inline message rather than silently moving a self-parent to root.
`Location_WorkspaceCreate` validates ownership/parent and creates a child transactionally from only
a name. Naming matches existing forms (required, 200 characters; repeated names are allowed).
Aliases and manuscript text are never rewritten by rename. Traditional creation remains available.

View File

@ -7,7 +7,7 @@ const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Da
await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await page.locator('form button[type=submit]').click();await page.waitForURL(base+'/Projects');
if(setup){assert(!identity.ProjectID);await page.goto(base+'/Projects/Create');await page.locator('[name=ProjectName]').fill('Locations acceptance · disposable world');await page.getByRole('button',{name:'Save project',exact:true}).click();await page.waitForURL(/\/Projects\/Details\/\d+/);identity.ProjectID=Number(page.url().split('/').pop());await page.goto(base+`/Books/Create?projectId=${identity.ProjectID}`);await page.locator('[name=BookTitle]').fill('Locations acceptance fixture');await page.getByRole('button',{name:'Save book',exact:true}).click();await page.waitForURL(/\/Books\/Details\/\d+/);identity.BookID=Number(page.url().split('/').pop());fs.writeFileSync(file,JSON.stringify(identity,null,2),{mode:0o600});console.log('PASS dedicated fixture project/book created through normal Development forms.');return;}
assert(identity.ProjectID&&identity.BookID);const q=`projectId=${identity.ProjectID}`;
const api=async(action,body)=>page.evaluate(async({action,body})=>{const response=await fetch('/LocationWorkspace/'+action,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':document.querySelector('[data-location-token] [name=__RequestVerificationToken]').value},body:JSON.stringify(body)});return{status:response.status,body:await response.json()};},{action,body});
const api=async(action,body)=>page.evaluate(async({action,body})=>{const response=await fetch('/LocationWorkspace/'+action,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':document.querySelector('[data-location-token] [name=__RequestVerificationToken]').value},body:JSON.stringify(body)});return{status:response.status,body:await response.json().catch(()=>({}))};},{action,body});
const directory=async()=>{const response=await page.request.get(base+`/LocationWorkspace/Directory?${q}`);assert.equal(response.status(),200);return response.json();};
await page.goto(base+`/Locations?${q}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();let data=await directory();assert.equal(data.locations.length,0,'only an empty dedicated project may be populated');
const created=await api('Create',{projectId:identity.ProjectID,name:'Meridian acceptance',parentId:null});assert.equal(created.status,200);const id=created.body.id;await page.reload();const row=()=>page.locator(`[data-location-id="${id}"]`);await row().locator('[data-location-name]').click();
@ -18,10 +18,11 @@ const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Da
await row().focus();await page.keyboard.press('F2');await row().getByRole('textbox',{name:'Location name'}).fill('Meridian renamed');await row().getByRole('textbox',{name:'Location name'}).press('Enter');await row().getByRole('button',{name:'Meridian renamed',exact:true}).waitFor();data=await directory();assert.equal(data.locations.find(r=>r.id===child.id).parent,id);
await row().locator('[data-location-name]').click();await page.getByRole('button',{name:'Edit description',exact:true}).click();await page.getByRole('textbox',{name:'Location description'}).fill('Author-controlled synthetic description.');await page.locator('[data-details]').getByRole('button',{name:'Save',exact:true}).click();await page.waitForTimeout(200);data=await directory();assert.equal(data.locations.find(r=>r.id===id).description,'Author-controlled synthetic description.');
const bulk=await api('Assign',{projectId:identity.ProjectID,attribute:'quickAdd',changes:data.locations.map(r=>({id:r.id,value:'1',version:r.version}))});assert.equal(bulk.status,200);assert.equal(bulk.body.changes.length,2);assert(bulk.body.undoToken);const restored=await api('Undo',{token:bulk.body.undoToken});assert.equal(restored.status,200);data=await directory();assert(data.locations.every(r=>r.quickAdd==='0'));
const current=data.locations.find(r=>r.id===id),bad=await api('Assign',{projectId:identity.ProjectID,attribute:'parent',changes:[{id,value:String(child.id),version:current.version}]});assert.equal(bad.status,409);const unauthorised=await api('Assign',{projectId:2147483647,attribute:'classification',changes:[{id,value:'Real',version:current.version}]});assert.equal(unauthorised.status,403);
const current=data.locations.find(r=>r.id===id),bad=await api('Assign',{projectId:identity.ProjectID,attribute:'parent',changes:[{id,value:String(child.id),version:current.version}]});assert.equal(bad.status,409);const unauthorised=await api('Assign',{projectId:2147483647,attribute:'classification',changes:[{id,value:'Real',version:current.version}]});assert([403,404].includes(unauthorised.status));
const out='/tmp/pd-locations-evidence';await page.screenshot({path:out+'/development-workspace.png'});
await page.goto(base+`/Locations/Edit/${id}`);await page.locator('[name=ParentLocationID]').selectOption(String(child.id));await page.getByRole('button',{name:'Save location',exact:true}).click();await page.waitForLoadState();assert.match(await page.locator('[data-valmsg-summary=true]').textContent(),/descendant/);data=await directory();assert.equal(data.locations.find(r=>r.id===id).parent,null);assert.equal(data.locations.find(r=>r.id===id).description,'Author-controlled synthetic description.');
const checks=[];for(const route of [`/Characters?${q}`,`/Names?${q}`,`/RelationshipMap?${q}`,`/Maps?${q}`,`/FloorPlans?${q}`,`/StoryAssets?${q}`,`/Locations/Details/${id}`,`/Locations/Edit/${id}`,`/Writer?${q}&bookId=${identity.BookID}`]){const response=await page.goto(base+route);assert.equal(response.status(),200,route);assert(!page.url().includes('/Account/'));checks.push(route.split('?')[0]);}
await page.goto(base+`/Locations/Details/${id}`);await page.locator('[name=ToLocationID]').selectOption(String(child.id));await page.locator('[name=Notes]').fill('Disposable non-hierarchical relationship');await page.getByRole('button',{name:'Add relationship',exact:true}).click();await page.waitForLoadState();assert(await page.getByText('Disposable non-hierarchical relationship',{exact:true}).count());
await page.goto(base+`/Locations?${q}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();await page.getByRole('button',{name:'Expand all',exact:true}).click();await page.locator(`[data-location-id="${child.id}"]`).getByRole('button',{name:'Actions for Observatory acceptance'}).click();await page.getByRole('menuitem',{name:'Merge with another location…',exact:true}).click();await page.getByRole('combobox',{name:'Surviving location'}).selectOption(String(id));await page.locator('[data-location-dialog] input[type=checkbox]').check();await page.locator('[data-dialog-save]').click();await page.locator('[data-location-dialog]').waitFor({state:'hidden'});data=await directory();assert.equal(data.locations.length,1);assert.equal(data.locations[0].id,id);assert.equal(data.locations[0].description,'Author-controlled synthetic description.');
fs.writeFileSync(out+'/development-smoke.json',JSON.stringify({status:'passed',target:'Development',checks:['real Directory/Create/Assign/Undo/Merge endpoints','bulk assignment and protected Undo','normal non-hierarchical relationship form','reviewed merge archives source and retains survivor','inline child Enter-save','classification','inline rename preserves child identifiers','description save','server cycle rejection','cross-project mutation rejection','actual second-window live invalidation',...checks]},null,2));console.log('PASS authenticated Development workspace mutations, hierarchy safeguards, cross-window live updates and related route smoke; disposable data only.');
fs.writeFileSync(out+'/development-smoke.json',JSON.stringify({status:'passed',target:'Development',checks:['real Directory/Create/Assign/Undo/Merge endpoints','bulk assignment and protected Undo','normal non-hierarchical relationship form','reviewed merge archives source and retains survivor','inline child Enter-save','classification','inline rename preserves child identifiers','description save','server cycle rejection','traditional full Edit rejects cycles without losing posted data','cross-project mutation rejection','actual second-window live invalidation',...checks]},null,2));console.log('PASS authenticated Development workspace mutations, hierarchy safeguards, cross-window live updates and related route smoke; disposable data only.');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -23,8 +23,8 @@ const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:52
const noOpRequests=requests.length;await drag(attribute('type','1').locator('button').first(),row(1));assert.equal(requests.length,noOpRequests);rejectNext=true;await drag(attribute('type','6').locator('button').first(),row(1));assert.equal(records[0].type,'1');assert.match(await page.locator('[data-workspace-error]').textContent(),/concurrent/);
await row(2).locator('[data-select-location]').check();await row(3).locator('[data-select-location]').check();const bulkStart=performance.now();await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert.equal(records[1].classification,'Real');assert.equal(records[2].classification,'Real');timings.bulkMs=Math.round(performance.now()-bulkStart);await shot('bulk-assignment');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(60);assert.equal(records[1].classification,'');
if(count===50){
await row(1).locator('[data-expand-id]').click();const from=await row(14).locator('[data-drag-location]').boundingBox(),to=await row(1).boundingBox();
await page.mouse.move(from.x+from.width/2,from.y+from.height/2);await page.mouse.down();await page.mouse.move(from.x+from.width/2+9,from.y+from.height/2,{steps:3});await page.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:10});await page.waitForTimeout(850);assert.equal(await row(1).getAttribute('aria-expanded'),'true');await shot('hover-reparent');await page.mouse.move(to.x+to.width/2+1,to.y+to.height/2);await page.mouse.up();await page.waitForTimeout(150);assert.equal(records[13].parent,1);await row(14).locator('[data-drag-location]').dragTo(page.locator('[data-root-drop]'));await page.waitForTimeout(150);assert.equal(records[13].parent,null);await shot('root-drop');
await row(1).locator('[data-expand-id]').click();await page.locator('.locations-centre').evaluate(n=>n.scrollTop=0);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));const from=await row(14).locator('[data-drag-location]').boundingBox(),to=await row(1).boundingBox();
await page.mouse.move(from.x+from.width/2,from.y+from.height/2);await page.mouse.down();await page.mouse.move(from.x+from.width/2+9,from.y+from.height/2,{steps:3});await page.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:10});await page.mouse.move(to.x+to.width/2+1,to.y+to.height/2+1);await page.waitForTimeout(850);assert.equal(await row(1).getAttribute('aria-expanded'),'true');await shot('hover-reparent');await page.mouse.move(to.x+to.width/2+1,to.y+to.height/2);await page.mouse.up();await page.waitForTimeout(150);assert.equal(records[13].parent,1);await row(14).locator('[data-drag-location]').dragTo(page.locator('[data-root-drop]'));await page.waitForTimeout(150);assert.equal(records[13].parent,null);await shot('root-drop');
const beforeInvalid=requests.length;await row(1).locator('[data-drag-location]').dragTo(row(11));await page.waitForTimeout(80);assert.equal(requests.length,beforeInvalid);assert.equal(records[0].parent,null);
}
await page.locator('[data-clear-selection]').click();const reparentStart=performance.now();await row(5).locator('[data-drag-location]').dragTo(row(3));await page.waitForTimeout(100);assert.equal(records[4].parent,3);assert.equal(records[5].parent,5);timings.reparentMs=Math.round(performance.now()-reparentStart);await shot('reparenting');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(100);assert.equal(records[4].parent,4);

View File

@ -108,3 +108,28 @@ IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID=@feat
IF (SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map)<>1 OR (SELECT LocationID FROM dbo.FloorPlans WHERE FloorPlanID=@plan)<>@b THROW 51000,'Map revision/floor-plan association not preserved.',1;
ROLLBACK;
PRINT 'PASS transactional merge preserves conflicting descriptions, source, classification, children, map geometry, floor-plan links, scene assignments, aliases and non-hierarchical relationships';
-- Traditional forms/import repository cannot bypass hierarchy validation either (336).
BEGIN TRAN;
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Full-form cycle source');SET @a=SCOPE_IDENTITY();
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Full-form cycle child',@a);SET @b=SCOPE_IDENTITY();
BEGIN TRY EXEC dbo.Location_Save @LocationID=@a,@ProjectID=@p,@ParentLocationID=@b,@LocationName=N'Invalid cycle';THROW 51099,'Full-form cycle accepted.',1;
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH;
PRINT 'PASS traditional save rejects descendant cycles';
BEGIN TRAN;
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Full-form self source');SET @a=SCOPE_IDENTITY();
BEGIN TRY EXEC dbo.Location_Save @LocationID=@a,@ProjectID=@p,@ParentLocationID=@a,@LocationName=N'Invalid self parent';THROW 51099,'Full-form self-parent accepted.',1;
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH;
PRINT 'PASS traditional save rejects self-parent assignment';
BEGIN TRAN;
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Full-form scoped source');SET @a=SCOPE_IDENTITY();
BEGIN TRY EXEC dbo.Location_Save @LocationID=@a,@ProjectID=@other,@LocationName=N'Invalid project';THROW 51099,'Full-form cross-project update accepted.',1;
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH;
PRINT 'PASS traditional save rejects mismatched location/project';
BEGIN TRAN;
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Historical parent');SET @a=SCOPE_IDENTITY();
INSERT dbo.Locations(ProjectID,ParentLocationID,LocationName,Classification) VALUES(@p,@a,N'Historical child',N'Fictional');SET @b=SCOPE_IDENTITY();
UPDATE dbo.Locations SET IsArchived=1 WHERE LocationID=@a;
EXEC dbo.Location_Save @LocationID=@b,@ProjectID=@p,@ParentLocationID=@a,@LocationName=N'Edited historical child',@Description=N'Preserved historical containment';
IF @@TRANCOUNT<>1 OR NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@b AND ParentLocationID=@a AND Classification=N'Fictional' AND Description=N'Preserved historical containment') THROW 51000,'Traditional save changed historical parent/classification or escaped the outer transaction.',1;
ROLLBACK;
PRINT 'PASS traditional save preserves unchanged archived-parent references, classification and import transaction';

View File

@ -97,33 +97,43 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
[ValidateAntiForgeryToken]
public async Task<IActionResult> Save(LocationEditViewModel model)
{
if (!ModelState.IsValid)
{
var editModel = model.LocationID == 0
? await locations.GetCreateAsync(model.ProjectID)
: await locations.GetEditAsync(model.LocationID);
if (editModel is null)
{
return NotFound();
}
if (!ModelState.IsValid) return await InvalidEdit(model);
editModel.ParentLocationID = model.ParentLocationID;
editModel.LocationName = model.LocationName;
editModel.Aliases = model.Aliases;
editModel.LocationTypeID = model.LocationTypeID;
editModel.Description = model.Description;
editModel.ShowInQuickAddBar = model.ShowInQuickAddBar;
editModel.ExcludeFromCompanionDetection = model.ExcludeFromCompanionDetection;
editModel.DetectionPriority = model.DetectionPriority;
return View("Edit", editModel);
try
{
var before = model.LocationID > 0 ? await locations.GetEditAsync(model.LocationID) : null;
var locationId = await locations.SaveAsync(model);
if ((model.ParentLocationID.HasValue && (before is null || before.ParentLocationID != model.ParentLocationID))
|| (before is not null && (before.LocationName != model.LocationName || before.LocationTypeID != model.LocationTypeID)))
TempData["LocationMessage"] = await geography.SubmitAsync(model.ProjectID, locationId);
return RedirectToAction(nameof(Details), new { id = locationId });
}
catch (InvalidOperationException ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
return await InvalidEdit(model);
}
}
private async Task<IActionResult> InvalidEdit(LocationEditViewModel model)
{
var editModel = model.LocationID == 0
? await locations.GetCreateAsync(model.ProjectID)
: await locations.GetEditAsync(model.LocationID);
if (editModel is null)
{
return NotFound();
}
var before = model.LocationID > 0 ? await locations.GetEditAsync(model.LocationID) : null;
var locationId = await locations.SaveAsync(model);
if ((model.ParentLocationID.HasValue && (before is null || before.ParentLocationID != model.ParentLocationID))
|| (before is not null && (before.LocationName != model.LocationName || before.LocationTypeID != model.LocationTypeID)))
TempData["LocationMessage"] = await geography.SubmitAsync(model.ProjectID, locationId);
return RedirectToAction(nameof(Details), new { id = locationId });
editModel.ParentLocationID = model.ParentLocationID;
editModel.LocationName = model.LocationName;
editModel.Aliases = model.Aliases;
editModel.LocationTypeID = model.LocationTypeID;
editModel.Description = model.Description;
editModel.ShowInQuickAddBar = model.ShowInQuickAddBar;
editModel.ExcludeFromCompanionDetection = model.ExcludeFromCompanionDetection;
editModel.DetectionPriority = model.DetectionPriority;
return View("Edit", editModel);
}
[HttpPost]

View File

@ -547,6 +547,8 @@ public sealed class LocationRepository(ISqlConnectionFactory connectionFactory)
public async Task<int> SaveAsync(LocationItem location)
{
using var connection = connectionFactory.CreateConnection();
try
{
return await connection.QuerySingleAsync<int>(
"dbo.Location_Save",
new
@ -562,6 +564,11 @@ public sealed class LocationRepository(ISqlConnectionFactory connectionFactory)
location.DetectionPriority
},
commandType: CommandType.StoredProcedure);
}
catch (SqlException ex) when (ex.Number == 51012)
{
throw new InvalidOperationException(ex.Message, ex);
}
}
public async Task<IReadOnlyList<LocationAlias>> ListAliasesAsync(int locationId)

View File

@ -8379,7 +8379,7 @@ public sealed class LocationService(
{
LocationID = model.LocationID,
ProjectID = model.ProjectID,
ParentLocationID = model.ParentLocationID == model.LocationID ? null : model.ParentLocationID,
ParentLocationID = model.ParentLocationID,
LocationName = model.LocationName,
LocationTypeID = model.LocationTypeID,
Description = model.Description,

View File

@ -0,0 +1,104 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Keep the traditional full form and existing import repository on the same hierarchy rules.
CREATE OR ALTER PROCEDURE dbo.Location_Save
@LocationID int = NULL,
@ProjectID int,
@ParentLocationID int = NULL,
@LocationName nvarchar(200),
@LocationTypeID int = NULL,
@Description nvarchar(max) = NULL,
@ShowInQuickAddBar bit = 0,
@ExcludeFromCompanionDetection bit = 0,
@DetectionPriority int = 50
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- Match the workspace lock order before locking locations. Imports calling this
-- procedure inside an outer transaction retain that transaction's atomicity.
DECLARE @LockedProjectID int,@OldParentID int;
SELECT @LockedProjectID=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID;
IF @LockedProjectID IS NULL THROW 51012,'Location project unavailable.',1;
IF ISNULL(@LocationID,0)>0
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@LocationID AND ProjectID=@ProjectID)
THROW 51012,'Choose a location in this project.',1;
SELECT @OldParentID=ParentLocationID FROM dbo.Locations WHERE LocationID=@LocationID;
END;
-- Preserve unchanged historical parent references, including archived parents.
-- Any newly assigned parent must be active and in the same project.
IF ISNULL(@LocationID,0)=0 OR ISNULL(@OldParentID,0)<>ISNULL(@ParentLocationID,0)
BEGIN
IF @ParentLocationID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK)
WHERE LocationID=@ParentLocationID AND ProjectID=@ProjectID AND IsArchived=0)
THROW 51012,'Choose an active parent in this project.',1;
DECLARE @AncestorID int=@ParentLocationID,@NextAncestorID int;
DECLARE @Visited TABLE(ID int PRIMARY KEY);
WHILE @AncestorID IS NOT NULL
BEGIN
IF @AncestorID=@LocationID OR EXISTS(SELECT 1 FROM @Visited WHERE ID=@AncestorID)
THROW 51012,'A location cannot be its own parent or be moved beneath a descendant.',1;
INSERT @Visited VALUES(@AncestorID);
SET @NextAncestorID=NULL;
SELECT @NextAncestorID=ParentLocationID FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@AncestorID AND ProjectID=@ProjectID;
SET @AncestorID=@NextAncestorID;
END;
END;
SET @LocationName = LTRIM(RTRIM(@LocationName));
SET @DetectionPriority = COALESCE(@DetectionPriority, 50);
IF @LocationID IS NULL OR @LocationID = 0
BEGIN
INSERT dbo.Locations (ProjectID, ParentLocationID, LocationName, LocationTypeID, Description, ShowInQuickAddBar, ExcludeFromCompanionDetection, DetectionPriority)
VALUES (@ProjectID, @ParentLocationID, @LocationName, @LocationTypeID, @Description, @ShowInQuickAddBar, @ExcludeFromCompanionDetection, @DetectionPriority);
SET @LocationID = CAST(SCOPE_IDENTITY() AS int);
END
ELSE
BEGIN
UPDATE dbo.Locations
SET ParentLocationID = @ParentLocationID,
LocationName = @LocationName,
LocationTypeID = @LocationTypeID,
Description = @Description,
ShowInQuickAddBar = @ShowInQuickAddBar,
ExcludeFromCompanionDetection = @ExcludeFromCompanionDetection,
DetectionPriority = @DetectionPriority,
UpdatedDate = SYSUTCDATETIME()
WHERE LocationID = @LocationID AND ProjectID=@ProjectID;
END
IF NULLIF(@LocationName, N'') IS NOT NULL
AND NOT EXISTS
(
SELECT 1
FROM dbo.LocationAliases
WHERE LocationID = @LocationID
AND UPPER(LTRIM(RTRIM(Alias))) = UPPER(@LocationName)
)
BEGIN
INSERT dbo.LocationAliases (LocationID, Alias, SortOrder)
SELECT @LocationID,
@LocationName,
ISNULL(MAX(SortOrder), 0) + 10
FROM dbo.LocationAliases
WHERE LocationID = @LocationID;
END
COMMIT TRANSACTION;
SELECT @LocationID;
END TRY
BEGIN CATCH
IF XACT_STATE()<>0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
END;
GO