diff --git a/Docs/Locations/Acceptance.md b/Docs/Locations/Acceptance.md new file mode 100644 index 00000000..89b01804 --- /dev/null +++ b/Docs/Locations/Acceptance.md @@ -0,0 +1,163 @@ +# Locations workspace delivery and acceptance + +Implementation is complete. Development activation and authenticated smoke evidence will be +appended after the signed release is activated. Production is outside this task. + +## Delivered architecture + +The full-width directory has independently resizable/collapsible Attributes and Details panels, +an expandable tree and variable-height cards, search/filters/sibling sorting, selection and +bulk assignment, bidirectional attribute drag, branch/root drag moves with hover expansion, +inline rename, child creation, description Save/Cancel, and shared context menus. +The same records and commands drive both views. Traditional forms and non-hierarchical +relationship editing remain available. See [architecture and safeguards](Workspace.md). + +Reused: Dapper/stored procedures, canonical location records and aliases, project ownership roles, +`workspace-surface.js`, shared context menus/ribbon icons, `PlotDirector.toast`, protected Undo +receipts, existing merge reconciliation/audit, and Context invalidation notifications. + +Migration **335_LocationsWorkspace.sql** adds nullable classification (Real/Fictional/Fictionalised; +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. +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. + +## Verification + +- `dotnet build PlotLine.slnx`: passed, zero warnings/errors. +- Executable regression harness: **889 PASS**, successful exit. Existing Characters, Names, + Relationships, Maps/topology, Floor Plans, Assets, import, Context and shared focus contracts + remain covered by the existing harness; this is not a claim of exhaustive manual workflow testing. +- Actual compiled Razor and production CSS/JavaScript: Chromium browser and a genuinely installed + Chromium PWA under Xvfb. Collections of 50/200/500/1,000 records; deep chains, wide branches, + repeated names, complete long descriptions, map/floor-plan indicators. +- Physical attribute/location dragging, hover-expand reparenting, root drops and invalid target + rejection; bulk assignment, individual-value Undo, no-op assignment, simulated save failure, + inline rename Save/Escape, child creation, right-click/keyboard/visible menus, unsaved-description + protection, filters, cards, sorting, and a delayed live-refresh race. +- Both divider pointer drags and keyboard resizing; saved widths, collapsed panels, view, attribute + groups and expanded branches survive reload. View changes retain selection and filters. +- All seven available theme choices; 390/768/1024/1280/1440/1920-pixel viewport checks without + horizontal document overflow. Native physical Windows/Edge installation was not available. +- Focused SQL regressions run only on disposable clones and roll back: ancestor/descendant bulk + safety, root moves, exact original parents on Undo, no-op versions, cycle/unavailable/cross-project + parent rejection, unauthorized/stale writes, and targeted rename preserving scene assignment. + Merge preserves source records, descriptions, classification, children, aliases, authored + relationships, scene assignments, map feature IDs/geometry and floor-plan links. +- Real Dapper create/assignment/Undo and six directory result sets, including entry/exit-only + character scene assignments counted once. Actual typed project export and generic location JSON + restore retain a non-null classification. Restore fixture is rolled back and removed. +- Two fresh final-schema qualification clones produce identical schema hashes. All **208** other + original business tables retain fingerprints; existing LocationTypes rows are unchanged and the + only data addition is four canonical types. DBCC integrity and constraints pass (zero violations). + See [sanitised qualification](Evidence/database-qualification.json). + +## Performance + +Milliseconds, single representative passes on the isolated Razor host. Browser transport/data +mutations are synthetic; these are not authenticated network benchmarks. The richer after-workspace +also renders indicators, controls and descriptions. The large after fixtures include a 100-level +chain. Search/interaction timings include deliberate settling waits; no statistical speedup is claimed. + +| Locations | Old list load | New browser load | Installed PWA load | Expand all (browser) | Search (browser) | Cards (browser) | +|---:|---:|---:|---:|---:|---:|---:| +| 50 | 257 | 266 | 302 | 102 | 108 | 116 | +| 200 | 230 | 292 | 375 | 167 | 148 | 200 | +| 500 | 410 | 317 | 451 | 334 | 126 | 436 | +| 1000 | 609 | 445 | 729 | 636 | 163 | 1248 | + +The first cold post-build 50-record request measured **1,424 ms**; warm 50-record passes were about +266–302 ms. At 1,000 records the measured browser bulk interaction was 858 ms, rename 123 ms, +reparent 283 ms and selected-details 103 ms in one pass; later passes vary. Card rendering at this +scale is approximately 1.2 seconds with full descriptions. There is no card virtualization. +Raw passes: [before](Evidence/before.json), [after](Evidence/after-large.json), +[cold request](Evidence/after-cold-release.json), [PWA](Evidence/pwa-performance.json). + +Actual SQL/Dapper reads, on a disposable Development clone with 69 existing records in addition +to each synthetic collection: old simple list / new six-result directory = 25.5/82.1 ms (50), +41.2/18.3 ms (200), 55.9/41.2 ms (500), 71.3/68.1 ms (1,000). +The new read includes aliases, maps, floor plans, usage, types and relationship/character/asset +counts, without per-location queries. [Raw database results](Evidence/database-performance.txt). + +## Acceptance matrix + +“Passed” means exercised by the stated browser/SQL/harness checks, not merely compiled. + +| Requirement | Status | Evidence / boundary | +|---|---|---| +| Full-width three-panel workspace; responsive layouts | Passed | Rendered browser/PWA, viewport overflow checks | +| Both pointer/keyboard dividers; independent saved widths | Passed | Native pointer checks, reload assertions | +| Collapse/restore Attributes and Details | Passed | Both modes, reload assertions | +| Tree expansion, remembered branches, ancestral paths | Passed | Tree/search/reload checks | +| Native reparenting and hover-expanded branches | Passed | Native pointer test and hover screenshot | +| Root-level drop and invalid descendant target feedback | Passed | Native drop/no-write checks; SQL rejection | +| Bulk branch preservation and exact parent Undo | Passed | Transactional SQL fixture with different original parents | +| Server ownership, active-parent and cycle validation | Passed | Unauthorized, cross-project, unavailable and cycle SQL/HTTP contracts | +| Type/classification and existing quick switches | Passed | Browser assignments and SQL/Dapper round trip | +| Bidirectional attribute drag, selection and bulk assignment | Passed | Browser/PWA drag and selection checks | +| Counts, derived filters, aliases, branch search and clear | Passed | Rendered tests; authoritative batched SQL | +| Shared toast and version-protected Undo | Passed | Browser actions and real Dapper exact-version restore | +| No-op and failed-assignment preservation | Passed | No-request and simulated conflict checks; SQL version checks | +| F2/menu rename, Enter save, Escape cancel | Passed | Native keyboard/browser checks; scene IDs preserved | +| Direct child creation and description editing | Passed | Rendered dialog/details tests; unsaved draft checks | +| Context menus, visible menu and keyboard alternative | Passed | Browser right-click, Shift+F10, installed PWA | +| Hierarchy/cards, complete descriptions, variable heights | Passed | DOM height checks and rendered screenshots | +| Selection/filter preservation and branch-safe sorting | Passed | View/sibling-order checks | +| Multiple map/floor-plan associations and same-window links | Passed | Directory links and SQL preservation checks | +| Merge review, reconciliation and rollback safeguards | Passed | SQL data-integrity fixtures; workspace review implemented | +| Backup/export/restore retains optional classification | Passed | Actual typed export and generic restore round trip | +| No new AI, no manuscript focus writes | Passed | Command paths contain no AI/geography/focus calls; existing harness | +| Existing related workspace behavior | Passed | 889-check harness; authenticated route smoke pending activation | +| Live updates across actual Development windows | Not verified | Pending post-activation dedicated-account check | +| Development deployment and authenticated mutations | Not verified | Pending signed release activation | +| Every existing Context consumer with physical Word/PWA | Not verified | Existing contracts/hints preserved; physical Word unavailable | +| Windows/Edge installed-PWA behavior | Not verified | Linux Chromium browser + real installed PWA verified | +| Collections above 1,000; exhaustive keyboard/assistive-tech audit | Not verified | No claim beyond measured cases | +| New location image storage | Not implemented | No canonical location-image attribute exists; conditional scope only | +| New feature-level reveal inside Maps/Floor Plans | Not implemented | Existing routes select map/plan; their editors are unchanged | + +No unresolved failing check is known. The last two “Not implemented” items are conditional features +without an existing canonical field/route, not replacement representations or editor redesigns. + +## Rendered evidence + +All screenshots use controlled synthetic data, never the author's manuscripts/locations. + +| Demonstration | Screenshot | +|---|---| +| Baseline list | [Before](Evidence/before.png) | +| Complete workspace | [Browser](Evidence/workspace.png), [installed PWA](Evidence/pwa-workspace.png) | +| Populated multilevel hierarchy | [Hierarchy](Evidence/hierarchy.png) | +| Attribute assignment | [Assignment](Evidence/attribute-assignment.png) | +| Reparenting and hover expansion | [Move](Evidence/reparenting.png), [hover](Evidence/hover-reparent.png), [root drop](Evidence/root-drop.png) | +| Bulk assignment | [Bulk](Evidence/bulk-assignment.png) | +| Inline rename | [Rename](Evidence/inline-rename.png) | +| Context menu | [Menu](Evidence/context-menu.png) | +| Direct child creation | [Child](Evidence/create-child.png) | +| Editable Details | [Description](Evidence/details-edit.png) | +| Variable-size cards | [Cards](Evidence/cards.png), [PWA](Evidence/pwa-cards.png) | +| Search with ancestors | [Search](Evidence/search-context.png) | +| Map/floor-plan indicators | [Workspace](Evidence/workspace.png) | +| Resized panels | [Dividers](Evidence/resized-panels.png), [PWA](Evidence/pwa-resized-panels.png) | +| Representative light/dark themes | [Light](Evidence/theme-modern-light.png), [dark](Evidence/theme-modern-dark.png) | +| Large hierarchy | [1,000 locations](Evidence/large-hierarchy.png), [PWA](Evidence/pwa-large-hierarchy.png) | + +Additional screenshots cover PlotDirector, warm light/dark, rose pink and baby blue themes. + +## Known boundaries + +Geography confirmations are not regenerated by quick edits or inherited during merge. Existing +explicit geography review remains available. Location images do not currently exist in the model. +Map/plan navigation uses current route contracts; no editor geometry or interaction is redesigned. +Description editing is explicit Save/Cancel; merge and archive have no workspace Undo. Undo rejects +stale records or unavailable original parents rather than overwriting later changes. Bulk commands +are bounded at 2,000 records, consistent with the Characters convention. + +Non-hierarchical sensory/travel relationships remain on the established Details editor. Temporary +asset/scene circumstances stay separate from permanent containment; no temporal tracking system is +added. Full descriptions are preserved; very large card collections render all matches. + +User help: [Locations overview](../../PlotLine/Help/Articles/Locations/Overview.md). diff --git a/Docs/Locations/Evidence/after-cold-release.json b/Docs/Locations/Evidence/after-cold-release.json new file mode 100644 index 00000000..7c5fea23 --- /dev/null +++ b/Docs/Locations/Evidence/after-cold-release.json @@ -0,0 +1,30 @@ +[ + { + "count": 50, + "loadMs": 1424, + "expandMs": 134, + "searchMs": 115, + "assignments": 7 + }, + { + "count": 200, + "loadMs": 350, + "expandMs": 167, + "searchMs": 142, + "assignments": 6 + }, + { + "count": 500, + "loadMs": 399, + "expandMs": 332, + "searchMs": 131, + "assignments": 6 + }, + { + "count": 1000, + "loadMs": 416, + "expandMs": 593, + "searchMs": 163, + "assignments": 6 + } +] \ No newline at end of file diff --git a/Docs/Locations/Evidence/after-large.json b/Docs/Locations/Evidence/after-large.json new file mode 100644 index 00000000..24ca3823 --- /dev/null +++ b/Docs/Locations/Evidence/after-large.json @@ -0,0 +1,50 @@ +[ + { + "count": 50, + "loadMs": 266, + "expandMs": 102, + "searchMs": 108, + "detailsMs": 66, + "bulkMs": 175, + "reparentMs": 236, + "renameMs": 98, + "cardsMs": 116, + "assignments": 7 + }, + { + "count": 200, + "loadMs": 292, + "expandMs": 167, + "searchMs": 148, + "detailsMs": 62, + "bulkMs": 273, + "reparentMs": 354, + "renameMs": 106, + "cardsMs": 200, + "assignments": 6 + }, + { + "count": 500, + "loadMs": 317, + "expandMs": 334, + "searchMs": 126, + "detailsMs": 80, + "bulkMs": 498, + "reparentMs": 528, + "renameMs": 113, + "cardsMs": 436, + "assignments": 6 + }, + { + "count": 1000, + "loadMs": 445, + "expandMs": 636, + "searchMs": 163, + "detailsMs": 106, + "bulkMs": 873, + "reparentMs": 297, + "renameMs": 133, + "cardsMs": 1248, + "assignments": 6 + } +] \ No newline at end of file diff --git a/Docs/Locations/Evidence/attribute-assignment.png b/Docs/Locations/Evidence/attribute-assignment.png new file mode 100644 index 00000000..a616ff30 Binary files /dev/null and b/Docs/Locations/Evidence/attribute-assignment.png differ diff --git a/Docs/Locations/Evidence/before.json b/Docs/Locations/Evidence/before.json new file mode 100644 index 00000000..0dfdc52d --- /dev/null +++ b/Docs/Locations/Evidence/before.json @@ -0,0 +1,22 @@ +[ + { + "count": 50, + "loadMs": 257, + "dom": 1803 + }, + { + "count": 200, + "loadMs": 230, + "dom": 3904 + }, + { + "count": 500, + "loadMs": 410, + "dom": 8104 + }, + { + "count": 1000, + "loadMs": 609, + "dom": 15104 + } +] \ No newline at end of file diff --git a/Docs/Locations/Evidence/before.png b/Docs/Locations/Evidence/before.png new file mode 100644 index 00000000..b7233949 Binary files /dev/null and b/Docs/Locations/Evidence/before.png differ diff --git a/Docs/Locations/Evidence/bulk-assignment.png b/Docs/Locations/Evidence/bulk-assignment.png new file mode 100644 index 00000000..f50d7ef3 Binary files /dev/null and b/Docs/Locations/Evidence/bulk-assignment.png differ diff --git a/Docs/Locations/Evidence/cards.png b/Docs/Locations/Evidence/cards.png new file mode 100644 index 00000000..18822282 Binary files /dev/null and b/Docs/Locations/Evidence/cards.png differ diff --git a/Docs/Locations/Evidence/context-menu.png b/Docs/Locations/Evidence/context-menu.png new file mode 100644 index 00000000..99e98941 Binary files /dev/null and b/Docs/Locations/Evidence/context-menu.png differ diff --git a/Docs/Locations/Evidence/create-child.png b/Docs/Locations/Evidence/create-child.png new file mode 100644 index 00000000..c0694b96 Binary files /dev/null and b/Docs/Locations/Evidence/create-child.png differ diff --git a/Docs/Locations/Evidence/database-performance.txt b/Docs/Locations/Evidence/database-performance.txt new file mode 100644 index 00000000..cf8652df --- /dev/null +++ b/Docs/Locations/Evidence/database-performance.txt @@ -0,0 +1,6 @@ +PASS Dapper read: 50 synthetic + 69 existing clone records, old list 25.5 ms (119 rows), new six-result directory 82.1 ms +PASS Dapper read: 200 synthetic + 69 existing clone records, old list 41.2 ms (269 rows), new six-result directory 18.3 ms +PASS Dapper read: 500 synthetic + 69 existing clone records, old list 55.9 ms (569 rows), new six-result directory 41.2 ms +PASS Dapper read: 1000 synthetic + 69 existing clone records, old list 71.3 ms (1069 rows), new six-result directory 68.1 ms +PASS Dapper create result, exact-version assignment/Undo, directory projections including entry/exit-only usage, and rollback; no live data changed. +PASS actual typed ProjectBackup export and generic location JSON restore retain classification; restore rolled back. diff --git a/Docs/Locations/Evidence/database-qualification.json b/Docs/Locations/Evidence/database-qualification.json new file mode 100644 index 00000000..97fcddf9 --- /dev/null +++ b/Docs/Locations/Evidence/database-qualification.json @@ -0,0 +1,31 @@ +{ + "status": "passed", + "runs": [ + { + "clone": 4, + "starting_schema_sha256": "dc6afafb8c25fd63d98a97d016402ddda7474fdfa296a18722b3ddc2569ecb91", + "resulting_schema_sha256": "53a1d38ea01c4a0c6f601dc280a3dbdf706060b05b3ce9e9dd45ca83312ccbd4", + "executed": 1, + "unchanged_original_tables": 208, + "existing_canonical_types_unchanged": true, + "only_data_addition": "four canonical location types", + "integrity": { + "integrity": true, + "constraint_violations": 0 + } + }, + { + "clone": 5, + "starting_schema_sha256": "dc6afafb8c25fd63d98a97d016402ddda7474fdfa296a18722b3ddc2569ecb91", + "resulting_schema_sha256": "53a1d38ea01c4a0c6f601dc280a3dbdf706060b05b3ce9e9dd45ca83312ccbd4", + "executed": 1, + "unchanged_original_tables": 208, + "existing_canonical_types_unchanged": true, + "only_data_addition": "four canonical location types", + "integrity": { + "integrity": true, + "constraint_violations": 0 + } + } + ] +} \ No newline at end of file diff --git a/Docs/Locations/Evidence/details-edit.png b/Docs/Locations/Evidence/details-edit.png new file mode 100644 index 00000000..f01336b4 Binary files /dev/null and b/Docs/Locations/Evidence/details-edit.png differ diff --git a/Docs/Locations/Evidence/hierarchy.png b/Docs/Locations/Evidence/hierarchy.png new file mode 100644 index 00000000..620dde79 Binary files /dev/null and b/Docs/Locations/Evidence/hierarchy.png differ diff --git a/Docs/Locations/Evidence/hover-reparent.png b/Docs/Locations/Evidence/hover-reparent.png new file mode 100644 index 00000000..79195019 Binary files /dev/null and b/Docs/Locations/Evidence/hover-reparent.png differ diff --git a/Docs/Locations/Evidence/inline-rename.png b/Docs/Locations/Evidence/inline-rename.png new file mode 100644 index 00000000..6a4315ec Binary files /dev/null and b/Docs/Locations/Evidence/inline-rename.png differ diff --git a/Docs/Locations/Evidence/large-hierarchy.png b/Docs/Locations/Evidence/large-hierarchy.png new file mode 100644 index 00000000..2ced33f9 Binary files /dev/null and b/Docs/Locations/Evidence/large-hierarchy.png differ diff --git a/Docs/Locations/Evidence/pwa-cards.png b/Docs/Locations/Evidence/pwa-cards.png new file mode 100644 index 00000000..a09c63cd Binary files /dev/null and b/Docs/Locations/Evidence/pwa-cards.png differ diff --git a/Docs/Locations/Evidence/pwa-large-hierarchy.png b/Docs/Locations/Evidence/pwa-large-hierarchy.png new file mode 100644 index 00000000..07a3c7ca Binary files /dev/null and b/Docs/Locations/Evidence/pwa-large-hierarchy.png differ diff --git a/Docs/Locations/Evidence/pwa-performance.json b/Docs/Locations/Evidence/pwa-performance.json new file mode 100644 index 00000000..921e432f --- /dev/null +++ b/Docs/Locations/Evidence/pwa-performance.json @@ -0,0 +1,30 @@ +[ + { + "count": 50, + "loadMs": 302, + "expandMs": 130, + "searchMs": 127, + "assignments": 7 + }, + { + "count": 200, + "loadMs": 375, + "expandMs": 210, + "searchMs": 131, + "assignments": 6 + }, + { + "count": 500, + "loadMs": 451, + "expandMs": 416, + "searchMs": 163, + "assignments": 6 + }, + { + "count": 1000, + "loadMs": 729, + "expandMs": 851, + "searchMs": 161, + "assignments": 6 + } +] \ No newline at end of file diff --git a/Docs/Locations/Evidence/pwa-resized-panels.png b/Docs/Locations/Evidence/pwa-resized-panels.png new file mode 100644 index 00000000..bc6f2c67 Binary files /dev/null and b/Docs/Locations/Evidence/pwa-resized-panels.png differ diff --git a/Docs/Locations/Evidence/pwa-theme-modern-dark.png b/Docs/Locations/Evidence/pwa-theme-modern-dark.png new file mode 100644 index 00000000..d9a0de60 Binary files /dev/null and b/Docs/Locations/Evidence/pwa-theme-modern-dark.png differ diff --git a/Docs/Locations/Evidence/pwa-workspace.png b/Docs/Locations/Evidence/pwa-workspace.png new file mode 100644 index 00000000..2922bf50 Binary files /dev/null and b/Docs/Locations/Evidence/pwa-workspace.png differ diff --git a/Docs/Locations/Evidence/reparenting.png b/Docs/Locations/Evidence/reparenting.png new file mode 100644 index 00000000..5728a085 Binary files /dev/null and b/Docs/Locations/Evidence/reparenting.png differ diff --git a/Docs/Locations/Evidence/resized-panels.png b/Docs/Locations/Evidence/resized-panels.png new file mode 100644 index 00000000..a19139a6 Binary files /dev/null and b/Docs/Locations/Evidence/resized-panels.png differ diff --git a/Docs/Locations/Evidence/root-drop.png b/Docs/Locations/Evidence/root-drop.png new file mode 100644 index 00000000..b24aa3d5 Binary files /dev/null and b/Docs/Locations/Evidence/root-drop.png differ diff --git a/Docs/Locations/Evidence/search-context.png b/Docs/Locations/Evidence/search-context.png new file mode 100644 index 00000000..66baf1aa Binary files /dev/null and b/Docs/Locations/Evidence/search-context.png differ diff --git a/Docs/Locations/Evidence/sql-regressions.txt b/Docs/Locations/Evidence/sql-regressions.txt new file mode 100644 index 00000000..23156db2 --- /dev/null +++ b/Docs/Locations/Evidence/sql-regressions.txt @@ -0,0 +1,7 @@ +PASS bulk branch preservation, root moves, classification, targeted rename, exact undo +PASS descendant cycle rejection +PASS unavailable parent rejection +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 diff --git a/Docs/Locations/Evidence/theme-baby-blue.png b/Docs/Locations/Evidence/theme-baby-blue.png new file mode 100644 index 00000000..edf42528 Binary files /dev/null and b/Docs/Locations/Evidence/theme-baby-blue.png differ diff --git a/Docs/Locations/Evidence/theme-modern-dark.png b/Docs/Locations/Evidence/theme-modern-dark.png new file mode 100644 index 00000000..a8106cec Binary files /dev/null and b/Docs/Locations/Evidence/theme-modern-dark.png differ diff --git a/Docs/Locations/Evidence/theme-modern-light.png b/Docs/Locations/Evidence/theme-modern-light.png new file mode 100644 index 00000000..14a4c0c5 Binary files /dev/null and b/Docs/Locations/Evidence/theme-modern-light.png differ diff --git a/Docs/Locations/Evidence/theme-plotdirector.png b/Docs/Locations/Evidence/theme-plotdirector.png new file mode 100644 index 00000000..c2438e91 Binary files /dev/null and b/Docs/Locations/Evidence/theme-plotdirector.png differ diff --git a/Docs/Locations/Evidence/theme-rose-pink.png b/Docs/Locations/Evidence/theme-rose-pink.png new file mode 100644 index 00000000..2249ff83 Binary files /dev/null and b/Docs/Locations/Evidence/theme-rose-pink.png differ diff --git a/Docs/Locations/Evidence/theme-warm-dark.png b/Docs/Locations/Evidence/theme-warm-dark.png new file mode 100644 index 00000000..6af43cd0 Binary files /dev/null and b/Docs/Locations/Evidence/theme-warm-dark.png differ diff --git a/Docs/Locations/Evidence/theme-warm-light.png b/Docs/Locations/Evidence/theme-warm-light.png new file mode 100644 index 00000000..a27b362e Binary files /dev/null and b/Docs/Locations/Evidence/theme-warm-light.png differ diff --git a/Docs/Locations/Evidence/workspace.png b/Docs/Locations/Evidence/workspace.png new file mode 100644 index 00000000..7a255e74 Binary files /dev/null and b/Docs/Locations/Evidence/workspace.png differ diff --git a/Docs/Locations/Workspace.md b/Docs/Locations/Workspace.md new file mode 100644 index 00000000..5dfb0243 --- /dev/null +++ b/Docs/Locations/Workspace.md @@ -0,0 +1,94 @@ +# Locations workspace + +The main directory uses the existing `dbo.Locations` identifiers. `LocationWorkspaceController` +reads a flat directory and recorded associations using Dapper and `Location_WorkspaceRead`. +The browser builds hierarchy paths and child indexes without a recursive SQL view or per-location +queries. The initial MVC request reads the authorised project only. Associated manuscript prose +is never loaded. Existing Details/Edit, archive, scene assignment and relationship forms remain. + +The three panels reuse `workspace-surface.js` (a Locations profile), shared theme tokens, +`PlotDirectorContextMenus`, `PlotDirector.toast` and `ContextWorkspaceNotifications.Invalidate`. +Browser and installed PWA use the same commands and same-window links. Nothing changes narrative +focus or invokes AI/geocoding. Location images are not currently a canonical location attribute; +there are no fabricated image placeholders. + +## Canonical attributes + +Existing types: Country, Region, Town, Village, Street, Building, Floor, Room, Outdoor Area, +Vehicle Interior, Landmark and Other. Migration 335 adds Planet, District, Natural Feature and +City without changing existing IDs or values. Existing aliases, description, Quick Add inclusion, +Word Companion exclusion and detection priority are retained. Quick Add and detection exclusion +are suitable quick switches; numeric detection priority remains in the full form. + +`Locations.Classification` is optional: NULL (Unclassified), Real, Fictional, Fictionalised. +It is independent of type. No existing location is classified automatically. Classification +is edited in the workspace and preserved by existing full forms, which do not update this column. +`LocationItem.Classification` and the existing export selector preserve it through project backups; +the generic restore contract already accepts the additional column. `LocationWorkspaceIcons` maps +canonical labels onto opt-in shared ribbon icons without changing other consumers. + +## Mutation and hierarchy safety + +`Location_WorkspaceAssign` validates project role (Owner/Collaborator), active project/location, +canonical values, parent membership and optimistic `UpdatedDate` versions inside a transaction. +Only the selected attribute is written. Permanent containment can be arbitrarily nested. +The final parent graph is checked on the server, including Undo; cycles and self/descendant moves +are rejected. Root is NULL. For ordinary bulk moves, selected descendants whose ancestor is also +selected are omitted, retaining complete branches. Undo restores only the roots actually changed. +No-op assignments do not update timestamps or audit history. Unavailable ancestors are shown as +“Parent unavailable”; original parent IDs are retained, and the Root filter means an actual NULL +parent. Recorded unavailable types remain visible in Details rather than being relabelled Unclassified. + +Each mutation records the established project audit. Audit result sets are captured internally. +The response returns exact post-save versions and changed values. A user-bound, protected receipt +expires after ten minutes; Undo compares the current version before applying the original value. +A stale receipt cannot overwrite later edits. The browser updates its directory, counts and details +without navigating/reloading. Live invalidations refresh other windows; dirty descriptions defer +refresh. Explicit Save/Cancel and discard confirmation protect unsaved descriptions. + +`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. + +## Merge + +Workspace merge is explicit, reviewed and has no Undo. The author chooses the survivor and sees +both descriptions and type/classification conflicts. `Location_WorkspaceMerge` validates both +record versions and the editing role, then wraps the established `Location_Merge` transaction. +That operation transfers scene/character/asset references, children, aliases, floor plans, +import references and non-hierarchical links; direct source/survivor links are archived. The forward-only extension to the established merge +also transfers MapFeatures.LocationID and increments affected map revisions without changing any +feature ID or geometry. Different descriptions are retained together with a source label. +An unclassified survivor inherits source classification; otherwise survivor classification wins. +Survivor name, type and parent remain. Source records and original information stay archived. +Geographic confirmation evidence stays with its original record and is not inferred for the survivor. +The older full merge form remains available and receives the same preservation safeguards. The +workspace additionally previews conflicts and rejects records changed since review. + +## Filters, associations and preferences + +Map/floor-plan indicators come from MapFeatures and direct plan/floor/block links. Multiple links +are listed individually rather than selecting one implicitly. Map links open the existing selected +map; floor-plan links open its existing editor. Location/feature reveal inside those editors is +limited to their current route contracts. Scene use counts distinct recorded primary, character current/entry/exit and asset scene assignments; +it is not textual name matching. Relationship, explicitly located character and current asset +counts come from authoritative records; full evidence remains on Details. Derived filters are +read-only. Branch-filter results retain ancestors without modifying permanent expansion state. + +`pd.locations.workspace.v1..` stores view, sorting, expanded branches, collapsed +panels and expanded attribute groups. The shared divider key is independently scoped to the same +user/project. Dragging dividers writes local preferences only on completion. Narrow displays stack +the panels, without horizontal page overflow. Tree keyboard commands: arrows, Home/End, Enter, +Space selection, F2 rename, Shift+F10/context-menu key. Shared menus handle focus/dismissal. + +## Boundaries and limitations + +Permanent containment is separate from sensory/travel relationships and `SceneAssetLocations` / +asset current location. A vehicle temporarily parked somewhere must not become its permanent child +unless the author explicitly chooses that hierarchy. No temporal asset tracking is added. +No Context, Maps, Floor Plans, Assets, Characters or Names workspace is redesigned. + +Geography confirmations are not regenerated after workspace changes. Existing explicit geography +review remains available. Large trees render only expanded branches; card view renders matching +cards, with complete descriptions and variable height. There is no card virtualization. +See `Acceptance.md` for measured verification and remaining limitations. diff --git a/PlotLine.Tests/Browser/locations-workspace-dev-pwa.cjs b/PlotLine.Tests/Browser/locations-workspace-dev-pwa.cjs new file mode 100644 index 00000000..58d9c860 --- /dev/null +++ b/PlotLine.Tests/Browser/locations-workspace-dev-pwa.cjs @@ -0,0 +1,9 @@ +// Actual installed Development PWA; reads only the dedicated fixture left by locations-workspace-dev.cjs. +const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const base='https://dev.plotdirector.com',file=process.argv[2];if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated private identity required');const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));assert(identity.ProjectID); +(async()=>{const profile=fs.mkdtempSync('/tmp/pd-locations-dev-pwa-'),context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}),cdp=await context.browser().newBrowserCDPSession(),manifestId=base+'/Projects';try{ + const tab=context.pages()[0];await tab.goto(base+'/Account/Login');await tab.locator('[name=Email]').fill(identity.Email);await tab.locator('[name=Password]').fill(identity.Password);await tab.locator('form button[type=submit]').click();await tab.waitForURL(base+'/Projects'); + await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/Projects'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+`/Locations?projectId=${identity.ProjectID}`});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));await page.locator('[data-location-records][aria-busy=false]').waitFor();const row=page.locator('[data-location-id]').first();await row.locator('[data-location-name]').click();assert.equal(await page.locator('[data-details]').getByRole('combobox',{name:'Classification',exact:true}).inputValue(),'Fictional');await row.getByRole('button',{name:/Actions for/}).click();await page.getByRole('menu').first().waitFor();await page.screenshot({path:'/tmp/pd-locations-evidence/development-pwa-context.png'});await page.keyboard.press('Escape'); + await page.getByRole('button',{name:'Cards',exact:true}).click();assert(await page.getByText('Author-controlled synthetic description.',{exact:true}).count());await page.screenshot({path:'/tmp/pd-locations-evidence/development-pwa-cards.png'});const pages=context.pages().length;await page.locator('[data-details]').getByRole('link',{name:'Full details',exact:true}).click();await page.waitForURL(/\/Locations\/Details\/\d+/);assert.equal(context.pages().length,pages,'same-window navigation'); + fs.writeFileSync('/tmp/pd-locations-evidence/development-pwa-smoke.json',JSON.stringify({status:'passed',target:'Development',installed:true,checks:['real installed Chromium PWA','authenticated workspace directory','saved classification','shared context menu','card description','same-window Location Details navigation']},null,2));console.log('PASS actual authenticated installed Development PWA, saved state, context menu, cards and same-window details.'); + }finally{await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/locations-workspace-dev.cjs b/PlotLine.Tests/Browser/locations-workspace-dev.cjs new file mode 100644 index 00000000..c0feebdf --- /dev/null +++ b/PlotLine.Tests/Browser/locations-workspace-dev.cjs @@ -0,0 +1,27 @@ +// Explicit Development-only operational smoke. Uses only a dedicated disposable identity/project. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const base='https://dev.plotdirector.com',file=process.argv[2],setup=process.argv.includes('--setup'); +if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Private dedicated identity file required.'); +const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-')&&identity.Email.endsWith('@example.invalid')); +(async()=>{const browser=await chromium.launch(),context=await browser.newContext({viewport:{width:1440,height:1000}}),page=await context.newPage();try{ + 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 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(); + await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.getByRole('textbox',{name:'New location name'}).fill('Observatory acceptance');await page.getByRole('textbox',{name:'New location name'}).press('Enter');await page.locator('[data-location-dialog]').waitFor({state:'hidden'});data=await directory();const child=data.locations.find(r=>r.name==='Observatory acceptance');assert.equal(child.parent,id); + await row().locator('[data-location-name]').click();const peer=await context.newPage();await peer.goto(base+`/Locations?${q}`);await peer.locator('[data-location-records][aria-busy=false]').waitFor(); + await page.locator('[data-details]').getByRole('combobox',{name:'Classification',exact:true}).selectOption('Fictional');await page.waitForTimeout(250);data=await directory();assert.equal(data.locations.find(r=>r.id===id).classification,'Fictional'); + await peer.locator(`[data-location-id="${id}"] [aria-label="Fictional"]`).waitFor({timeout:20000}); + 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 out='/tmp/pd-locations-evidence';await page.screenshot({path:out+'/development-workspace.png'}); + 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.'); + }finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/locations-workspace.cjs b/PlotLine.Tests/Browser/locations-workspace.cjs new file mode 100644 index 00000000..777e46f5 --- /dev/null +++ b/PlotLine.Tests/Browser/locations-workspace.cjs @@ -0,0 +1,58 @@ +// Actual compiled Locations Razor + shared shell. All mutations use synthetic HTTP fixtures. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:5238',out='/tmp/pd-locations-evidence'+(installed?'/pwa':'');fs.mkdirSync(out,{recursive:true}); +(async()=>{const profile=installed?fs.mkdtempSync('/tmp/pd-locations-pwa-'):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null,manifestId=origin+'/Projects',results=[];if(installed){await persistent.pages()[0].goto(origin+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:origin+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});}async function newPage(){if(!installed)return browser.newPage({viewport:{width:1440,height:1000}});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:origin+'/fixture?page=calendar-test'});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return page;}try{for(const count of process.argv.includes('--persistence-only')?[50]:[50,200,500,1000]){ + const page=await newPage(),errors=[],timings={};page.on('pageerror',e=>errors.push(e.message)); + const types=await (await page.request.get(`${origin}/locations-workspace-types-fixture`)).json();let clock=0,requests=[],undo=new Map(),rejectNext=false,delayDirectory=false,releaseDirectory=null;const records=Array.from({length:count},(_,i)=>({id:i+1,name:['Meridian','Northern coast','Port Halcyon','Observatory','Reading room'][i]||`Location ${String(i+1).padStart(3,'0')}`,parent:i===0||i%13===0?null:i<10?i:Math.floor((i-1)/12)*12+1,type:String(i%9+1),typeName:types[i%9].label,classification:i%4===0?'Fictional':'',description:i%5===0?'':('Salt air drifts through the open windows. The old charts record a coastline changed by generations of storms. ').repeat(i%7+1),quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:i===4?['Quiet study']:[],maps:i%5===0?[{id:1,name:'Coast chart'}]:[],floors:i%7===0?[{id:2,name:'Observatory floors'}]:[],scenes:i%3})); + records[count-1].parent=2147483647; + records[0].maps.push({id:2,name:'Northern chart'});records[0].floors.push({id:3,name:'Annex floor plan'}); + if(count>=500){for(let i=count-100;i{const snapshot=structuredClone(records);if(delayDirectory){delayDirectory=false;await new Promise(resolve=>releaseDirectory=resolve);}await r.fulfill({json:{canEdit:true,types,locations:snapshot}});}); + await page.route('**/LocationWorkspace/Assign',async route=>{assert(route.request().headers().requestverificationtoken);const input=route.request().postDataJSON();requests.push(input);if(rejectNext){rejectNext=false;return route.fulfill({status:409,json:{message:'Simulated concurrent edit rejected.'}});}let changes=input.changes;const ids=new Set(changes.map(c=>c.id));if(input.attribute==='parent')changes=changes.filter(c=>{let p=records.find(r=>r.id===c.id).parent;const seen=new Set();while(p&&!seen.has(p)){if(ids.has(p))return false;seen.add(p);p=records.find(r=>r.id===p)?.parent;}return true;});const previous=[],changed=[];for(const c of changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Changed in another window.'}});previous.push({id:r.id,value:r[input.attribute],version:r.version});r[input.attribute]=input.attribute==='parent'?(c.value?Number(c.value):null):c.value;r.version=`v${clock++}`;changed.push({id:r.id,value:c.value,version:r.version});}const token=`u${clock}`;undo.set(token,{attribute:input.attribute,previous});await route.fulfill({json:{saved:true,changes:changed,attribute:input.attribute,undoToken:token}});}); + await page.route('**/LocationWorkspace/Undo',async route=>{const receipt=undo.get(route.request().postDataJSON().token),changes=[];for(const old of receipt.previous){const r=records.find(r=>r.id===old.id);r[receipt.attribute]=old.value;r.version=`v${clock++}`;changes.push({id:r.id,value:old.value?.toString()||'',version:r.version});}await route.fulfill({json:{saved:true,changes,attribute:receipt.attribute}});}); + await page.route('**/LocationWorkspace/Create',async route=>{const input=route.request().postDataJSON(),id=records.length+1;records.push({id,name:input.name,parent:input.parentId,type:'',classification:'',description:'',quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:[],maps:[],floors:[],scenes:0});await route.fulfill({json:{id}});}); + const shot=async name=>{if(count===50){await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^=Dismiss]').forEach(b=>b.click()));await page.screenshot({path:`${out}/${name}.png`});}};const row=id=>page.locator(`[data-location-id="${id}"]`),attribute=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`); + const start=performance.now();await page.goto(`${origin}/locations-workspace-fixture?count=${count}`);await row(1).waitFor();const loadMs=Math.round(performance.now()-start);const detailsStart=performance.now();await row(1).locator('[data-location-name]').click();timings.detailsMs=Math.round(performance.now()-detailsStart);assert.equal(await page.locator('[data-related] a[href^="/Maps"]').count(),2);assert.equal(await page.locator('[data-related] a[href^="/FloorPlans"]').count(),2);assert.equal(await page.locator('[data-related] a[target]').count(),0);await shot('workspace'); + const expandStart=performance.now();await page.getByRole('button',{name:'Expand all',exact:true}).click();await row(5).waitFor();const expandMs=Math.round(performance.now()-expandStart);assert.match(await row(count).getAttribute('title'),/Parent unavailable/);await shot('hierarchy');if(count===50){ + const parents=records.map(r=>r.parent);await page.locator('[data-sort]').selectOption('desc');const order=await page.locator('[data-location-id]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.locationId)));for(const r of records)if(r.parent)assert(order.indexOf(r.parent)r.parent),parents);await page.locator('[data-sort]').selectOption('asc'); + await row(1).focus();await page.keyboard.press('Space');assert(await row(1).locator('[data-select-location]').isChecked());await page.keyboard.press('Space');assert(!(await row(1).locator('[data-select-location]').isChecked())); + } + const drag=async(source,target)=>{await source.dragTo(target);await page.waitForTimeout(100);}; + await drag(attribute('type','6').locator('button').first(),row(1));await page.waitForFunction(()=>document.querySelector('[data-undo]').hidden===false);assert.equal(records[0].type,'6');await shot('attribute-assignment');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(60);assert.equal(records[0].type,'1'); + if(count===50){await page.evaluate(()=>{window.fixtureHints={};document.dispatchEvent(new CustomEvent('pd-presence-connection',{detail:{on:(name,fn)=>window.fixtureHints[name]=fn,onreconnected:()=>{}}}));});delayDirectory=true;await page.evaluate(()=>{const handlers=Object.values(window.PlotDirectorPresenceConnection||{}).find(v=>v&&typeof v==='object'&&Array.isArray(v.contextinvalidated))?.contextinvalidated;if(handlers?.length)for(const handler of handlers)handler({projectId:7});else if(window.fixtureHints.ContextInvalidated)window.fixtureHints.ContextInvalidated({projectId:7});else throw Error('No live invalidation handler registered.');});for(let attempt=0;!releaseDirectory&&attempt<50;attempt++)await page.waitForTimeout(20);assert(releaseDirectory,'live invalidation requests fresh data');await page.waitForTimeout(30);await drag(attribute('type','6').locator('button').first(),row(1));assert.equal(records[0].type,'6');releaseDirectory();await page.waitForTimeout(150);assert.equal(await row(1).getByRole('img',{name:'Room',exact:true}).count(),1);await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(100);} + 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'); + 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); + await row(4).focus();await page.keyboard.press('F2');const rename=row(4).getByRole('textbox',{name:'Location name'});await rename.fill('West observatory');await shot('inline-rename');const renameStart=performance.now();await rename.press('Enter');await page.waitForTimeout(80);timings.renameMs=Math.round(performance.now()-renameStart);assert.equal(records[3].name,'West observatory');if(count===50){await row(4).focus();await page.keyboard.press('F2');await row(4).getByRole('textbox',{name:'Location name'}).fill('Discard this name');await page.keyboard.press('Escape');assert.equal(records[3].name,'West observatory');} + await row(4).click({button:'right'});await page.getByRole('menu').first().waitFor();await shot('context-menu');await page.keyboard.press('Escape');if(count===50){await row(4).focus();await page.keyboard.press('Shift+F10');await page.getByRole('menu').first().waitFor();await page.keyboard.press('Escape');} + await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.getByRole('textbox',{name:'New location name'}).fill('Chart room');await shot('create-child');await page.locator('[data-dialog-save]').click();await page.waitForTimeout(150);assert.equal(records.at(-1).parent,4); + await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Edit description',exact:true}).click();const description=page.getByRole('textbox',{name:'Location description'});await description.fill('Preserved author prose.\nSecond paragraph.');page.once('dialog',d=>d.dismiss());await row(1).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');await shot('details-edit');await page.locator('[data-details]').getByRole('button',{name:'Save',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[3].description,'Preserved author prose.\nSecond paragraph.'); + const searchStart=performance.now();await page.locator('[data-search]').fill('Quiet study');await page.waitForTimeout(80);assert(await row(5).isVisible());assert(await row(1).isVisible());const searchMs=Math.round(performance.now()-searchStart);await shot('search-context');await page.locator('[data-clear-search]').click(); + await row(1).locator('[data-select-location]').check();const cardsStart=performance.now();await page.getByRole('button',{name:'Cards',exact:true}).click();timings.cardsMs=Math.round(performance.now()-cardsStart);assert(await row(1).locator('[data-select-location]').isChecked());await shot('cards');const heights=await page.locator('.location-record').evaluateAll(ns=>ns.slice(0,12).map(n=>n.getBoundingClientRect().height));assert(new Set(heights.map(Math.round)).size>3); + if(count===50){ + const fictional=attribute('classification','Fictional').locator('button').first();await fictional.click();assert(await row(1).isVisible());assert(!(await row(2).count()));const matching=records.filter(r=>r.classification==='Fictional').length;assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+matching+' of ')); + await page.getByRole('button',{name:'Hierarchy',exact:true}).click();assert.equal(await fictional.getAttribute('aria-pressed'),'true');assert(await row(1).locator('[data-select-location]').isChecked());await page.getByRole('button',{name:'Cards',exact:true}).click(); + await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert(!(await row(1).count()));assert.equal(records[0].classification,'Real');assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+(matching-1)+' of '));await page.getByRole('button',{name:'Undo',exact:true}).first().click();await row(1).waitFor(); + await page.locator('[data-clear-filters]').click();await attribute('mapState','yes').locator('button').click();assert.equal(await page.locator('[data-location-id]').count(),records.filter(r=>r.maps.length).length);assert.equal(await attribute('mapState','yes').locator('[data-assign]').count(),0);await page.locator('[data-clear-filters]').click(); + await page.locator('[data-branch-filter]').click();await page.getByRole('listbox',{name:'Parent location'}).selectOption('1');await page.locator('[data-dialog-save]').click();const inBranch=r=>{const seen=new Set();while(r&&!seen.has(r.id)){if(r.id===1)return true;seen.add(r.id);r=records.find(x=>x.id===r.parent);}return false;};assert.equal(await page.locator('[data-location-id]').count(),records.filter(inBranch).length);await page.locator('[data-clear-filters]').click(); + } + + await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await page.locator('[data-clear-selection]').click();const divider=page.getByRole('separator',{name:'Resize left panel'});await divider.press('ArrowRight');const right=page.getByRole('separator',{name:'Resize right panel'});await right.press('ArrowLeft');if(count===50)for(const [handle,delta]of [[divider,55],[right,-55]]){const box=await handle.boundingBox(),before=Number(await handle.getAttribute('aria-valuenow'));await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width/2+delta,box.y+box.height/2,{steps:8});await page.mouse.up();assert(Number(await handle.getAttribute('aria-valuenow'))>=before+50);}await shot('resized-panels'); + for(const panel of ['attributes','details']){await page.getByRole('button',{name:panel==='attributes'?'Attributes':'Details',exact:true}).click();assert(await page.locator(`.locations-${panel}`).isHidden());await page.getByRole('button',{name:panel==='attributes'?'Attributes':'Details',exact:true}).click();} + for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(t=>{document.documentElement.dataset.appTheme=t;document.documentElement.dataset.bsTheme=t.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=t.endsWith('dark')?'dark':'light';},theme);await shot(`theme-${theme}`);} + for(const [width,height]of [[1920,1080],[1440,900],[1280,720],[1024,768],[768,1024],[390,844]]){await page.setViewportSize({width,height});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),`no horizontal overflow at ${width}`);} + await page.setViewportSize({width:1440,height:1000});if(count===1000)await page.screenshot({path:`${out}/large-hierarchy.png`});if(count===50){ + const widths=await page.locator('.locations-layout').evaluate(n=>[n.style.getPropertyValue('--workspace-left'),n.style.getPropertyValue('--workspace-right')]); + await page.locator('[data-groups]>details').first().evaluate(n=>n.open=false);await page.waitForTimeout(20); + await page.getByRole('button',{name:'Cards',exact:true}).click();await page.getByRole('button',{name:'Details',exact:true}).click();await page.reload();await row(1).waitFor(); + assert(await page.locator('.locations-details').isHidden());assert(await page.locator('.locations-cards').count());assert.equal(await page.locator('[data-groups]>details').first().evaluate(n=>n.open),false); + assert.deepEqual(await page.locator('.locations-layout').evaluate(n=>[n.style.getPropertyValue('--workspace-left'),n.style.getPropertyValue('--workspace-right')]),widths); + await page.getByRole('button',{name:'Details',exact:true}).click();await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await row(5).waitFor();await page.locator('[data-groups]>details').first().evaluate(n=>n.open=true); + } + assert.deepEqual(errors,[]);results.push({count,loadMs,expandMs,searchMs,...timings,assignments:requests.length});console.log('PASS',results.at(-1));await page.close(); + }fs.writeFileSync(`${out}/after.json`,JSON.stringify(results,null,2));}finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs b/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs new file mode 100644 index 00000000..fe0bebca --- /dev/null +++ b/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs @@ -0,0 +1,78 @@ +using System.Data; +using System.Diagnostics; +using System.Text.Json; +using Dapper; +using Microsoft.Data.SqlClient; +using PlotLine.Controllers; +using PlotLine.Models; +using PlotLine.Data; + +internal static class LocationsWorkspaceDatabaseTests +{ + public static async Task Run(string configPath) + { + using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath)); + var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString()); + if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_Locations",StringComparison.Ordinal))throw new InvalidOperationException("Disposable Locations clone required."); + using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync(); + if(await db.ExecuteScalarAsync("SELECT DB_NAME()")!=builder.InitialCatalog)throw new InvalidOperationException("Wrong database."); + var identity=await db.QueryFirstAsync<(int ProjectID,int UserID)>("SELECT TOP(1) p.ProjectID,a.UserID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.IsArchived=0 AND a.IsActive=1 AND a.AccessRole=N'Owner' ORDER BY p.ProjectID"); + using var transaction=db.BeginTransaction(); + try + { + var created=await db.QuerySingleAsync("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Dapper workspace contract",ParentID=(int?)null},transaction,commandType:CommandType.StoredProcedure); + if(!await db.ExecuteScalarAsync("SELECT CONVERT(bit,COUNT(*)) FROM dbo.Locations WHERE LocationID=@created AND LocationName=N'Dapper workspace contract'",new{created},transaction))throw new Exception("Create returned an audit identifier instead of the location identifier."); + var row=await db.QuerySingleAsync("SELECT * FROM dbo.Locations WHERE LocationID=@created",new{created},transaction); + var changes=new[]{new LocationWorkspaceController.Change(created,"Fictionalised",row.UpdatedDate.ToString("O"))}; + var before=(await db.QueryAsync("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(changes)},transaction,commandType:CommandType.StoredProcedure)).ToArray(); + if(before.Length!=1||before[0].Id!=created||before[0].Value!=""||!DateTime.TryParse(before[0].Version,out var version))throw new Exception("Invalid assignment result/undo receipt."); + await db.QueryAsync("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(before),Restore=true},transaction,commandType:CommandType.StoredProcedure); + if(await db.ExecuteScalarAsync("SELECT Classification FROM dbo.Locations WHERE LocationID=@created",new{created},transaction)!=null)throw new Exception("Exact timestamp Undo failed."); + var presence=await db.QueryFirstOrDefaultAsync("SELECT TOP(1) sc.SceneCharacterID FROM dbo.SceneCharacters sc JOIN dbo.Scenes s ON s.SceneID=sc.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0",new{identity.ProjectID},transaction); + if(presence is null)throw new Exception("Clone character presence fixture required."); + await db.ExecuteAsync("UPDATE dbo.SceneCharacters SET LocationID=NULL,EntryLocationID=@created,ExitLocationID=@created WHERE SceneCharacterID=@presence",new{created,presence},transaction); + foreach(var count in new[]{50,200,500,1000}) + { + await db.ExecuteAsync("DELETE FROM dbo.Locations WHERE ProjectID=@ProjectID AND LocationName LIKE N'Dapper performance fixture %'; WITH n AS (SELECT TOP(@count) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ID FROM sys.all_objects) INSERT dbo.Locations(ProjectID,LocationName,Description) SELECT @ProjectID,CONCAT(N'Dapper performance fixture ',ID),REPLICATE(N'Complete synthetic description. ',20) FROM n",new{identity.ProjectID,count},transaction); + var baseline=Stopwatch.StartNew(); + var previousRows=(await db.QueryAsync("dbo.Location_ListByProject",new{identity.ProjectID},transaction,commandType:CommandType.StoredProcedure)).ToArray(); + var baselineMs=baseline.Elapsed.TotalMilliseconds; + var watch=Stopwatch.StartNew(); + using var result=await db.QueryMultipleAsync("dbo.Location_WorkspaceRead",new{identity.ProjectID,identity.UserID},transaction,commandType:CommandType.StoredProcedure); + var rows=(await result.ReadAsync()).ToArray(); + await result.ReadAsync();await result.ReadAsync();await result.ReadAsync();var usage=(await result.ReadAsync()).ToArray();await result.ReadAsync(); + if(!usage.Any(u=>u.LocationID==created&&u.SceneCount==1))throw new Exception("Entry/exit-only assignments were missed or double counted."); + if(rows.Count(r=>r.LocationName.StartsWith("Dapper performance fixture "))!=count)throw new Exception("Directory lost fixture rows."); + Console.WriteLine($"PASS Dapper read: {count} synthetic + {rows.Length-count} existing clone records, old list {baselineMs:F1} ms ({previousRows.Length} rows), new six-result directory {watch.Elapsed.TotalMilliseconds:F1} ms"); + } + transaction.Rollback(); + Console.WriteLine("PASS Dapper create result, exact-version assignment/Undo, directory projections including entry/exit-only usage, and rollback; no live data changed."); + } + catch{try{transaction.Rollback();}catch{}throw;} + // Verify the typed export and the existing generic location restore on committed clone-only data. + var fixture=await db.QuerySingleAsync("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Classification round-trip fixture",ParentID=(int?)null},commandType:CommandType.StoredProcedure); + try + { + var original=await db.QuerySingleAsync("SELECT * FROM dbo.Locations WHERE LocationID=@fixture",new{fixture}); + await db.QueryAsync("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(new[]{new LocationWorkspaceController.Change(fixture,"Fictionalised",original.UpdatedDate.ToString("O"))})},commandType:CommandType.StoredProcedure); + var export=await new ProjectBackupRepository(new Connections(builder.ConnectionString)).GetProjectBackupAsync(identity.ProjectID,identity.UserID)??throw new Exception("Export failed."); + var exported=export.Data.Locations.Single(l=>l.LocationID==fixture); + if(exported.Classification!="Fictionalised")throw new Exception("Typed project export lost classification."); + using var restore=db.BeginTransaction(); + try + { + await db.ExecuteAsync("DELETE dbo.Locations WHERE LocationID=@fixture",new{fixture},restore); + await db.ExecuteAsync("dbo.ProjectRestore_InsertJsonTable",new{TableName="Locations",JsonPath="$.Data.Locations",JsonData=JsonSerializer.Serialize(new{Data=new{Locations=new[]{exported}}}),identity.ProjectID,ProjectScopedOnly=false},restore,commandType:CommandType.StoredProcedure); + if(await db.ExecuteScalarAsync("SELECT Classification FROM dbo.Locations WHERE LocationID=@fixture",new{fixture},restore)!="Fictionalised")throw new Exception("Location restore lost classification."); + restore.Rollback(); + } + catch{try{restore.Rollback();}catch{}throw;} + Console.WriteLine("PASS actual typed ProjectBackup export and generic location JSON restore retain classification; restore rolled back."); + } + finally + { + await db.ExecuteAsync("DELETE dbo.ProjectActivity WHERE ProjectID=@ProjectID AND EntityType=N'Location' AND EntityID=@fixture; DELETE dbo.Locations WHERE LocationID=@fixture AND ProjectID=@ProjectID",new{identity.ProjectID,fixture}); + } + } + private sealed class Connections(string value):ISqlConnectionFactory { public IDbConnection CreateConnection()=>new SqlConnection(value); } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 52fb2e29..98861e7f 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -15,6 +15,7 @@ using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; +if(args.Contains("--locations-workspace-database")){await LocationsWorkspaceDatabaseTests.Run(args.Last());return;} if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;} if(args.Contains("--shared-focus-cleanup")){await SharedFocusDatabaseTests.Concurrent(true);return;} if(args.Contains("--relationship-workspace")){RelationshipWorkspaceTests.StateAndEditing();Console.WriteLine("PASS main Relationships canonical editing, historical resolution and isolated author-family access");return;} diff --git a/PlotLine.Tests/Sql/LocationsWorkspace.sql b/PlotLine.Tests/Sql/LocationsWorkspace.sql new file mode 100644 index 00000000..3852f5e5 --- /dev/null +++ b/PlotLine.Tests/Sql/LocationsWorkspace.sql @@ -0,0 +1,110 @@ +-- Run ONLY on a disposable qualification clone after 335. All fixture writes roll back. +SET NOCOUNT ON; +IF DB_NAME() NOT LIKE N'PlotDirector_Qualification_Locations%' THROW 51000,'Disposable Locations qualification clone required.',1; +DECLARE @p int,@u int; +SELECT TOP(1) @p=p.ProjectID,@u=a.UserID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.IsArchived=0 AND a.IsActive=1 AND a.AccessRole=N'Owner' ORDER BY p.ProjectID; +IF @p IS NULL THROW 51000,'An existing clone-only owner fixture is required.',1; +DECLARE @scene int=(SELECT TOP(1) s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@p); +IF @scene IS NULL THROW 51000,'Clone project scene fixture required.',1; +DECLARE @a int,@b int,@c int,@d int,@changes nvarchar(max),@old datetime2,@updated datetime2; +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName,Description) VALUES(@p,N'Workspace test root',N'Author prose');SET @a=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Workspace test child',@a);SET @b=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Workspace test grandchild',@b);SET @c=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Workspace destination');SET @d=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@d) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@a,@b) FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes; +IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@a)<>@d OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@b)<>@a OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@c)<>@b THROW 51000,'Bulk move flattened a branch.',1; +-- Selecting an already-placed ancestor must still protect its selected descendant. +SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@d) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@a,@b) FOR JSON PATH); +SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a; +EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes; +IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@b)<>@a OR (SELECT UpdatedDate FROM dbo.Locations WHERE LocationID=@a)<>@old THROW 51000,'No-op bulk move flattened a branch or changed its version.',1; +SELECT @changes=(SELECT LocationID AS Id,N'' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes; +IF EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND ParentLocationID IS NOT NULL) THROW 51000,'Root move failed.',1; +SELECT @changes=(SELECT LocationID AS Id,N'Fictional' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@a,@b) FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'classification',@changes; +IF EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID IN(@a,@b) AND ISNULL(Classification,N'')<>N'Fictional') THROW 51000,'Classification assignment failed.',1; +UPDATE dbo.Scenes SET PrimaryLocationID=@a WHERE SceneID=@scene; +SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a; +SELECT @changes=(SELECT LocationID AS Id,N'Workspace renamed' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'name',@changes; +IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND LocationName=N'Workspace renamed' AND Description=N'Author prose' AND Classification=N'Fictional') THROW 51000,'Rename overwrote unrelated data.',1; +IF (SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@scene)<>@a THROW 51000,'Rename changed the recorded scene assignment.',1; +-- Exact-value restore uses the post-save version and preserves unrelated fields. +SELECT @changes=(SELECT LocationID AS Id,N'Workspace test root' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'name',@changes,1; +IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND LocationName=N'Workspace test root' AND Description=N'Author prose') THROW 51000,'Undo failed.',1; +DECLARE @leaf int; +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Other branch leaf',@d);SET @leaf=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,N'' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@b,@leaf) FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes; +SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),CASE WHEN LocationID=@b THEN @a ELSE @d END) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@b,@leaf) FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes,1; +IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@b)<>@a OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@leaf)<>@d OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@c)<>@b THROW 51000,'Bulk parent undo did not restore each original branch.',1; +ROLLBACK; +PRINT 'PASS bulk branch preservation, root moves, classification, targeted rename, exact undo'; +-- Expected failures roll back the complete transaction, including their fixtures. +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Cycle root');SET @a=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Cycle child',@a);SET @b=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@b) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +BEGIN TRY + EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes; + THROW 51099,'Cycle accepted.',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH; +PRINT 'PASS descendant cycle rejection'; +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Unavailable parent test');SET @a=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,N'2147483647' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;THROW 51099,'Unavailable parent accepted.',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH; +PRINT 'PASS unavailable parent rejection'; +BEGIN TRAN; +DECLARE @other int=(SELECT TOP(1) ProjectID FROM dbo.Projects WHERE ProjectID<>@p); +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Cross-project source');SET @a=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@other,N'Cross-project destination');SET @b=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@b) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;THROW 51099,'Cross-project parent accepted.',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH; +PRINT 'PASS cross-project parent rejection'; +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Stale test');SET @a=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,N'Real' AS Value,N'2000-01-01' AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'classification',@changes;THROW 51099,'Stale update accepted.',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51011 THROW; END CATCH; +PRINT 'PASS stale write rejection'; +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Unauthorized test');SET @a=SCOPE_IDENTITY(); +SELECT @changes=(SELECT LocationID AS Id,N'Real' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,-2147483647,N'classification',@changes;THROW 51099,'Unauthorized update accepted.',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51010 THROW; END CATCH; +PRINT 'PASS unauthorized mutation rejection'; +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName,Description,Classification) VALUES(@p,N'Merge source',N'Source prose',N'Fictional');SET @a=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,Description) VALUES(@p,N'Merge survivor',N'Survivor prose');SET @b=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Merge child',@a);SET @c=SCOPE_IDENTITY(); +UPDATE dbo.Scenes SET PrimaryLocationID=@a WHERE SceneID=@scene; +DECLARE @relationshipType int=(SELECT TOP(1) LocationRelationshipTypeID FROM dbo.LocationRelationshipTypes WHERE IsActive=1),@relationship int,@direct int; +INSERT dbo.LocationRelationships(FromLocationID,ToLocationID,LocationRelationshipTypeID,CanHearNormalSpeech,Notes) VALUES(@a,@c,@relationshipType,1,N'Preserve authored relationship');SET @relationship=SCOPE_IDENTITY(); +INSERT dbo.LocationRelationships(FromLocationID,ToLocationID,LocationRelationshipTypeID,Notes) VALUES(@a,@b,@relationshipType,N'Direct relationship preserved archived');SET @direct=SCOPE_IDENTITY(); +INSERT dbo.LocationAliases(LocationID,Alias,SortOrder) VALUES(@a,N'Former source name',10); +DECLARE @map int,@feature uniqueidentifier=NEWID(),@plan int; +INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@p,N'Workspace merge map',N'Local');SET @map=SCOPE_IDENTITY(); +INSERT dbo.MapFeatures(MapID,FeatureID,Name,Type,GeometryClass,Layer,X,Y,Width,Height,Rotation,ZOrder,IsPlaced,IsProvisional,IsLocked,ShowLabel,LabelX,LabelY,LocationID,GeometryJson) +VALUES(@map,@feature,N'Preserved marker',N'Location',N'Marker',N'Places',10,20,5,5,0,0,1,0,0,1,0,0,@a,N'{"fixture":"unchanged"}'); +INSERT dbo.FloorPlans(ProjectID,Name,LocationID) VALUES(@p,N'Workspace merge floor plan',@a);SET @plan=SCOPE_IDENTITY(); +SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a;SELECT @updated=UpdatedDate FROM dbo.Locations WHERE LocationID=@b; +EXEC dbo.Location_WorkspaceMerge @p,@u,@a,@b,@old,@updated; +IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND IsArchived=1 AND Description=N'Source prose') THROW 51000,'Merge source not preserved.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@b AND Description LIKE N'%Source prose%' AND Description LIKE N'%Survivor prose%' AND Classification=N'Fictional') THROW 51000,'Merge discarded description/classification.',1; +IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@c)<>@b THROW 51000,'Merge child not transferred.',1; +IF (SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@scene)<>@b THROW 51000,'Merge lost the scene assignment.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.LocationRelationships WHERE LocationRelationshipID=@relationship AND FromLocationID=@b AND ToLocationID=@c AND CanHearNormalSpeech=1 AND Notes=N'Preserve authored relationship' AND IsArchived=0) THROW 51000,'Merge lost the authored non-hierarchical relationship.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.LocationRelationships WHERE LocationRelationshipID=@direct AND FromLocationID=@a AND ToLocationID=@b AND IsArchived=1) THROW 51000,'Merge did not preserve the archived direct relationship.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.LocationAliases WHERE LocationID=@b AND Alias=N'Former source name') THROW 51000,'Merge lost aliases.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID=@feature AND LocationID=@b AND X=10 AND Y=20 AND GeometryJson=N'{"fixture":"unchanged"}') THROW 51000,'Merge changed map identity/geometry or lost its association.',1; +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'; diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index acd797b4..c4349a19 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -271,6 +271,11 @@ internal static class ToolbarBrowserHost app.MapGet("/relationship-main-state-fixture",async (HttpContext context)=>await context.Response.WriteAsJsonAsync(await RelationshipWorkspaceTests.LargeFixture(int.TryParse(context.Request.Query["cast"],out var n)?Math.Clamp(n,1,200):75,context.Request.Query["network"].ToString(),int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:null))); app.MapGet("/relationship-main-family-fixture",async (HttpContext context)=>{var model=await RelationshipWorkspaceTests.LargeFixture(int.TryParse(context.Request.Query["cast"],out var n)?Math.Clamp(n,1,200):75,"family");await context.Response.WriteAsJsonAsync(new{canEdit=true,relationships=model.Relationships,nodes=model.Cast.Select(c=>new{id=c.CharacterID,name=c.CharacterName,birthDate=(string?)null})});}); app.MapGet("/character-attribute-definitions-fixture",()=>Results.Json(CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male",IsSystem=true},new(){CharacterSexValueID=2,SexName="Female",IsSystem=true},new(){CharacterSexValueID=3,SexName="Custom recorded sex"}]).Select(g=>new{g.Id,g.Label,values=g.Values.Select(CharacterQuickAttributes.Presentation),fallback=g.RecordedFallback is {} fallback?CharacterQuickAttributes.Presentation(fallback):null}))); + app.MapGet("/locations-workspace-types-fixture",()=>Results.Json(new[]{"Country","Region","Town","Building","Floor","Room","Outdoor Area","Vehicle Interior","Planet"}.Select((name,i)=>LocationWorkspaceIcons.Presentation((i+1).ToString(),name)))); + app.MapGet("/locations-workspace-fixture",async (HttpContext context)=>{ + var count=int.TryParse(context.Request.Query["count"],out var n)?Math.Clamp(n,1,2000):50; + await RenderFullAsync(context,"Locations","Index",new LocationListViewModel{Project=new(){ProjectID=7,ProjectName="The Meridian Atlas",AccessRole="Owner"},Locations=Enumerable.Range(1,count).Select(i=>new LocationItem{LocationID=i,ProjectID=7,ParentLocationID=i==1||i%13==0?null:i<12?i-1:((i-2)/12)*12+1,LocationName=i==1?"Meridian":i==2?"Northern coast":i==3?"Port Halcyon":i==4?"Observatory":i==5?"Reading room":$"Location {i:D3}",LocationTypeID=i%4+1,LocationTypeName=new[]{"Region","Town","Building","Room"}[i%4],Depth=Math.Min(i-1,10),LocationPath=$"Meridian / Northern coast / Location {i:D3}",Description=string.Join(" ",Enumerable.Repeat("Salt air drifts through the open windows. The old survey charts record a coastline changed by generations of storms.",i%7+1)),UpdatedDate=new DateTime(2026,11,27,0,0,0,DateTimeKind.Utc)}).ToArray()}); + }); app.MapGet("/character-attributes-fixture",async (HttpContext context)=>{ var count=int.TryParse(context.Request.Query["count"],out var n)?Math.Clamp(n,1,500):10; await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Character attribute acceptance fixture",AccessRole="Owner"},Characters=Enumerable.Range(1,count).Select(i=>new Character{CharacterID=i,ProjectID=7,CharacterName=$"Fixture character {i:D3}",CharacterImportance=i%3==0?10:i%3==1?6:2,DefaultDescription=string.Join(" ",Enumerable.Repeat($"Complete biography for character {i}: remembered history, motivations and relationships.",i%9+1))}).ToArray()}); diff --git a/PlotLine/Controllers/LocationWorkspaceController.cs b/PlotLine/Controllers/LocationWorkspaceController.cs new file mode 100644 index 00000000..b2e8ac4e --- /dev/null +++ b/PlotLine/Controllers/LocationWorkspaceController.cs @@ -0,0 +1,133 @@ +using System.Data; +using System.Security.Cryptography; +using System.Text.Json; +using Dapper; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Data.SqlClient; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.Services.Context; + +namespace PlotLine.Controllers; + +[Authorize] +public sealed class LocationWorkspaceController(ISqlConnectionFactory connections, ICurrentUserService user, + IProjectRepository projects, ContextWorkspaceNotifications notifications, IDataProtectionProvider protection) : Controller +{ + public sealed record Alias(int LocationID, string Value); + public sealed record Link(int LocationID, int ID, string Name, string Kind); + public sealed record Usage(int LocationID, int SceneCount); + public sealed record Option(int ID, string Name); + public sealed record Change(int Id, string Value, string Version); + public sealed record Assignment(int ProjectId, string Attribute, Change[] Changes); + public sealed record Receipt(int User, int ProjectId, string Attribute, Change[] Changes, DateTime Expires); + public sealed record UndoRequest(string Token); + public sealed record CreateRequest(int ProjectId, string Name, int? ParentId); + private IDataProtector Protector => protection.CreateProtector("LocationWorkspace.Undo.v1"); + + [HttpGet] + public async Task Directory(int projectId) + { + if (user.UserId is not int author) return Unauthorized(); + var project = await projects.GetForUserAsync(projectId, author); + if (project is null) return NotFound(); + using var db = connections.CreateConnection(); + using var result = await db.QueryMultipleAsync("dbo.Location_WorkspaceRead", new { ProjectID = projectId, UserID = author }, commandType: CommandType.StoredProcedure); + var records = (await result.ReadAsync()).ToArray(); + var aliases = (await result.ReadAsync()).ToLookup(a => a.LocationID, a => a.Alias); + var maps = (await result.ReadAsync()).ToLookup(a => a.LocationID); + var floors = (await result.ReadAsync()).ToLookup(a => a.LocationID); + var usage = (await result.ReadAsync()).ToDictionary(a => a.LocationID, a => a.SceneCount); + var types = (await result.ReadAsync