diff --git a/.gitignore b/.gitignore index 5eddd35..b2b8378 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ frontend/coverage/ .DS_Store Thumbs.db +.codex/config.toml diff --git a/README.md b/README.md index d0db98e..2b78d6a 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ and mitigation vertical slice: - Ranked, evidence-backed replacement recommendations - Persisted parent/child mitigation simulations with idempotent replay - Stateless impact and mitigation previews for user-built draft organizations +- Stable public organization IDs and refresh-safe links for reopening editable + organization maps, inventories, and impact screens - Draft recommendations that verify eligibility and workflow recovery after the proposed role assignment, even when the candidate does not already have the access that the new role would grant @@ -60,9 +62,11 @@ docker compose up -d In a second terminal, start the API: ```powershell -.\backend\mvnw.cmd spring-boot:run +\.\backend\mvnw.cmd spring-boot:run -Dspring-boot.run.profiles=dev ``` +With the `dev` profile active, Boot UI is available at . + In a third terminal, install and start the frontend: ```powershell @@ -75,6 +79,25 @@ amber impact paths, review Bob Chen's recommendation, and test the mitigation to see the restored green relationship graph alongside the Low residual access impact. +Editable organizations can be reopened from the homepage using their public ID +with or without the displayed hyphen. Anyone with an organization ID or link can +edit that organization in this portfolio MVP, so do not enter confidential or +personal data. + +## Frontend routes + +- `/example` opens the read-only Harborline example. +- `/organizations/{publicCode}/map` opens an editable organization map. +- `/organizations/{publicCode}/inventory` opens its detailed inventory. +- `/organizations/{publicCode}/impact` opens a fresh impact-testing screen. + +Refreshing any of these routes keeps the same organization and screen. Impact +and mitigation results are intentionally temporary, so refreshing the impact +route clears the previous result while preserving the selected screen. Vite's +development and preview servers provide the required history fallback locally. +Production hosting must rewrite non-asset, non-API routes to +`frontend/index.html` so pasted organization links load correctly. + ## API endpoints - `GET /api/v1/dashboard` loads the default Harborline Commerce dashboard. @@ -84,6 +107,12 @@ impact. - `GET /api/v1/simulations/{simulationId}` retrieves an immutable saved result. - `POST /api/v1/simulations/{simulationId}/branches` tests and saves a recommendation as a child mitigation simulation. +- `POST /api/v1/workspaces` creates a blank editable organization and returns + its stable public code. +- `GET /api/v1/workspaces/by-code/{publicCode}` resolves an editable + organization. The Harborline example is intentionally excluded. +- `GET /api/v1/workspaces/{workspaceId}/catalog` loads the editable catalog + after the public code has been resolved. - `POST /api/v1/workspaces/{workspaceId}/impact-previews` tests a role removal against the current draft without changing it. - `POST /api/v1/workspaces/{workspaceId}/impact-previews/mitigations` verifies a diff --git a/backend/pom.xml b/backend/pom.xml index 4d9024a..b000ee9 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 3.5.16 + 4.1.0 com.roleimpact @@ -28,7 +28,23 @@ 21 + 1.14.1 + 3.1.5 + 2.21.5 + 2.25.5 + 42.7.12 + + + + com.fasterxml.jackson + jackson-bom + ${jackson2-bom.version} + pom + import + + + org.springframework.boot @@ -39,8 +55,8 @@ spring-boot-starter-data-jpa - org.flywaydb - flyway-core + org.springframework.boot + spring-boot-starter-flyway org.springframework.boot @@ -50,11 +66,22 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-jackson2 + org.flywaydb flyway-database-postgresql + + com.julien-dubois.bootui + bootui-spring-boot-starter + ${bootui.version} + runtime + + org.postgresql postgresql @@ -65,6 +92,11 @@ spring-boot-starter-test test + + org.springframework.boot + spring-boot-starter-webmvc-test + test + org.springframework.boot spring-boot-testcontainers @@ -72,12 +104,12 @@ org.testcontainers - junit-jupiter + testcontainers-junit-jupiter test org.testcontainers - postgresql + testcontainers-postgresql test diff --git a/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java b/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java index bad1008..c9ff79b 100644 --- a/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java +++ b/backend/src/main/java/com/roleimpact/catalog/persistence/EmployeeEntity.java @@ -12,9 +12,17 @@ import jakarta.persistence.Enumerated; import jakarta.persistence.Id; import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; @Entity -@Table(name = "employees") +@Table(name = "employees", uniqueConstraints = { + @UniqueConstraint( + name = "uq_employees_organization_employee_no", + columnNames = { "organization_id", "employee_no" }), + @UniqueConstraint( + name = "uq_employees_organization_email", + columnNames = { "organization_id", "email" }) +}) public class EmployeeEntity { @Id @@ -26,13 +34,13 @@ public class EmployeeEntity { @Column(name = "team_id", nullable = false) private UUID teamId; - @Column(name = "employee_no", unique = true, length = 40) + @Column(name = "employee_no", length = 40) private String employeeNumber; @Column(nullable = false, length = 160) private String name; - @Column(unique = true, length = 254) + @Column(length = 254) private String email; @Enumerated(EnumType.STRING) diff --git a/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java b/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java index dcffb9a..f6cd7a9 100644 --- a/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java +++ b/backend/src/main/java/com/roleimpact/impactengine/DeterministicImpactEngine.java @@ -59,7 +59,6 @@ public final class DeterministicImpactEngine implements ImpactEngine { public static final String SCHEMA_VERSION = REQUEST_SCHEMA_VERSION; public static final String ENGINE_VERSION = "1.2.0"; - private static final int MAX_RECOMMENDATIONS = 2; private static final Comparator UUID_ORDER = Comparator.comparing(UUID::toString); private static final Comparator ENTITY_ORDER = Comparator .comparing(EntityRef::name) @@ -848,7 +847,6 @@ private static RecommendationOutcome recommendMitigations( var role = snapshot.roles().get(roleId); var orderedCandidates = safeCandidates.stream() .sorted(RECOMMENDATION_ORDER) - .limit(MAX_RECOMMENDATIONS) .toList(); var recommendations = new ArrayList(); for (var index = 0; index < orderedCandidates.size(); index++) { diff --git a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java index ba89a03..865a1c4 100644 --- a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java +++ b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java @@ -1,7 +1,6 @@ package com.roleimpact.workspace.api; import java.net.URI; -import java.util.List; import java.util.UUID; import com.roleimpact.workspace.application.WorkspaceService; @@ -27,32 +26,25 @@ public WorkspaceController(WorkspaceService workspaceService) { this.workspaceService = workspaceService; } - @GetMapping - public List list() { - return workspaceService.list(); - } - @GetMapping("/{workspaceId}") public WorkspaceResource get(@PathVariable UUID workspaceId) { return workspaceService.get(workspaceId); } + @GetMapping("/by-code/{publicCode}") + public WorkspaceResource getByCode(@PathVariable String publicCode) { + return workspaceService.getEditableByCode(publicCode); + } + @PostMapping public ResponseEntity create(@Valid @RequestBody WorkspaceRequest request) { return created(workspaceService.createBlank(request)); } - @PostMapping("/{sourceWorkspaceId}/clones") - public ResponseEntity clone( - @PathVariable UUID sourceWorkspaceId, - @Valid @RequestBody WorkspaceRequest request) { - return created(workspaceService.clonePublished(sourceWorkspaceId, request)); - } - private ResponseEntity created(WorkspaceResource workspace) { URI location = ServletUriComponentsBuilder.fromCurrentContextPath() - .path("/api/v1/workspaces/{id}") - .buildAndExpand(workspace.id()) + .path("/api/v1/workspaces/by-code/{publicCode}") + .buildAndExpand(workspace.publicCode()) .toUri(); return ResponseEntity.created(location).body(workspace); } diff --git a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java index ce3b010..8a46b30 100644 --- a/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java +++ b/backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java @@ -9,7 +9,7 @@ public record WorkspaceResource( String name, String status, int currentVersion, - UUID sourceTemplateOrganizationId, + String publicCode, Instant createdAt, Instant updatedAt, WorkspaceCounts counts) { diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java new file mode 100644 index 0000000..32c682b --- /dev/null +++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java @@ -0,0 +1,69 @@ +package com.roleimpact.workspace.application; + +import java.security.SecureRandom; +import java.text.Normalizer; +import java.util.Arrays; +import java.util.Locale; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Component; + +@Component +public class WorkspaceCode { + + private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + private static final int TOKEN_LENGTH = 16; + private static final Pattern SHORT_COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{19}$"); + private static final Pattern SHORT_DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{16}$"); + private static final Pattern LONG_COMPACT = Pattern.compile("^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$"); + private static final Pattern LONG_DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$"); + + private final SecureRandom random; + + public WorkspaceCode() { + this(new SecureRandom()); + } + + WorkspaceCode(SecureRandom random) { + this.random = random; + } + + public String generate(String organizationName) { + String asciiName = Normalizer.normalize(organizationName, Normalizer.Form.NFD) + .replaceAll("\\p{M}", "") + .toUpperCase(Locale.ROOT); + String initials = Arrays.stream(asciiName.split("[^A-Z0-9]+")) + .filter(token -> !token.isBlank()) + .map(token -> token.substring(0, 1)) + .collect(Collectors.joining()); + String compactName = asciiName.replaceAll("[^A-Z0-9]", ""); + String prefixSeed = sanitize(initials + compactName + "ORG"); + StringBuilder token = new StringBuilder(TOKEN_LENGTH); + for (int index = 0; index < TOKEN_LENGTH; index++) { + token.append(ALPHABET.charAt(random.nextInt(ALPHABET.length()))); + } + return prefixSeed.substring(0, 3) + "-" + token; + } + + public static String normalize(String rawCode) { + if (rawCode == null) { + return null; + } + String candidate = rawCode.trim().toUpperCase(Locale.ROOT); + if (SHORT_COMPACT.matcher(candidate).matches() || LONG_COMPACT.matcher(candidate).matches()) { + candidate = candidate.substring(0, 3) + "-" + candidate.substring(3); + } + return SHORT_DISPLAYED.matcher(candidate).matches() || LONG_DISPLAYED.matcher(candidate).matches() + ? candidate + : null; + } + + private static String sanitize(String value) { + return value.replace('O', 'Q') + .replace('I', 'J') + .replace('0', '2') + .replace('1', '3') + .replaceAll("[^A-HJ-NP-Z2-9]", ""); + } +} diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java index 2ba9209..ca2e55e 100644 --- a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java +++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java @@ -7,4 +7,8 @@ public class WorkspaceNotFoundException extends RuntimeException { public WorkspaceNotFoundException(UUID id) { super("Workspace not found: " + id); } + + public WorkspaceNotFoundException(String publicCode) { + super("Organization not found: " + publicCode); + } } diff --git a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java index 9cf14bf..9058a51 100644 --- a/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java +++ b/backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java @@ -1,7 +1,6 @@ package com.roleimpact.workspace.application; import java.text.Normalizer; -import java.util.List; import java.util.Locale; import java.util.UUID; @@ -9,7 +8,6 @@ import com.roleimpact.workspace.api.WorkspaceResource; import com.roleimpact.workspace.persistence.WorkspaceRepository; -import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -17,14 +15,11 @@ public class WorkspaceService { private final WorkspaceRepository workspaceRepository; + private final WorkspaceCode workspaceCode; - public WorkspaceService(WorkspaceRepository workspaceRepository) { + public WorkspaceService(WorkspaceRepository workspaceRepository, WorkspaceCode workspaceCode) { this.workspaceRepository = workspaceRepository; - } - - @Transactional(readOnly = true) - public List list() { - return workspaceRepository.findAll(); + this.workspaceCode = workspaceCode; } @Transactional(readOnly = true) @@ -33,43 +28,39 @@ public WorkspaceResource get(UUID id) { .orElseThrow(() -> new WorkspaceNotFoundException(id)); } - @Transactional - public WorkspaceResource createBlank(WorkspaceRequest request) { - String name = request.name().trim(); - String slug = resolveSlug(request, name); - UUID workspaceId = UUID.randomUUID(); - - insertDraft(workspaceId, slug, name, null); - return get(workspaceId); + @Transactional(readOnly = true) + public WorkspaceResource getEditableByCode(String rawCode) { + String publicCode = WorkspaceCode.normalize(rawCode); + if (publicCode == null) { + throw new WorkspaceNotFoundException(rawCode); + } + return workspaceRepository.findDraftByPublicCode(publicCode) + .orElseThrow(() -> new WorkspaceNotFoundException(rawCode)); } @Transactional - public WorkspaceResource clonePublished(UUID sourceId, WorkspaceRequest request) { - String status = workspaceRepository.findStatus(sourceId) - .orElseThrow(() -> new WorkspaceNotFoundException(sourceId)); - if (!"PUBLISHED".equals(status)) { - throw new WorkspaceValidationException("Only a published workspace can be cloned"); - } - + public WorkspaceResource createBlank(WorkspaceRequest request) { String name = request.name().trim(); String slug = resolveSlug(request, name); - UUID workspaceId = UUID.randomUUID(); - - insertDraft(workspaceId, slug, name, sourceId); - workspaceRepository.cloneCatalog(sourceId, workspaceId); - return get(workspaceId); - } - - private void insertDraft(UUID id, String slug, String name, UUID sourceTemplateId) { if (workspaceRepository.existsBySlug(slug)) { - throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists"); - } - try { - workspaceRepository.insertDraft(id, slug, name, sourceTemplateId); + throw slugConflict(slug); } - catch (DataIntegrityViolationException exception) { - throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists"); + + for (int attempt = 0; attempt < 5; attempt++) { + UUID workspaceId = UUID.randomUUID(); + String publicCode = workspaceCode.generate(name); + if (workspaceRepository.insertDraft(workspaceId, slug, name, publicCode)) { + return get(workspaceId); + } + if (workspaceRepository.existsBySlug(slug)) { + throw slugConflict(slug); + } } + throw new WorkspaceConflictException("A unique organization ID could not be generated; try again"); + } + + private WorkspaceConflictException slugConflict(String slug) { + return new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists"); } private String resolveSlug(WorkspaceRequest request, String name) { diff --git a/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java b/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java index a1d01e1..d84093b 100644 --- a/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java +++ b/backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java @@ -168,7 +168,7 @@ public DraftCatalogResource addWorkflowRequirement( throw new DraftCatalogNotFoundException("Workflow", workflowId); } if (!repository.quickWorkflowExists(workspaceId, workflowId)) { - throw new DraftCatalogConflictException("The example workflow is read-only for now; clone its pattern into a custom workflow to edit requirements"); + throw new DraftCatalogConflictException("The example workflow is read-only; create a custom workflow to edit requirements"); } requireRole(workspaceId, request.roleId()); requireCoverage(request.minimumActors(), request.resilienceTarget()); diff --git a/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java b/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java index 8e6577e..0e87212 100644 --- a/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java +++ b/backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java @@ -3,6 +3,6 @@ public class PublishedWorkspaceMutationException extends RuntimeException { public PublishedWorkspaceMutationException() { - super("Published workspaces are immutable; clone this workspace before editing it"); + super("Published examples are read-only; create a new organization to make changes"); } } diff --git a/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java b/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java index 062dc88..382699b 100644 --- a/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java +++ b/backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java @@ -2,7 +2,6 @@ import java.sql.Timestamp; import java.time.Instant; -import java.util.List; import java.util.Optional; import java.util.UUID; @@ -17,7 +16,7 @@ public class WorkspaceRepository { private static final String WORKSPACE_SELECT = """ SELECT o.id, o.slug, o.name, o.workspace_status, o.current_version, - o.source_template_organization_id, o.created_at, o.updated_at, + o.public_code, o.created_at, o.updated_at, (SELECT COUNT(*) FROM teams t WHERE t.organization_id = o.id) AS team_count, (SELECT COUNT(*) FROM employees e WHERE e.organization_id = o.id) AS member_count, (SELECT COUNT(*) FROM roles r WHERE r.organization_id = o.id) AS role_count, @@ -33,12 +32,6 @@ public WorkspaceRepository(JdbcClient jdbcClient) { this.jdbcClient = jdbcClient; } - public List findAll() { - return jdbcClient.sql(WORKSPACE_SELECT + " ORDER BY o.created_at, o.id") - .query(this::mapWorkspace) - .list(); - } - public Optional findById(UUID id) { return jdbcClient.sql(WORKSPACE_SELECT + " WHERE o.id = :id") .param("id", id) @@ -46,6 +39,14 @@ public Optional findById(UUID id) { .optional(); } + public Optional findDraftByPublicCode(String publicCode) { + return jdbcClient.sql(WORKSPACE_SELECT + + " WHERE UPPER(o.public_code) = :publicCode AND o.workspace_status = 'DRAFT'") + .param("publicCode", publicCode) + .query(this::mapWorkspace) + .optional(); + } + public boolean existsBySlug(String slug) { return jdbcClient.sql("SELECT EXISTS (SELECT 1 FROM organizations WHERE slug = :slug)") .param("slug", slug) @@ -53,218 +54,22 @@ public boolean existsBySlug(String slug) { .single(); } - public Optional findStatus(UUID id) { - return jdbcClient.sql("SELECT workspace_status FROM organizations WHERE id = :id") - .param("id", id) - .query(String.class) - .optional(); - } - - public void insertDraft(UUID id, String slug, String name, UUID sourceTemplateId) { - jdbcClient.sql(""" + public boolean insertDraft(UUID id, String slug, String name, String publicCode) { + return jdbcClient.sql(""" INSERT INTO organizations ( id, slug, name, current_version, workspace_status, - source_template_organization_id, created_at, updated_at + public_code, created_at, updated_at ) VALUES ( - :id, :slug, :name, 0, 'DRAFT', :sourceTemplateId, + :id, :slug, :name, 0, 'DRAFT', :publicCode, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP ) + ON CONFLICT DO NOTHING """) .param("id", id) .param("slug", slug) .param("name", name) - .param("sourceTemplateId", sourceTemplateId) - .update(); - } - - public void cloneCatalog(UUID sourceId, UUID targetId) { - jdbcClient.sql(""" - CREATE TEMP TABLE workspace_clone_ids ( - entity_type VARCHAR(20) NOT NULL, - source_id UUID NOT NULL, - target_id UUID NOT NULL, - PRIMARY KEY (entity_type, source_id) - ) ON COMMIT DROP - """).update(); - - mapIds("team", "teams", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO teams (id, organization_id, name, department, manager_employee_id) - SELECT m.target_id, :targetId, t.name, t.department, NULL - FROM teams t - JOIN workspace_clone_ids m ON m.entity_type = 'team' AND m.source_id = t.id - WHERE t.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - - mapIds("employee", "employees", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO employees ( - id, organization_id, team_id, employee_no, name, email, status, region, shift - ) - SELECT em.target_id, :targetId, tm.target_id, e.employee_no, e.name, e.email, - e.status, e.region, e.shift - FROM employees e - JOIN workspace_clone_ids em ON em.entity_type = 'employee' AND em.source_id = e.id - JOIN workspace_clone_ids tm ON tm.entity_type = 'team' AND tm.source_id = e.team_id - WHERE e.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - jdbcClient.sql(""" - UPDATE teams target_team - SET manager_employee_id = manager_map.target_id - FROM teams source_team - JOIN workspace_clone_ids team_map - ON team_map.entity_type = 'team' AND team_map.source_id = source_team.id - JOIN workspace_clone_ids manager_map - ON manager_map.entity_type = 'employee' - AND manager_map.source_id = source_team.manager_employee_id - WHERE target_team.id = team_map.target_id - AND source_team.organization_id = :sourceId - """).param("sourceId", sourceId).update(); - - mapIds("role", "roles", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO roles (id, organization_id, name, description, sensitivity, owner_employee_id) - SELECT rm.target_id, :targetId, r.name, r.description, r.sensitivity, owner_map.target_id - FROM roles r - JOIN workspace_clone_ids rm ON rm.entity_type = 'role' AND rm.source_id = r.id - LEFT JOIN workspace_clone_ids owner_map - ON owner_map.entity_type = 'employee' AND owner_map.source_id = r.owner_employee_id - WHERE r.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - jdbcClient.sql(""" - INSERT INTO employee_roles (employee_id, role_id, assigned_at, assigned_by) - SELECT em.target_id, rm.target_id, er.assigned_at, 'workspace clone' - FROM employee_roles er - JOIN workspace_clone_ids em ON em.entity_type = 'employee' AND em.source_id = er.employee_id - JOIN workspace_clone_ids rm ON rm.entity_type = 'role' AND rm.source_id = er.role_id - """).update(); - - mapIds("application", "applications", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO applications (id, organization_id, name, category, owner_employee_id) - SELECT am.target_id, :targetId, a.name, a.category, owner_map.target_id - FROM applications a - JOIN workspace_clone_ids am ON am.entity_type = 'application' AND am.source_id = a.id - LEFT JOIN workspace_clone_ids owner_map - ON owner_map.entity_type = 'employee' AND owner_map.source_id = a.owner_employee_id - WHERE a.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - - mapIdsThroughOrganization("resource", "resources", "application_id", "applications", sourceId); - jdbcClient.sql(""" - INSERT INTO resources (id, application_id, name, resource_type) - SELECT res_map.target_id, app_map.target_id, r.name, r.resource_type - FROM resources r - JOIN workspace_clone_ids res_map ON res_map.entity_type = 'resource' AND res_map.source_id = r.id - JOIN workspace_clone_ids app_map ON app_map.entity_type = 'application' AND app_map.source_id = r.application_id - """).update(); - - mapIds("permission", "permissions", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO permissions ( - id, organization_id, application_id, resource_id, action, sensitivity - ) - SELECT pm.target_id, :targetId, am.target_id, rm.target_id, p.action, p.sensitivity - FROM permissions p - JOIN workspace_clone_ids pm ON pm.entity_type = 'permission' AND pm.source_id = p.id - JOIN workspace_clone_ids am ON am.entity_type = 'application' AND am.source_id = p.application_id - JOIN workspace_clone_ids rm ON rm.entity_type = 'resource' AND rm.source_id = p.resource_id - WHERE p.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - jdbcClient.sql(""" - INSERT INTO role_permissions (role_id, permission_id) - SELECT rm.target_id, pm.target_id - FROM role_permissions rp - JOIN workspace_clone_ids rm ON rm.entity_type = 'role' AND rm.source_id = rp.role_id - JOIN workspace_clone_ids pm ON pm.entity_type = 'permission' AND pm.source_id = rp.permission_id - """).update(); - - mapIds("capability", "capabilities", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO capabilities (id, organization_id, name, description) - SELECT cm.target_id, :targetId, c.name, c.description - FROM capabilities c - JOIN workspace_clone_ids cm ON cm.entity_type = 'capability' AND cm.source_id = c.id - WHERE c.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - jdbcClient.sql(""" - INSERT INTO capability_permissions (capability_id, permission_id) - SELECT cm.target_id, pm.target_id - FROM capability_permissions cp - JOIN workspace_clone_ids cm ON cm.entity_type = 'capability' AND cm.source_id = cp.capability_id - JOIN workspace_clone_ids pm ON pm.entity_type = 'permission' AND pm.source_id = cp.permission_id - """).update(); - - mapIds("workflow", "workflows", "organization_id", sourceId); - jdbcClient.sql(""" - INSERT INTO workflows (id, organization_id, name, criticality, owner_employee_id) - SELECT wm.target_id, :targetId, w.name, w.criticality, owner_map.target_id - FROM workflows w - JOIN workspace_clone_ids wm ON wm.entity_type = 'workflow' AND wm.source_id = w.id - LEFT JOIN workspace_clone_ids owner_map - ON owner_map.entity_type = 'employee' AND owner_map.source_id = w.owner_employee_id - WHERE w.organization_id = :sourceId - """).param("targetId", targetId).param("sourceId", sourceId).update(); - - mapIdsThroughOrganization("workflow_step", "workflow_steps", "workflow_id", "workflows", sourceId); - jdbcClient.sql(""" - INSERT INTO workflow_steps ( - id, workflow_id, step_key, name, position, required_capability_id, - minimum_actors, resilience_target, required_department, required_region, - required_shift, required_application_id - ) - SELECT sm.target_id, wm.target_id, s.step_key, s.name, s.position, cm.target_id, - s.minimum_actors, s.resilience_target, s.required_department, s.required_region, - s.required_shift, am.target_id - FROM workflow_steps s - JOIN workspace_clone_ids sm ON sm.entity_type = 'workflow_step' AND sm.source_id = s.id - JOIN workspace_clone_ids wm ON wm.entity_type = 'workflow' AND wm.source_id = s.workflow_id - JOIN workspace_clone_ids cm ON cm.entity_type = 'capability' AND cm.source_id = s.required_capability_id - LEFT JOIN workspace_clone_ids am - ON am.entity_type = 'application' AND am.source_id = s.required_application_id - """).update(); - - mapIdsThroughOrganization("constraint", "workflow_constraints", "workflow_id", "workflows", sourceId); - jdbcClient.sql(""" - INSERT INTO workflow_constraints (id, workflow_id, type, parameters) - SELECT cm.target_id, wm.target_id, c.type, c.parameters - FROM workflow_constraints c - JOIN workspace_clone_ids cm ON cm.entity_type = 'constraint' AND cm.source_id = c.id - JOIN workspace_clone_ids wm ON wm.entity_type = 'workflow' AND wm.source_id = c.workflow_id - """).update(); - jdbcClient.sql(""" - INSERT INTO workflow_step_constraints (workflow_step_id, constraint_id) - SELECT sm.target_id, cm.target_id - FROM workflow_step_constraints sc - JOIN workspace_clone_ids sm ON sm.entity_type = 'workflow_step' AND sm.source_id = sc.workflow_step_id - JOIN workspace_clone_ids cm ON cm.entity_type = 'constraint' AND cm.source_id = sc.constraint_id - """).update(); - } - - private void mapIds(String entityType, String table, String organizationColumn, UUID sourceId) { - String sql = "INSERT INTO workspace_clone_ids (entity_type, source_id, target_id) " - + "SELECT :entityType, id, gen_random_uuid() FROM " + table - + " WHERE " + organizationColumn + " = :sourceId"; - jdbcClient.sql(sql) - .param("entityType", entityType) - .param("sourceId", sourceId) - .update(); - } - - private void mapIdsThroughOrganization( - String entityType, - String table, - String parentColumn, - String parentTable, - UUID sourceId) { - String sql = "INSERT INTO workspace_clone_ids (entity_type, source_id, target_id) " - + "SELECT :entityType, child.id, gen_random_uuid() FROM " + table + " child " - + "JOIN " + parentTable + " parent ON parent.id = child." + parentColumn + " " - + "WHERE parent.organization_id = :sourceId"; - jdbcClient.sql(sql) - .param("entityType", entityType) - .param("sourceId", sourceId) - .update(); + .param("publicCode", publicCode) + .update() == 1; } private WorkspaceResource mapWorkspace(java.sql.ResultSet resultSet, int rowNumber) throws java.sql.SQLException { @@ -276,7 +81,7 @@ private WorkspaceResource mapWorkspace(java.sql.ResultSet resultSet, int rowNumb resultSet.getString("name"), resultSet.getString("workspace_status"), resultSet.getInt("current_version"), - resultSet.getObject("source_template_organization_id", UUID.class), + resultSet.getString("public_code"), toInstant(createdAt), toInstant(updatedAt), new WorkspaceCounts( diff --git a/backend/src/main/resources/application-dev.yml b/backend/src/main/resources/application-dev.yml new file mode 100644 index 0000000..f6c5884 --- /dev/null +++ b/backend/src/main/resources/application-dev.yml @@ -0,0 +1,7 @@ +bootui: + enabled: true + +management: + endpoint: + health: + show-details: always diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index 67a7a62..77713f6 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -12,7 +12,13 @@ spring: flyway: enabled: true +bootui: + enabled: false + management: + endpoint: + health: + show-details: never endpoints: web: exposure: diff --git a/backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql b/backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql new file mode 100644 index 0000000..8057daa --- /dev/null +++ b/backend/src/main/resources/db/migration/V10__allow_shorter_organization_public_codes.sql @@ -0,0 +1,9 @@ +ALTER TABLE organizations + DROP CONSTRAINT IF EXISTS ck_organizations_public_code_format; + +ALTER TABLE organizations + ADD CONSTRAINT ck_organizations_public_code_format + CHECK ( + public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{16}$' + OR public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$' + ); diff --git a/backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql b/backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql new file mode 100644 index 0000000..3a1edf4 --- /dev/null +++ b/backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql @@ -0,0 +1,53 @@ +ALTER TABLE organizations ADD COLUMN public_code VARCHAR(10); + +CREATE FUNCTION pg_temp.encode_workspace_number(value BIGINT) +RETURNS TEXT +LANGUAGE plpgsql +AS $$ +DECLARE + alphabet CONSTANT TEXT := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + encoded TEXT := ''; + remainder INTEGER; +BEGIN + FOR position IN 1..6 LOOP + remainder := MOD(value, 32); + encoded := SUBSTRING(alphabet FROM remainder + 1 FOR 1) || encoded; + value := value / 32; + END LOOP; + RETURN encoded; +END; +$$; + +WITH ranked_organizations AS ( + SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS code_number + FROM organizations +) +UPDATE organizations organization +SET public_code = RPAD( + SUBSTRING( + TRANSLATE( + COALESCE(NULLIF(UPPER(REGEXP_REPLACE(organization.name, '[^A-Za-z0-9]', '', 'g')), ''), 'ORG'), + 'OI01', + 'QJ23' + ) + FROM 1 FOR 3 + ), + 3, + 'X' + ) || '-' || pg_temp.encode_workspace_number(ranked.code_number) +FROM ranked_organizations ranked +WHERE ranked.id = organization.id; + +ALTER TABLE organizations + ALTER COLUMN public_code SET NOT NULL, + ADD CONSTRAINT ck_organizations_public_code_format + CHECK (public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$'); + +CREATE UNIQUE INDEX uq_organizations_public_code_ci + ON organizations (UPPER(public_code)); + +DROP INDEX IF EXISTS idx_organizations_source_template; + +ALTER TABLE organizations + DROP CONSTRAINT IF EXISTS ck_organizations_not_own_template, + DROP COLUMN source_template_organization_id; diff --git a/backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql b/backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql new file mode 100644 index 0000000..1877b2e --- /dev/null +++ b/backend/src/main/resources/db/migration/V8__add_foreign_key_supporting_indexes.sql @@ -0,0 +1,5 @@ +CREATE INDEX idx_permissions_resource_application + ON permissions(resource_id, application_id); + +CREATE INDEX idx_simulations_organization_baseline_version + ON simulations(organization_id, baseline_version); diff --git a/backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql b/backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql new file mode 100644 index 0000000..1bdf17c --- /dev/null +++ b/backend/src/main/resources/db/migration/V9__strengthen_organization_public_codes.sql @@ -0,0 +1,14 @@ +ALTER TABLE organizations + DROP CONSTRAINT IF EXISTS ck_organizations_public_code_format; + +ALTER TABLE organizations + ALTER COLUMN public_code TYPE VARCHAR(36); + +UPDATE organizations +SET public_code = SUBSTRING(public_code FROM 1 FOR 3) + || '-' + || UPPER(MD5(gen_random_uuid()::TEXT || gen_random_uuid()::TEXT || id::TEXT)); + +ALTER TABLE organizations + ADD CONSTRAINT ck_organizations_public_code_format + CHECK (public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$'); diff --git a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java index 213659d..d84d9ff 100644 --- a/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java +++ b/backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java @@ -22,13 +22,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.jdbc.core.simple.JdbcClient; import org.springframework.test.web.servlet.MockMvc; -import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; @SpringBootTest @Testcontainers @@ -42,7 +42,7 @@ class CatalogMigrationIntegrationTest { @Container @ServiceConnection - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:17-alpine") + static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine") .withDatabaseName("roleimpact") .withUsername("roleimpact") .withPassword("roleimpact"); @@ -74,6 +74,26 @@ class CatalogMigrationIntegrationTest { @Autowired private ObjectMapper objectMapper; + @Test + void assignsPublicCodesAndRemovesCloneMetadata() { + var publicCodes = jdbcClient.sql("SELECT public_code FROM organizations ORDER BY id") + .query(String.class) + .list(); + var cloneColumnCount = jdbcClient.sql(""" + SELECT COUNT(*) + FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name = 'organizations' + AND column_name = 'source_template_organization_id' + """).query(Integer.class).single(); + + assertThat(publicCodes).isNotEmpty() + .allSatisfy(code -> assertThat(code).matches("[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}")); + assertThat(publicCodes.stream().map(String::toUpperCase).distinct().count()) + .isEqualTo(publicCodes.size()); + assertThat(cloneColumnCount).isZero(); + } + @Test void appliesSchemaAndLoadsTheCompleteHarborlineBaseline() { assertThat(count("organizations")).isEqualTo(1); @@ -95,7 +115,7 @@ SELECT COUNT(*) .query(Integer.class) .single(); - assertThat(successfulMigrations).isEqualTo(6); + assertThat(successfulMigrations).isEqualTo(10); var employeeNumberNullable = jdbcClient.sql(""" SELECT is_nullable FROM information_schema.columns @@ -104,6 +124,24 @@ SELECT COUNT(*) assertThat(employeeNumberNullable).isEqualTo("YES"); } + @Test + void addsCompositeIndexesForForeignKeyLookups() { + var indexes = jdbcClient.sql(""" + SELECT indexname + FROM pg_indexes + WHERE schemaname = 'public' + AND indexname IN ( + 'idx_permissions_resource_application', + 'idx_simulations_organization_baseline_version' + ) + ORDER BY indexname + """).query(String.class).list(); + + assertThat(indexes).containsExactly( + "idx_permissions_resource_application", + "idx_simulations_organization_baseline_version"); + } + @Test void mapsSeededCatalogDataThroughJpa() { var organization = organizationRepository.findBySlug("harborline-commerce").orElseThrow(); diff --git a/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java b/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java index 27454f4..7bbbf8b 100644 --- a/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java +++ b/backend/src/test/java/com/roleimpact/impactengine/DeterministicImpactEngineTest.java @@ -51,6 +51,9 @@ class DeterministicImpactEngineTest { private static final UUID OLIVIA_ID = id("20000000", 3); private static final UUID DYLAN_ID = id("20000000", 4); private static final UUID INEZ_ID = id("20000000", 5); + private static final UUID ALICE_ID = id("20000000", 6); + private static final UUID CARLOS_ID = id("20000000", 7); + private static final UUID ELENA_ID = id("20000000", 8); private static final UUID FINANCE_ANALYST_ID = id("30000000", 1); private static final UUID FINANCE_APPROVER_ID = id("30000000", 2); private static final UUID CLOSE_BACKUP_ID = id("30000000", 3); @@ -113,6 +116,18 @@ void recommendsBobWithStableEvidenceAndExplainsUnsafeCandidates() { .containsExactly(CandidateExclusionReasonCode.SOURCE_EMPLOYEE); } + @Test + void returnsEverySafeReplacementCandidateInRankOrder() { + var result = engine.analyze(snapshotWithAdditionalSafeCandidates(), revokePriyaApprover()); + + assertThat(result.recommendations()) + .extracting(recommendation -> recommendation.candidate().name()) + .containsExactly("Bob Chen", "Alice Morgan", "Carlos Ruiz", "Elena Rossi"); + assertThat(result.recommendations()) + .extracting(recommendation -> recommendation.rank()) + .containsExactly(1, 2, 3, 4); + } + @Test void producesTheSameResultAndHashRegardlessOfSnapshotInsertionOrder() { var first = engine.analyze(snapshot(false, false), revokePriyaApprover()); @@ -411,6 +426,28 @@ private static OrganizationSnapshot snapshot(boolean reverseOrder, boolean overl Map.entry(APPROVE_PAYMENT_STEP_ID, linkedSet(DIFFERENT_ACTORS_ID))))); } + private static OrganizationSnapshot snapshotWithAdditionalSafeCandidates() { + var baseline = snapshot(false, false); + var employees = new LinkedHashMap<>(baseline.employees()); + employees.put(ALICE_ID, employee(ALICE_ID, "Alice Morgan", EmployeeStatus.ACTIVE, WorkShift.EVENING)); + employees.put(CARLOS_ID, employee(CARLOS_ID, "Carlos Ruiz", EmployeeStatus.ACTIVE, WorkShift.EVENING)); + employees.put(ELENA_ID, employee(ELENA_ID, "Elena Rossi", EmployeeStatus.ACTIVE, WorkShift.EVENING)); + return new OrganizationSnapshot( + baseline.organization(), + baseline.teams(), + employees, + baseline.roles(), + baseline.applications(), + baseline.resources(), + baseline.permissions(), + baseline.capabilities(), + baseline.workflows(), + baseline.roleIdsByEmployeeId(), + baseline.permissionIdsByRoleId(), + baseline.permissionIdsByCapabilityId(), + baseline.constraintIdsByWorkflowStepId()); + } + private static EmployeeNode employee( UUID id, String name, diff --git a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java index b2927ef..5000eaf 100644 --- a/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java +++ b/backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java @@ -16,15 +16,15 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.http.MediaType; import org.springframework.jdbc.core.simple.JdbcClient; import org.springframework.test.web.servlet.MockMvc; -import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; @SpringBootTest @Testcontainers @@ -35,7 +35,7 @@ class WorkspaceIntegrationTest { @Container @ServiceConnection - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:17-alpine") + static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine") .withDatabaseName("roleimpact") .withUsername("roleimpact") .withPassword("roleimpact"); @@ -50,90 +50,56 @@ class WorkspaceIntegrationTest { private JdbcClient jdbcClient; @Test - void createsBlankAndClonedDraftsWithoutChangingThePublishedTemplate() throws Exception { - mockMvc.perform(get("/api/v1/workspaces")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id").value(HARBORLINE_ID.toString())) - .andExpect(jsonPath("$[0].status").value("PUBLISHED")) - .andExpect(jsonPath("$[0].currentVersion").value(1)) - .andExpect(jsonPath("$[0].counts.members").value(25)) - .andExpect(jsonPath("$[0].counts.workflows").value(4)); - + void createsAndResolvesAnEditableDraftByPublicCode() throws Exception { var blankResponse = mockMvc.perform(post("/api/v1/workspaces") .contentType(MediaType.APPLICATION_JSON) - .content(workspaceRequest("Northstar Labs", null))) + .content(workspaceRequest("Northstar Medical Supplies", null))) .andExpect(status().isCreated()) - .andExpect(header().string("Location", org.hamcrest.Matchers.containsString("/api/v1/workspaces/"))) - .andExpect(jsonPath("$.slug").value("northstar-labs")) + .andExpect(header().string("Location", org.hamcrest.Matchers.containsString("/api/v1/workspaces/by-code/"))) + .andExpect(jsonPath("$.slug").value("northstar-medical-supplies")) .andExpect(jsonPath("$.status").value("DRAFT")) .andExpect(jsonPath("$.currentVersion").value(0)) - .andExpect(jsonPath("$.sourceTemplateOrganizationId").doesNotExist()) + .andExpect(jsonPath("$.publicCode") + .value(org.hamcrest.Matchers.matchesPattern("NMS-[A-HJ-NP-Z2-9]{16}"))) .andExpect(jsonPath("$.counts.members").value(0)) .andExpect(jsonPath("$.counts.workflows").value(0)) .andReturn(); - UUID blankId = responseId(blankResponse.getResponse().getContentAsString()); - - var cloneResponse = mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", HARBORLINE_ID) - .contentType(MediaType.APPLICATION_JSON) - .content(workspaceRequest("Harborline Sandbox", "harborline-sandbox"))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.status").value("DRAFT")) - .andExpect(jsonPath("$.currentVersion").value(0)) - .andExpect(jsonPath("$.sourceTemplateOrganizationId").value(HARBORLINE_ID.toString())) - .andExpect(jsonPath("$.counts.teams").value(5)) - .andExpect(jsonPath("$.counts.members").value(25)) - .andExpect(jsonPath("$.counts.roles").value(8)) - .andExpect(jsonPath("$.counts.permissions").value(23)) - .andExpect(jsonPath("$.counts.capabilities").value(10)) - .andExpect(jsonPath("$.counts.workflows").value(4)) - .andReturn(); - UUID cloneId = responseId(cloneResponse.getResponse().getContentAsString()); + var blankJson = objectMapper.readTree(blankResponse.getResponse().getContentAsString()); + UUID blankId = UUID.fromString(blankJson.path("id").asText()); + String publicCode = blankJson.path("publicCode").asText(); - mockMvc.perform(get("/api/v1/workspaces/{workspaceId}", cloneId)) + mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", publicCode.toLowerCase())) .andExpect(status().isOk()) - .andExpect(jsonPath("$.slug").value("harborline-sandbox")); + .andExpect(jsonPath("$.id").value(blankId.toString())) + .andExpect(jsonPath("$.publicCode").value(publicCode)); assertThat(workspaceState(HARBORLINE_ID)).isEqualTo("PUBLISHED|1"); assertThat(workspaceState(blankId)).isEqualTo("DRAFT|0"); - assertThat(workspaceState(cloneId)).isEqualTo("DRAFT|0"); - assertThat(countOrganizationVersions(cloneId)).isZero(); - assertThat(countSharedEmployeeIds(HARBORLINE_ID, cloneId)).isZero(); - assertThat(countNamedEmployees(cloneId, "Priya Sharma")).isOne(); - - var clonedCatalog = mockMvc.perform(get("/api/v1/workspaces/{workspaceId}/catalog", cloneId)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.workflows[?(@.name == 'Vendor Payment')].requirements[?(@.name == 'High-Value Payment Approval')]").exists()) - .andReturn(); - var catalogJson = objectMapper.readTree(clonedCatalog.getResponse().getContentAsString()); - UUID priyaId = findId(catalogJson, "members", "Priya Sharma"); - UUID aishaId = findId(catalogJson, "members", "Aisha Khan"); - UUID sofiaId = findId(catalogJson, "members", "Sofia Martinez"); - UUID financeApproverId = findId(catalogJson, "roles", "Finance Approver"); - UUID seniorSupportId = findId(catalogJson, "roles", "Senior Support"); - UUID supportAgentId = findId(catalogJson, "roles", "Support Agent"); - assertPreview(cloneId, priyaId, financeApproverId, "CRITICAL", 1, 1); - assertPreview(cloneId, aishaId, seniorSupportId, "MEDIUM", 0, 1); - assertPreview(cloneId, sofiaId, supportAgentId, "LOW", 0, 0); - - UUID clonedWorkflowId = UUID.fromString(catalogJson - .path("workflows").get(0).path("id").asText()); - mockMvc.perform(delete("/api/v1/workspaces/{workspaceId}/catalog/workflows/{workflowId}", cloneId, clonedWorkflowId)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.workflows.length()").value(3)); - assertThat(countForOrganization("workflows", cloneId)).isEqualTo(3); - assertThat(countForOrganization("workflows", HARBORLINE_ID)).isEqualTo(4); + } - mockMvc.perform(post("/api/v1/workspaces") - .contentType(MediaType.APPLICATION_JSON) - .content(workspaceRequest("Duplicate", "harborline-sandbox"))) - .andExpect(status().isConflict()) - .andExpect(jsonPath("$.code").value("WORKSPACE_CONFLICT")); + @Test + void hidesPublishedAndUnknownOrganizationsFromPublicCodeLookup() throws Exception { + String harborlinePublicCode = jdbcClient.sql("SELECT public_code FROM organizations WHERE id = :id") + .param("id", HARBORLINE_ID) + .query(String.class) + .single(); + + mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", harborlinePublicCode)) + .andExpect(status().isNotFound()); + mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", "BAD-CODE")) + .andExpect(status().isNotFound()); + mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", "NMS-AAAAAA")) + .andExpect(status().isNotFound()); + } - mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", blankId) + @Test + void removesWorkspaceListingAndCloningEndpoints() throws Exception { + mockMvc.perform(get("/api/v1/workspaces")) + .andExpect(status().isMethodNotAllowed()); + mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", HARBORLINE_ID) .contentType(MediaType.APPLICATION_JSON) - .content(workspaceRequest("Invalid Clone", null))) - .andExpect(status().isUnprocessableEntity()) - .andExpect(jsonPath("$.code").value("INVALID_WORKSPACE")); + .content(workspaceRequest("Removed Clone", null))) + .andExpect(status().isNotFound()); } @Test @@ -398,7 +364,7 @@ void buildsTeamsMembersAndRolesInsideADraftOnly() throws Exception { .contentType(MediaType.APPLICATION_JSON) .content("{\"name\":\"Illegal\",\"department\":\"Test\"}")) .andExpect(status().isConflict()) - .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("immutable"))); + .andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("read-only"))); mockMvc.perform(delete("/api/v1/workspaces/{workspaceId}/catalog/workflows/{workflowId}", workspaceId, workflowId)) .andExpect(status().isOk()) @@ -446,24 +412,6 @@ private com.fasterxml.jackson.databind.JsonNode findById( throw new IllegalArgumentException(id + " was not found in " + collection); } - private void assertPreview( - UUID workspaceId, - UUID memberId, - UUID roleId, - String severity, - int blocked, - int degraded) throws Exception { - mockMvc.perform(post("/api/v1/workspaces/{workspaceId}/impact-previews", workspaceId) - .contentType(MediaType.APPLICATION_JSON) - .content(""" - {"memberId":"%s","roleId":"%s"} - """.formatted(memberId, roleId))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.overallSeverity").value(severity)) - .andExpect(jsonPath("$.executiveSummary.workflowsBlocked").value(blocked)) - .andExpect(jsonPath("$.executiveSummary.workflowsDegraded").value(degraded)); - } - private String workspaceState(UUID id) { return jdbcClient.sql(""" SELECT workspace_status || '|' || current_version @@ -472,26 +420,6 @@ private String workspaceState(UUID id) { """).param("id", id).query(String.class).single(); } - private int countOrganizationVersions(UUID id) { - return jdbcClient.sql("SELECT COUNT(*) FROM organization_versions WHERE organization_id = :id") - .param("id", id).query(Integer.class).single(); - } - - private int countSharedEmployeeIds(UUID sourceId, UUID cloneId) { - return jdbcClient.sql(""" - SELECT COUNT(*) - FROM employees source - JOIN employees clone ON clone.id = source.id - WHERE source.organization_id = :sourceId AND clone.organization_id = :cloneId - """).param("sourceId", sourceId).param("cloneId", cloneId).query(Integer.class).single(); - } - - private int countNamedEmployees(UUID organizationId, String name) { - return jdbcClient.sql(""" - SELECT COUNT(*) FROM employees WHERE organization_id = :organizationId AND name = :name - """).param("organizationId", organizationId).param("name", name).query(Integer.class).single(); - } - private int countForOrganization(String table, UUID organizationId) { var allowed = java.util.Set.of("applications", "permissions", "capabilities", "workflows"); if (!allowed.contains(table)) throw new IllegalArgumentException("Unexpected table: " + table); diff --git a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java new file mode 100644 index 0000000..929bd4f --- /dev/null +++ b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java @@ -0,0 +1,39 @@ +package com.roleimpact.workspace.application; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.security.SecureRandom; + +import org.junit.jupiter.api.Test; + +class WorkspaceCodeTest { + + @Test + void normalizesTypedCodesWithOrWithoutTheHyphen() { + var displayed = "NSM-7K4P9D8XM2QR6WBC"; + + assertThat(WorkspaceCode.normalize(" " + displayed.toLowerCase() + " ")).isEqualTo(displayed); + assertThat(WorkspaceCode.normalize(displayed.replace("-", ""))).isEqualTo(displayed); + } + + @Test + void keepsExistingLongCodesValid() { + var existing = "NSM-0123456789ABCDEF0123456789ABCDEF"; + + assertThat(WorkspaceCode.normalize(existing)).isEqualTo(existing); + } + + @Test + void rejectsMalformedOrAmbiguousCodes() { + assertThat(WorkspaceCode.normalize("NSM-7K4P0D")).isNull(); + assertThat(WorkspaceCode.normalize("NSM-7K4P9D")).isNull(); + assertThat(WorkspaceCode.normalize("not-a-code")).isNull(); + } + + @Test + void generatesANamePrefixAndAn80BitRandomSuffix() { + var code = new WorkspaceCode(new SecureRandom()).generate("Northstar Medical Supplies"); + + assertThat(code).matches("NMS-[A-HJ-NP-Z2-9]{16}"); + } +} diff --git a/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java new file mode 100644 index 0000000..d708db0 --- /dev/null +++ b/backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java @@ -0,0 +1,59 @@ +package com.roleimpact.workspace.application; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; + +import com.roleimpact.workspace.api.WorkspaceRequest; +import com.roleimpact.workspace.api.WorkspaceResource; +import com.roleimpact.workspace.persistence.WorkspaceRepository; + +import org.junit.jupiter.api.Test; +class WorkspaceServiceTest { + + @Test + void retriesAPublicCodeCollisionWithoutChangingTheSlug() { + var repository = mock(WorkspaceRepository.class); + var workspaceCode = mock(WorkspaceCode.class); + when(repository.existsBySlug("northstar-medical-supplies")).thenReturn(false); + when(workspaceCode.generate("Northstar Medical Supplies")) + .thenReturn("NMS-AAAAAA", "NMS-AAAAAB"); + when(repository.insertDraft( + any(UUID.class), + eq("northstar-medical-supplies"), + eq("Northstar Medical Supplies"), + eq("NMS-AAAAAA"))).thenReturn(false); + when(repository.insertDraft( + any(UUID.class), + eq("northstar-medical-supplies"), + eq("Northstar Medical Supplies"), + eq("NMS-AAAAAB"))).thenReturn(true); + when(repository.findById(any(UUID.class))).thenAnswer(invocation -> Optional.of( + workspace(invocation.getArgument(0), "NMS-AAAAAB"))); + + var service = new WorkspaceService(repository, workspaceCode); + var created = service.createBlank(new WorkspaceRequest("Northstar Medical Supplies", null)); + + assertThat(created.publicCode()).isEqualTo("NMS-AAAAAB"); + } + + private WorkspaceResource workspace(UUID id, String publicCode) { + var timestamp = Instant.parse("2026-08-21T12:00:00Z"); + return new WorkspaceResource( + id, + "northstar-medical-supplies", + "Northstar Medical Supplies", + "DRAFT", + 0, + publicCode, + timestamp, + timestamp, + new WorkspaceResource.WorkspaceCounts(0, 0, 0, 0, 0, 0)); + } +} diff --git a/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java b/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java index ceb505d..9b741c7 100644 --- a/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java +++ b/backend/src/test/java/com/roleimpact/workspace/preview/application/DraftContinuityProjectionConcurrencyIntegrationTest.java @@ -20,15 +20,15 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.http.MediaType; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.web.servlet.MockMvc; -import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; @SpringBootTest @Testcontainers @@ -37,7 +37,7 @@ class DraftContinuityProjectionConcurrencyIntegrationTest { @Container @ServiceConnection - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:17-alpine") + static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine") .withDatabaseName("roleimpact") .withUsername("roleimpact") .withPassword("roleimpact"); diff --git a/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md b/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md new file mode 100644 index 0000000..0b2696c --- /dev/null +++ b/docs/superpowers/plans/2026-08-21-organization-deep-linking-implementation-plan.md @@ -0,0 +1,905 @@ +# Organization Deep Linking and Recovery Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give every editable organization a stable public code and refresh-safe nested URL while removing Harborline cloning from the product and backend. + +**Architecture:** PostgreSQL keeps UUIDs as internal entity identifiers and gains a unique `public_code` locator on `organizations`. Spring resolves a public code once and continues serving catalog and impact APIs by UUID; React Router becomes the source of truth for home, example, map, inventory, and impact screens. + +**Tech Stack:** Java 21, Spring Boot 3.5, Spring JDBC, Flyway, PostgreSQL 17, React 19, TypeScript 6, React Router 7, TanStack Query 5, Vitest, Testing Library, Maven, Vite. + +**Spec:** `docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md` + +## Global Constraints + +- UUID primary and foreign keys remain the internal data model. +- Public organization codes are stable, case-insensitive, random locators in the displayed form `ABC-XXXXXX`. +- The random alphabet excludes `0`, `O`, `1`, and `I`. +- Organization codes do not change when an organization is renamed. +- Anyone with an editable organization link or code can edit it in this portfolio MVP; the UI must warn against entering sensitive data. +- Impact and mitigation results remain temporary and are cleared by an impact-route refresh. +- Harborline remains read-only at `/example` and cannot be opened through the editable code endpoint. +- Previously cloned organizations remain ordinary editable drafts; no organization or catalog record is deleted. +- The all-workspaces endpoint, clone endpoint, clone SQL, clone metadata, and clone-specific UI are removed. +- Existing uncommitted graph and recommendation-transparency changes must be preserved and committed independently from this feature. +- Production code follows test-first red-green-refactor cycles. + +--- + +### Task 1: Add the public-code database contract and remove clone metadata + +**Files:** +- Create: `backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql` +- Modify: `backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java` + +**Interfaces:** +- Consumes: the `organizations` table produced by migrations V1 through V6. +- Produces: non-null `organizations.public_code VARCHAR(10)`, unique index `uq_organizations_public_code_ci`, and a schema without `source_template_organization_id` or `idx_organizations_source_template`. + +- [ ] **Step 1: Add a failing migration-contract test** + +Add this test to `CatalogMigrationIntegrationTest`: + +```java +@Test +void assignsPublicCodesAndRemovesCloneMetadata() { + var publicCodes = jdbcClient.sql("SELECT public_code FROM organizations ORDER BY id") + .query(String.class) + .list(); + var cloneColumnCount = jdbcClient.sql(""" + SELECT COUNT(*) + FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name = 'organizations' + AND column_name = 'source_template_organization_id' + """).query(Integer.class).single(); + + assertThat(publicCodes).isNotEmpty() + .allSatisfy(code -> assertThat(code).matches("[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}")); + assertThat(publicCodes.stream().map(String::toUpperCase).distinct().count()) + .isEqualTo(publicCodes.size()); + assertThat(cloneColumnCount).isZero(); +} +``` + +- [ ] **Step 2: Run the migration test and verify the expected failure** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml -Dtest=CatalogMigrationIntegrationTest#assignsPublicCodesAndRemovesCloneMetadata test +``` + +Expected: FAIL because `organizations.public_code` does not exist. + +- [ ] **Step 3: Add migration V7** + +Create the migration with these operations: + +```sql +ALTER TABLE organizations ADD COLUMN public_code VARCHAR(10); + +CREATE FUNCTION pg_temp.encode_workspace_number(value BIGINT) +RETURNS TEXT +LANGUAGE plpgsql +AS $$ +DECLARE + alphabet CONSTANT TEXT := 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + encoded TEXT := ''; + remainder INTEGER; +BEGIN + FOR position IN 1..6 LOOP + remainder := MOD(value, 32); + encoded := SUBSTRING(alphabet FROM remainder + 1 FOR 1) || encoded; + value := value / 32; + END LOOP; + RETURN encoded; +END; +$$; + +WITH ranked_organizations AS ( + SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS code_number + FROM organizations +) +UPDATE organizations organization +SET public_code = RPAD( + SUBSTRING( + TRANSLATE( + COALESCE(NULLIF(UPPER(REGEXP_REPLACE(organization.name, '[^A-Za-z0-9]', '', 'g')), ''), 'ORG'), + 'OI01', + 'QJ23' + ) + FROM 1 FOR 3 + ), + 3, + 'X' + ) || '-' || pg_temp.encode_workspace_number(ranked.code_number) +FROM ranked_organizations ranked +WHERE ranked.id = organization.id; + +ALTER TABLE organizations + ALTER COLUMN public_code SET NOT NULL, + ADD CONSTRAINT ck_organizations_public_code_format + CHECK (public_code ~ '^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$'); + +CREATE UNIQUE INDEX uq_organizations_public_code_ci + ON organizations (UPPER(public_code)); + +DROP INDEX IF EXISTS idx_organizations_source_template; + +ALTER TABLE organizations + DROP CONSTRAINT IF EXISTS ck_organizations_not_own_template, + DROP COLUMN source_template_organization_id; +``` + +The ranked Base32-style suffix makes every backfilled code unique without relying on a truncated UUID collision probability. V7 never updates organization IDs or dependent catalog rows. + +- [ ] **Step 4: Run the migration test and the full migration suite** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml -Dtest=CatalogMigrationIntegrationTest test +``` + +Expected: PASS, including the public-code schema assertions and all seed-data assertions. + +- [ ] **Step 5: Commit the migration contract** + +```powershell +git add backend/src/main/resources/db/migration/V7__add_organization_public_codes.sql backend/src/test/java/com/roleimpact/catalog/persistence/CatalogMigrationIntegrationTest.java +git commit -m "feat: add stable organization public codes" +``` + +--- + +### Task 2: Implement public-code generation, lookup, and clone removal in Spring + +**Files:** +- Create: `backend/src/main/java/com/roleimpact/workspace/application/WorkspaceCode.java` +- Create: `backend/src/test/java/com/roleimpact/workspace/application/WorkspaceCodeTest.java` +- Create: `backend/src/test/java/com/roleimpact/workspace/application/WorkspaceServiceTest.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/api/WorkspaceController.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/api/WorkspaceResource.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/application/WorkspaceNotFoundException.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/application/WorkspaceService.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/persistence/WorkspaceRepository.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/editor/application/DraftCatalogService.java` +- Modify: `backend/src/main/java/com/roleimpact/workspace/editor/application/PublishedWorkspaceMutationException.java` +- Modify: `backend/src/test/java/com/roleimpact/workspace/WorkspaceIntegrationTest.java` + +**Interfaces:** +- Consumes: `organizations.public_code` from Task 1. +- Produces: `WorkspaceCode.generate(String)`, `WorkspaceCode.normalize(String)`, `WorkspaceService.getEditableByCode(String)`, `WorkspaceRepository.findDraftByPublicCode(String)`, and `GET /api/v1/workspaces/by-code/{publicCode}`. +- Produces: `WorkspaceResource.publicCode()` and removes `sourceTemplateOrganizationId()`. + +- [ ] **Step 1: Write failing unit tests for the code value object** + +Create `WorkspaceCodeTest` with concrete cases: + +```java +class WorkspaceCodeTest { + @Test + void normalizesTypedCodesWithOrWithoutTheHyphen() { + assertThat(WorkspaceCode.normalize(" nsm-7k4p9d ")).isEqualTo("NSM-7K4P9D"); + assertThat(WorkspaceCode.normalize("nsm7k4p9d")).isEqualTo("NSM-7K4P9D"); + } + + @Test + void rejectsMalformedOrAmbiguousCodes() { + assertThat(WorkspaceCode.normalize("NSM-7K4P0D")).isNull(); + assertThat(WorkspaceCode.normalize("not-a-code")).isNull(); + } + + @Test + void generatesANamePrefixAndAllowedRandomSuffix() { + var code = new WorkspaceCode(new java.security.SecureRandom()).generate("Northstar Medical Supplies"); + assertThat(code).matches("NMS-[A-HJ-NP-Z2-9]{6}"); + } +} +``` + +- [ ] **Step 2: Run the unit test and verify the expected failure** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceCodeTest test +``` + +Expected: FAIL because `WorkspaceCode` does not exist. + +- [ ] **Step 3: Implement the code value object** + +Implement `WorkspaceCode` as a Spring component with: + +```java +@Component +public class WorkspaceCode { + private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + private static final Pattern DISPLAYED = Pattern.compile("^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{6}$"); + private final SecureRandom random; + + public WorkspaceCode() { + this(new SecureRandom()); + } + + WorkspaceCode(SecureRandom random) { + this.random = random; + } + + public String generate(String organizationName) { + String asciiName = Normalizer.normalize(organizationName, Normalizer.Form.NFD) + .replaceAll("\\p{M}", "") + .toUpperCase(Locale.ROOT); + String initials = Arrays.stream(asciiName.split("[^A-Z0-9]+")) + .filter(token -> !token.isBlank()) + .map(token -> token.substring(0, 1)) + .collect(Collectors.joining()); + String compact = asciiName.replaceAll("[^A-Z0-9]", ""); + String prefixSeed = sanitize(initials + compact + "ORG"); + StringBuilder suffix = new StringBuilder(6); + for (int index = 0; index < 6; index++) { + suffix.append(ALPHABET.charAt(random.nextInt(ALPHABET.length()))); + } + return prefixSeed.substring(0, 3) + "-" + suffix; + } + + public static String normalize(String rawCode) { + if (rawCode == null) return null; + String candidate = rawCode.trim().toUpperCase(Locale.ROOT); + if (candidate.matches("^[A-HJ-NP-Z2-9]{9}$")) { + candidate = candidate.substring(0, 3) + "-" + candidate.substring(3); + } + return DISPLAYED.matcher(candidate).matches() ? candidate : null; + } + + private static String sanitize(String value) { + return value.replace('O', 'Q').replace('I', 'J').replace('0', '2').replace('1', '3') + .replaceAll("[^A-HJ-NP-Z2-9]", ""); + } +} +``` + +Import `Normalizer`, `SecureRandom`, `Arrays`, `Locale`, `Pattern`, and `Collectors`. Appending the compact name and `ORG` guarantees a three-character prefix; `sanitize` removes ambiguous characters from the complete code. + +- [ ] **Step 4: Run `WorkspaceCodeTest` and verify it passes** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceCodeTest test +``` + +Expected: PASS. + +- [ ] **Step 5: Add a failing service test for public-code collision retry** + +Use Mockito to make the first generated code collide and the second succeed: + +```java +@ExtendWith(MockitoExtension.class) +class WorkspaceServiceTest { + @Mock WorkspaceRepository repository; + @Mock WorkspaceCode workspaceCode; + + @Test + void retriesAPublicCodeCollisionWithoutChangingTheSlug() { + when(repository.existsBySlug("northstar-medical-supplies")).thenReturn(false); + when(workspaceCode.generate("Northstar Medical Supplies")) + .thenReturn("NMS-AAAAAA", "NMS-AAAAAB"); + when(repository.insertDraft(any(UUID.class), eq("northstar-medical-supplies"), + eq("Northstar Medical Supplies"), eq("NMS-AAAAAA"))).thenReturn(false); + when(repository.insertDraft(any(UUID.class), eq("northstar-medical-supplies"), + eq("Northstar Medical Supplies"), eq("NMS-AAAAAB"))).thenReturn(true); + when(repository.findById(any(UUID.class))).thenAnswer(invocation -> Optional.of( + workspace(invocation.getArgument(0), "NMS-AAAAAB"))); + + var service = new WorkspaceService(repository, workspaceCode); + var created = service.createBlank(new WorkspaceRequest("Northstar Medical Supplies", null)); + + assertThat(created.publicCode()).isEqualTo("NMS-AAAAAB"); + verify(repository).insertDraft(any(UUID.class), eq("northstar-medical-supplies"), + eq("Northstar Medical Supplies"), eq("NMS-AAAAAA")); + verify(repository).insertDraft(any(UUID.class), eq("northstar-medical-supplies"), + eq("Northstar Medical Supplies"), eq("NMS-AAAAAB")); + } +} +``` + +Define the fixture in the same test class: + +```java +private WorkspaceResource workspace(UUID id, String publicCode) { + var timestamp = Instant.parse("2026-08-21T12:00:00Z"); + return new WorkspaceResource( + id, + "northstar-medical-supplies", + "Northstar Medical Supplies", + "DRAFT", + 0, + publicCode, + timestamp, + timestamp, + new WorkspaceResource.WorkspaceCounts(0, 0, 0, 0, 0, 0)); +} +``` + +- [ ] **Step 6: Run the collision test and verify the expected failure** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceServiceTest test +``` + +Expected: FAIL because `WorkspaceService` does not yet accept `WorkspaceCode` or retry a collision. + +- [ ] **Step 7: Replace the clone integration test with failing creation and lookup tests** + +In `WorkspaceIntegrationTest`, replace `createsBlankAndClonedDraftsWithoutChangingThePublishedTemplate` with tests that assert: + +```java +@Test +void createsAndResolvesAnEditableDraftByPublicCode() throws Exception { + var created = mockMvc.perform(post("/api/v1/workspaces") + .contentType(MediaType.APPLICATION_JSON) + .content(workspaceRequest("Northstar Medical Supplies", null))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.publicCode").value(org.hamcrest.Matchers.matchesPattern("NMS-[A-HJ-NP-Z2-9]{6}"))) + .andReturn(); + var resource = objectMapper.readTree(created.getResponse().getContentAsString()); + var publicCode = resource.path("publicCode").asText(); + + mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", publicCode.toLowerCase())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(resource.path("id").asText())) + .andExpect(jsonPath("$.status").value("DRAFT")); +} +``` + +Also add tests proving: + +```java +mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", "bad-code")) + .andExpect(status().isNotFound()); +mockMvc.perform(get("/api/v1/workspaces/by-code/{publicCode}", harborlinePublicCode)) + .andExpect(status().isNotFound()); +mockMvc.perform(get("/api/v1/workspaces")) + .andExpect(status().isMethodNotAllowed()); +mockMvc.perform(post("/api/v1/workspaces/{sourceWorkspaceId}/clones", HARBORLINE_ID) + .contentType(MediaType.APPLICATION_JSON) + .content(workspaceRequest("Removed Clone", null))) + .andExpect(status().isNotFound()); +``` + +- [ ] **Step 8: Run the Spring integration test and verify the expected failures** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml -Dtest=WorkspaceIntegrationTest test +``` + +Expected: FAIL because the resource has no public code, lookup is absent, and list/clone endpoints still exist. + +- [ ] **Step 9: Implement repository and service behavior** + +Change the workspace select and mapper to read `o.public_code`. Add: + +```java +public Optional findDraftByPublicCode(String publicCode) { + return jdbcClient.sql(WORKSPACE_SELECT + " WHERE UPPER(o.public_code) = :publicCode AND o.workspace_status = 'DRAFT'") + .param("publicCode", publicCode) + .query(this::mapWorkspace) + .optional(); +} + +public boolean insertDraft(UUID id, String slug, String name, String publicCode) { + return jdbcClient.sql(""" + INSERT INTO organizations ( + id, slug, name, current_version, workspace_status, public_code, created_at, updated_at + ) VALUES ( + :id, :slug, :name, 0, 'DRAFT', :publicCode, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP + ) + ON CONFLICT DO NOTHING + """) + .param("id", id) + .param("slug", slug) + .param("name", name) + .param("publicCode", publicCode) + .update() == 1; +} +``` + +Inject `WorkspaceCode` beside `WorkspaceRepository`. Change `WorkspaceService.createBlank` to generate a code and retry a public-code collision up to five times: + +```java +@Transactional +public WorkspaceResource createBlank(WorkspaceRequest request) { + String name = request.name().trim(); + String slug = resolveSlug(request, name); + if (workspaceRepository.existsBySlug(slug)) { + throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists"); + } + + for (int attempt = 0; attempt < 5; attempt++) { + UUID workspaceId = UUID.randomUUID(); + String publicCode = workspaceCode.generate(name); + if (workspaceRepository.insertDraft(workspaceId, slug, name, publicCode)) { + return get(workspaceId); + } + if (workspaceRepository.existsBySlug(slug)) { + throw new WorkspaceConflictException("A workspace with slug '" + slug + "' already exists"); + } + } + throw new WorkspaceConflictException("A unique organization ID could not be generated; try again"); +} +``` + +Add code lookup: + +```java +@Transactional(readOnly = true) +public WorkspaceResource getEditableByCode(String rawCode) { + String code = WorkspaceCode.normalize(rawCode); + if (code == null) throw new WorkspaceNotFoundException(rawCode); + return workspaceRepository.findDraftByPublicCode(code) + .orElseThrow(() -> new WorkspaceNotFoundException(rawCode)); +} +``` + +Remove `list`, `clonePublished`, `findAll`, `findStatus`, `cloneCatalog`, and the clone-ID mapping helpers. + +- [ ] **Step 10: Update the REST resource and controller** + +Replace `sourceTemplateOrganizationId` with `String publicCode` in `WorkspaceResource`. Add: + +```java +@GetMapping("/by-code/{publicCode}") +public WorkspaceResource getByCode(@PathVariable String publicCode) { + return workspaceService.getEditableByCode(publicCode); +} +``` + +Remove the list and clone mappings. Set the create response Location header to `/api/v1/workspaces/by-code/{publicCode}`. + +- [ ] **Step 11: Remove clone-specific messages** + +Change published mutation guidance to “Published examples are read-only; create a new organization to make changes.” Change the example workflow guidance to instruct users to create a custom workflow without mentioning cloning. + +- [ ] **Step 12: Run backend tests** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml test +``` + +Expected: PASS with no references to the removed clone endpoint or metadata. + +- [ ] **Step 13: Commit the backend API boundary** + +```powershell +git add backend/src +git commit -m "feat: resolve editable organizations by public code" +``` + +--- + +### Task 3: Replace homepage cloning with organization-code access + +**Files:** +- Modify: `frontend/src/api/workspaces.ts` +- Modify: `frontend/src/components/workspaces/WorkspaceWelcome.tsx` +- Modify: `frontend/src/App.css` +- Modify: `frontend/src/App.test.tsx` + +**Interfaces:** +- Consumes: `GET /api/v1/workspaces/by-code/{publicCode}` and `POST /api/v1/workspaces` from Task 2. +- Produces: `normalizeWorkspaceCode(rawCode): string | null`, `fetchWorkspaceByCode(rawCode, signal?)`, and a homepage with Explore, Open, and Create choices. + +- [ ] **Step 1: Add failing homepage tests** + +Update the test renderer to include `MemoryRouter` and accept `initialEntries`. Add tests that: + +```tsx +const linkedWorkspaceFixture: Workspace = { + id: '10000000-0000-0000-0000-000000000001', + slug: 'northstar-medical-supplies', + name: 'Northstar Medical Supplies', + status: 'DRAFT', + currentVersion: 0, + publicCode: 'NMS-7K4P9D', + createdAt: '2026-08-21T12:00:00Z', + updatedAt: '2026-08-21T12:00:00Z', + counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 }, +} +``` + +```tsx +it('opens an existing organization by a normalized code', async () => { + const user = userEvent.setup() + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + const url = input.toString() + if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture) + if (url.endsWith('/api/v1/workspaces/by-code/NMS-7K4P9D')) { + return jsonResponse(linkedWorkspaceFixture) + } + if (url.endsWith('/catalog')) return jsonResponse(blankCatalogFixture) + if (url.endsWith('/impact-previews/continuity')) return jsonResponse([]) + return new Response(null, { status: 404 }) + }) + renderApp(['/']) + await user.type(screen.getByLabelText('Organization ID'), ' nms7k4p9d ') + await user.click(screen.getByRole('button', { name: 'Open organization' })) + expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument() + expect(screen.getByText('NMS-7K4P9D')).toBeInTheDocument() +}) +``` + +Add assertions that the homepage has no “Clone Harborline” or “Clone and customize”, malformed codes show an inline message without a fetch, unknown codes show “Organization not found”, and a successful blank creation navigates to the new organization. + +- [ ] **Step 2: Run the homepage tests and verify the expected failures** + +Run: + +```powershell +npm --prefix frontend test -- --run src/App.test.tsx +``` + +Expected: FAIL because the homepage still lists workspaces and clones Harborline. + +- [ ] **Step 3: Replace the workspace API client** + +Change `Workspace` to include `publicCode: string` and remove `sourceTemplateOrganizationId`. Remove `fetchWorkspaces` and `cloneWorkspace`. Add: + +```ts +export function normalizeWorkspaceCode(rawCode: string): string | null { + const compact = rawCode.trim().toUpperCase().replace('-', '') + if (!/^[A-HJ-NP-Z2-9]{9}$/.test(compact)) return null + return `${compact.slice(0, 3)}-${compact.slice(3)}` +} + +export async function fetchWorkspaceByCode(rawCode: string, signal?: AbortSignal): Promise { + const code = normalizeWorkspaceCode(rawCode) + if (!code) throw new Error('Enter an organization ID such as NMS-7K4P9D') + const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/by-code/${code}`, { signal }) + return readResponse(response, 'Organization not found') +} +``` + +- [ ] **Step 4: Rebuild `WorkspaceWelcome` around the three approved choices** + +Use `fetchDashboard` for Harborline counts. Use `useNavigate` for navigation. On open success navigate to `/organizations/${workspace.publicCode}/map`; on create success navigate to the same path with `{ state: { newlyCreated: true } }`. + +The organization code form must use: + +```tsx + + setOrganizationCode(event.target.value)} + placeholder="NMS-7K4P9D" +/> + +``` + +Keep Harborline exploration independent of dashboard-count failure: show em dashes for unavailable counts while leaving the Explore action available. + +- [ ] **Step 5: Update homepage styles** + +Reuse `.workspace-choice` structure. Add an inline organization-code hint and error treatment without introducing a new page layout. Keep the three cards usable at existing responsive breakpoints. + +- [ ] **Step 6: Run the homepage tests** + +Run: + +```powershell +npm --prefix frontend test -- --run src/App.test.tsx +``` + +Expected: homepage access and creation tests PASS; route-shell tests may still fail until Task 4. + +- [ ] **Step 7: Commit the homepage access flow** + +```powershell +git add frontend/src/api/workspaces.ts frontend/src/components/workspaces/WorkspaceWelcome.tsx frontend/src/App.css frontend/src/App.test.tsx +git commit -m "feat: open organizations from the homepage" +``` + +--- + +### Task 4: Make nested routes the source of truth for organization screens + +**Files:** +- Create: `frontend/src/components/workspaces/OrganizationRoute.tsx` +- Modify: `frontend/src/App.tsx` +- Modify: `frontend/src/components/workspaces/DraftWorkspace.tsx` +- Modify: `frontend/src/components/workspaces/editor/DraftEditor.tsx` +- Modify: `frontend/src/App.test.tsx` + +**Interfaces:** +- Consumes: `fetchWorkspaceByCode` from Task 3. +- Produces: `/`, `/example`, `/organizations/:publicCode`, and `/organizations/:publicCode/:view` where `view` is `map | inventory | impact`. +- Produces: `DraftEditor({ workspaceId, view, onViewChange })` with no internal top-level view state. + +- [ ] **Step 1: Add failing direct-navigation and refresh tests** + +Add one test per approved route: + +```tsx +function mockOrganizationRoute() { + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + const url = input.toString() + if (url.endsWith('/api/v1/workspaces/by-code/NMS-7K4P9D')) { + return jsonResponse(linkedWorkspaceFixture) + } + if (url.endsWith('/catalog')) return jsonResponse(blankCatalogFixture) + if (url.endsWith('/impact-previews/continuity')) return jsonResponse([]) + if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture) + return new Response(null, { status: 404 }) + }) +} + +it.each([ + ['/organizations/NMS-7K4P9D/map', 'Map how your organization works'], + ['/organizations/NMS-7K4P9D/inventory', 'Detailed inventory'], + ['/organizations/NMS-7K4P9D/impact', 'Test a change before it happens'], +])('loads %s directly', async (entry, expectedText) => { + mockOrganizationRoute() + renderApp([entry]) + expect(await screen.findByText(expectedText)).toBeInTheDocument() +}) +``` + +Add tests for `/organizations/NMS-7K4P9D` redirecting to `/map`, an invalid nested view redirecting to `/map`, `/example` surviving direct load, and an unknown code rendering recovery actions without redirecting home. + +For impact refresh semantics, render directly at `/impact` and assert the Test Impact screen is present while no prior result or mitigation verdict is present. + +- [ ] **Step 2: Run the route tests and verify the expected failures** + +Run: + +```powershell +npm --prefix frontend test -- --run src/App.test.tsx +``` + +Expected: FAIL because `App` still uses local `AppView` state. + +- [ ] **Step 3: Implement route declarations in `App`** + +Replace local view state with: + +```tsx + + } /> + } /> + } /> + } /> + } /> + +``` + +Use `useNavigate` for Harborline’s back action. `OrganizationIndexRedirect` reads `publicCode` and returns ``. + +- [ ] **Step 4: Implement `OrganizationRoute`** + +`OrganizationRoute` must: + +```tsx +const validViews = ['map', 'inventory', 'impact'] as const +type OrganizationView = typeof validViews[number] +``` + +Normalize the route code, fetch the workspace with TanStack Query key `['workspace', normalizedCode]`, redirect an invalid view to the organization map, and render a recovery screen for invalid/unknown codes. Keep connection errors on the route with a Retry action. + +Pass `newlyCreated` from `location.state` to `DraftWorkspace`; do not store it in the URL or database. + +- [ ] **Step 5: Make `DraftWorkspace` route-aware** + +Replace `onBack` with: + +```ts +type DraftWorkspaceProps = { + workspace: Workspace + view: OrganizationView + newlyCreated: boolean + onViewChange: (view: OrganizationView) => void +} +``` + +Use navigation to return home and pass route view props to `DraftEditor`. + +- [ ] **Step 6: Remove top-level view state from `DraftEditor`** + +Change the signature to: + +```ts +export default function DraftEditor({ workspaceId, view, onViewChange }: { + workspaceId: string + view: 'map' | 'impact' | 'inventory' + onViewChange: (view: 'map' | 'impact' | 'inventory') => void +}) +``` + +Replace `setView('map')`, `setView('impact')`, and `setView('inventory')` with the matching `onViewChange` calls. Retain inventory `stage` as local state. Pass `initialFocus={false}` to `OrganizationCanvas` and remove `isTemplateClone`. + +- [ ] **Step 7: Run direct-route tests and the full frontend suite** + +Run: + +```powershell +npm --prefix frontend test +``` + +Expected: PASS, including direct map, inventory, impact, example, redirect, and recovery tests. + +- [ ] **Step 8: Commit nested routing** + +```powershell +git add frontend/src/App.tsx frontend/src/App.test.tsx frontend/src/components/workspaces/OrganizationRoute.tsx frontend/src/components/workspaces/DraftWorkspace.tsx frontend/src/components/workspaces/editor/DraftEditor.tsx +git commit -m "feat: add refresh-safe organization routes" +``` + +--- + +### Task 5: Add persistent organization recovery controls and creation onboarding + +**Files:** +- Modify: `frontend/src/components/workspaces/DraftWorkspace.tsx` +- Modify: `frontend/src/App.css` +- Modify: `frontend/src/App.test.tsx` + +**Interfaces:** +- Consumes: `Workspace.publicCode`, routed organization view, and `newlyCreated` from Task 4. +- Produces: persistent Copy ID and Copy organization link actions plus a dismissible first-creation notice. + +- [ ] **Step 1: Add failing copy and onboarding tests** + +Mock `navigator.clipboard.writeText`. Add tests asserting: + +```tsx +expect(screen.getByText('NMS-7K4P9D')).toBeInTheDocument() +await user.click(screen.getByRole('button', { name: 'Copy organization ID' })) +expect(navigator.clipboard.writeText).toHaveBeenCalledWith('NMS-7K4P9D') +await user.click(screen.getByRole('button', { name: 'Copy organization link' })) +expect(navigator.clipboard.writeText).toHaveBeenCalledWith( + `${window.location.origin}/organizations/NMS-7K4P9D/map`, +) +``` + +Creation navigation must show “Save this organization ID” and the warning “Anyone with this link or ID can edit this organization.” Directly reopening the same URL must keep header controls but not show the creation notice. + +- [ ] **Step 2: Run the focused tests and verify the expected failures** + +Run: + +```powershell +npm --prefix frontend test -- --run src/App.test.tsx +``` + +Expected: FAIL because recovery controls and onboarding do not exist. + +- [ ] **Step 3: Implement copy controls and creation notice** + +In `DraftWorkspace`, derive the canonical map link from `window.location.origin` and `workspace.publicCode`. Keep copy feedback local and non-blocking: + +```ts +async function copy(value: string, successMessage: string) { + try { + await navigator.clipboard.writeText(value) + setCopyMessage(successMessage) + } catch { + setCopyMessage('Copy failed. Select the visible organization ID instead.') + } +} +``` + +The persistent header displays the public code and both copy buttons. The dismissible onboarding notice appears only when `newlyCreated` is true and includes the no-sensitive-data warning. + +- [ ] **Step 4: Style recovery controls for desktop and mobile** + +Add `.organization-recovery`, `.organization-code`, and `.organization-onboarding` styles that use existing colors, border radii, focus treatments, and mobile wrapping behavior. + +- [ ] **Step 5: Run the full frontend quality gate** + +Run: + +```powershell +npm --prefix frontend test +npm --prefix frontend run lint +npm --prefix frontend run build +``` + +Expected: all commands PASS without warnings introduced by this feature. + +- [ ] **Step 6: Commit recovery controls** + +```powershell +git add frontend/src/components/workspaces/DraftWorkspace.tsx frontend/src/App.css frontend/src/App.test.tsx +git commit -m "feat: expose organization recovery controls" +``` + +--- + +### Task 6: Verify direct-link hosting behavior and complete clone cleanup + +**Files:** +- Modify: `README.md` +- Modify: any test fixture still containing `sourceTemplateOrganizationId` or clone actions. + +**Interfaces:** +- Consumes: the complete backend and frontend feature. +- Produces: documented organization URL behavior, deployment fallback requirement, and a repository with no active cloning implementation. + +- [ ] **Step 1: Scan for forbidden clone implementation references** + +Run: + +```powershell +rg -n -i "sourceTemplateOrganizationId|source_template_organization_id|cloneWorkspace|clonePublished|cloneCatalog|/clones|Clone Harborline|Clone and customize" backend/src frontend/src README.md +``` + +Expected: no matches outside historical migration V4 and the V7 statement that drops the old column. Remove stale test fixtures and product copy if the scan reports them. + +- [ ] **Step 2: Update README routes and local verification** + +Document: + +```markdown +- `GET /api/v1/workspaces/by-code/{publicCode}` resolves an editable organization. +- `/organizations/{publicCode}/map` opens its organization map. +- `/organizations/{publicCode}/inventory` opens its detailed inventory. +- `/organizations/{publicCode}/impact` opens a fresh impact-testing screen. +``` + +State that production hosting must rewrite non-asset, non-API paths to `frontend/index.html`. Document that Vite dev and preview already provide the SPA history fallback used for local verification. + +- [ ] **Step 3: Run all automated checks** + +Run: + +```powershell +.\backend\mvnw.cmd -f backend\pom.xml test +npm --prefix frontend test +npm --prefix frontend run lint +npm --prefix frontend run build +``` + +Expected: every command PASS. + +- [ ] **Step 4: Perform browser acceptance verification** + +With PostgreSQL, API, and frontend running: + +1. Create a blank organization and record its displayed ID. +2. Refresh its map route and confirm the same organization loads. +3. Navigate to inventory, refresh, and confirm inventory remains selected. +4. Navigate to impact, run a test, refresh, and confirm the impact screen remains while the previous result is cleared. +5. Paste the organization map URL into a fresh tab and confirm it loads. +6. Enter the ID without its hyphen on the homepage and confirm it opens the organization. +7. Open `/example`, refresh, and confirm Harborline remains read-only. +8. Enter an unknown valid-format code and confirm the recovery screen offers Try another ID, Return home, and Create a new organization. + +- [ ] **Step 5: Commit documentation and cleanup** + +```powershell +git add README.md backend/src frontend/src +git commit -m "docs: document organization deep links" +``` + +- [ ] **Step 6: Review the final diff** + +Run: + +```powershell +git status --short +git diff --stat HEAD~5..HEAD +git log --oneline -6 +``` + +Expected: no unintended files, no uncommitted feature changes, and separate commits for schema, backend API, homepage, routing, recovery controls, and documentation. diff --git a/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md new file mode 100644 index 0000000..fd9843b --- /dev/null +++ b/docs/superpowers/specs/2026-08-21-organization-deep-linking-design.md @@ -0,0 +1,229 @@ +# Organization Deep Linking and Recovery Design + +**Date:** 2026-08-21 +**Status:** Approved in conversation; awaiting written-spec review + +## Purpose + +RoleImpact currently keeps the active page and workspace in React component state. A browser refresh therefore returns the user to the homepage, and the homepage does not provide a direct way to reopen an existing organization. This design gives every editable organization a stable public code and nested URL routes, while keeping impact previews temporary. + +The same change removes Harborline cloning from the product and backend. Users will either explore Harborline as a read-only example, open an organization they already know, or create a blank organization. + +## Goals + +- Give every editable organization a stable, human-friendly public code. +- Allow an organization to be opened by entering its code on the homepage or by using its URL. +- Preserve the current organization screen across refreshes and direct navigation. +- Keep organization links editable for the portfolio MVP without introducing accounts or authentication. +- Keep impact and mitigation preview results temporary and deterministic. +- Remove the Harborline cloning flow, API, persistence logic, and template-specific UI branches. +- Preserve all existing organization records and catalog data. + +## Non-goals + +- User accounts, authentication, invitations, or organization membership. +- Separate view-only and edit links. +- Persisted impact-run history or shareable impact-result URLs. +- Restoring an in-progress impact result after refresh. +- Renaming the backend `workspace` package and API vocabulary to `organization` in this change. +- Deleting organizations that were previously created by cloning. + +## Product Flow + +### Homepage + +The homepage presents three actions: + +1. **Explore Harborline** opens the existing read-only example. +2. **Open your organization** accepts a public organization code and navigates to its map. +3. **Create a new organization** creates an empty draft and navigates to its map. + +The existing **Clone Harborline** card is removed and its space is used by **Open your organization**. + +The organization-code form: + +- trims surrounding whitespace; +- normalizes letters to uppercase; +- accepts the displayed form with or without its hyphen; +- does not navigate when the code is malformed; +- displays an inline not-found message when no organization matches; +- never lists all organizations from the server. + +### Organization creation + +Creating a blank organization generates both its internal UUID and public code. The frontend redirects to `/organizations/{code}/map` and displays a persistent onboarding notice containing: + +- the organization code; +- a **Copy ID** action; +- a **Copy organization link** action; and +- a reminder that anyone with the link or code can edit the organization in the portfolio MVP. + +The organization header continues to expose Copy ID and Copy Link after the onboarding notice is dismissed. Copy Link copies the stable map URL rather than a temporary impact state. + +In user-facing language, **Organization ID** means the public organization code. The internal UUID remains an implementation detail and is not shown as the recovery credential. + +### Organization navigation + +The organization map, inventory, and impact tabs are real nested routes: + +- `/organizations/{code}/map` +- `/organizations/{code}/inventory` +- `/organizations/{code}/impact` + +`/organizations/{code}` redirects to `/organizations/{code}/map`. + +Changing tabs changes the URL. Refreshing or directly opening any valid nested route loads the organization from PostgreSQL and returns to that screen. + +Impact selections, results, and mitigation previews remain screen state. Refreshing `/impact` keeps the user on the Test Impact screen but clears the previous result and initializes a valid default workflow, responsibility, and role-holder selection from the current organization. + +The Harborline example receives a stable `/example` route so it also survives refresh, but it does not receive an editable organization code. + +## Public Organization Code + +The database continues using UUID primary keys and foreign keys. A separate `public_code` column is used only for entry and routing. + +Code properties: + +- generated once when an organization is created; +- never changes when the organization is renamed; +- globally unique; +- case-insensitive; +- random rather than sequential; +- short enough to type accurately; +- excludes visually ambiguous characters such as `0`, `O`, `1`, and `I`. + +New codes use a three-letter name-derived prefix followed by a 16-character Base32-style random token (80 bits), for example `NSM-7K4P9D8XM2QR6WBC`. The name prefix is cosmetic and is not recalculated after rename. Existing 32-character IDs remain valid and unchanged until the development database is cleared. The full code is an editable bearer capability, uniqueness is enforced by the database, and the service retries generation on the unlikely event of a collision. + +The code is an unguessable locator, not authentication. The UI must state that real or sensitive company information should not be entered until authentication is added. + +## Database Migration + +A new Flyway migration will: + +1. add nullable `public_code` to `organizations`; +2. backfill a unique generated code for every existing organization; +3. make the column non-null; +4. add a case-insensitive unique index; +5. remove the clone-source index and foreign key; and +6. drop `source_template_organization_id`. + +Dropping the clone-source metadata does not remove or alter cloned catalog records because cloned organizations already own independent copies of their data. + +The Harborline published example also receives an internal code during migration to satisfy the non-null constraint, but that code is not exposed as an editable organization route. Requests that resolve to a published example through the editable organization endpoint are rejected. + +## Backend API + +Existing catalog and impact endpoints continue to use internal workspace UUIDs after the organization is resolved. This limits the scope of the change and avoids rewriting every established API boundary. + +### Retained and changed endpoints + +- `POST /api/v1/workspaces` + - Creates an empty draft. + - Generates the public code. + - Returns the public code in `WorkspaceResource`. + +- `GET /api/v1/workspaces/by-code/{publicCode}` + - Normalizes and resolves the code. + - Returns only editable draft organizations. + - Returns `404` for unknown, malformed, or published-example codes. + +- `GET /api/v1/workspaces/{workspaceId}` + - Remains available for internal UUID-based consumers and tests. + +- Existing `/catalog`, `/impact-previews`, and `/impact-previews/mitigations` endpoints remain UUID-based. + +### Removed endpoints + +- `POST /api/v1/workspaces/{sourceWorkspaceId}/clones` +- The public all-workspaces listing endpoint, `GET /api/v1/workspaces`, because an unauthenticated list would defeat code-based discovery boundaries. + +Harborline homepage counts and example navigation use the existing example/dashboard API rather than finding Harborline through the workspace list. + +## Backend Module Changes + +- `WorkspaceResource` replaces `sourceTemplateOrganizationId` with `publicCode`. +- `WorkspaceService` generates codes and resolves editable workspaces by code. +- `WorkspaceRepository` adds code lookup and collision-safe insertion. +- `WorkspaceRepository.cloneCatalog` and all temporary clone-ID mapping SQL are removed. +- `WorkspaceService.clonePublished` is removed. +- `WorkspaceController.clone` and `WorkspaceController.list` are removed. +- Template-specific validation messages are rewritten to direct users toward creating a new organization. +- Existing clone tests are deleted or replaced with public-code creation and lookup tests. + +## Frontend Routing and State + +React Router will become the source of truth for the active top-level screen. `App` will no longer hold a manual `AppView` union in component state. + +Route responsibilities: + +- `/` renders the homepage. +- `/example` renders the Harborline example. +- `/organizations/:publicCode` redirects to the map. +- `/organizations/:publicCode/:view` resolves the organization and renders the requested organization view. +- unknown routes render a lightweight not-found screen. + +The organization route loader/query resolves the code once, obtains the internal UUID, and supplies the `Workspace` to `DraftWorkspace`. `DraftEditor` derives its active view from the route segment rather than local state. Inventory stage selection may remain local state because refreshing the inventory screen, rather than a particular inventory subsection, satisfies the approved requirement. + +The frontend workspace API removes cloning and listing functions and adds code lookup. Template-clone props, copy-specific wording, and clone-only branches are removed. + +Both the local development server and production host must use an SPA history fallback: any non-API path that does not match a static asset serves `index.html`. This ensures that directly opening or refreshing a nested organization URL reaches React Router instead of returning a host-level 404. + +## Error Handling + +- A malformed code is rejected on the homepage before a request is made. +- An unknown or published-example code returns a consistent organization-not-found response. +- A direct invalid organization route renders a recovery screen with: + - **Try another organization ID**; + - **Return home**; and + - **Create a new organization**. +- API unavailability renders the existing connection-retry treatment without redirecting home. +- A valid organization with an invalid nested view redirects to its map. +- Clipboard failures display a non-blocking message and leave the code visible for manual copying. + +## Compatibility and Recovery + +- Existing draft organizations survive the migration and receive generated codes. +- Existing cloned organizations become ordinary drafts after clone metadata is removed. +- Existing catalog UUID relationships, canvas positions, and impact behavior remain unchanged. +- During development handoff, the generated codes for important existing test organizations can be retrieved once from the database so they are not effectively hidden after the all-workspaces list is removed. +- Previously bookmarked root URLs continue to open the homepage; there are no existing organization URLs to redirect. + +## Test Strategy + +### Backend + +- Migration integration test proves every existing organization receives a unique non-null code and clone metadata is removed without catalog loss. +- Service tests cover code generation, normalization, collision retry, draft-only lookup, and not-found behavior. +- Controller integration tests cover create-and-return-code, lookup-by-code, malformed code, unknown code, and published-example rejection. +- Existing catalog and impact tests continue proving that UUID-based downstream endpoints work after code resolution. +- Clone endpoint and clone-catalog tests are removed. + +### Frontend + +- Homepage tests cover code normalization, successful navigation, malformed code, unknown code, blank creation, and absence of clone controls. +- Routing tests directly load and refresh map, inventory, impact, example, and invalid-code routes. +- Impact-route tests prove refresh keeps the user on Test Impact while prior result panels are absent. +- Header tests cover Copy ID and Copy Link content. +- Existing organization-building, graph, and mitigation tests run through routed organization screens. + +### Browser verification + +- Create an organization and capture its code. +- Refresh map, inventory, and impact routes independently. +- Open the code in a fresh tab and verify the same organization loads. +- Enter the code on the homepage and verify redirection to the map. +- Confirm the impact result clears on refresh without leaving the impact route. +- Confirm Harborline remains explorable and no clone action remains. + +## Acceptance Criteria + +- A newly created organization receives a stable public code and map URL. +- Entering that code on the homepage opens the correct editable organization. +- Anyone with the code or link can edit the organization in the portfolio MVP. +- Refreshing map, inventory, impact, or example stays on the same screen. +- Impact previews are not persisted and disappear after impact-route refresh. +- Existing organizations and catalog data remain intact after migration. +- Harborline remains a read-only example. +- No clone card, clone API, cloning service, clone SQL, clone metadata field, or template-specific branch remains. +- Invalid codes and routes provide clear recovery actions. +- Backend tests, frontend tests, lint, production build, and browser verification pass. diff --git a/frontend/src/App.css b/frontend/src/App.css index 31cad50..4e96317 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -146,7 +146,7 @@ .workspace-mini-stats { display: grid; - grid-template-columns: repeat(4, 1fr); + grid-template-columns: repeat(3, 1fr); margin-bottom: 1rem; padding: 0.9rem 0; border-top: 1px solid #2c3040; @@ -944,7 +944,9 @@ .organization-node.simulation-removed, .organization-node.simulation-blocked { border-color: #fb7185; background: linear-gradient(145deg, #321a23, #1c1217); box-shadow: 0 0 0 3px rgb(251 113 133 / 12%), 0 12px 30px rgb(0 0 0 / 28%); } .organization-node.simulation-degraded { border-color: #fbbf24; background: linear-gradient(145deg, #302816, #1b1710); } +.organization-node.simulation-operational, .organization-node.simulation-restored { border-color: #4ade80; background: linear-gradient(145deg, #173322, #101d16); box-shadow: 0 0 0 3px rgb(74 222 128 / 13%), 0 12px 30px rgb(0 0 0 / 28%); } +.organization-node.simulation-operational .organization-node-icon, .organization-node.simulation-restored .organization-node-icon { background: #174d30; color: #8ff0b1; } .organization-node.simulation-removed .organization-node-icon, .organization-node.simulation-blocked .organization-node-icon { background: #5a2433; color: #ffadba; } @@ -971,6 +973,7 @@ .organization-node.simulation-degraded .organization-node-badge { color: #fbbf24; } .organization-node.simulation-removed .organization-node-badge, .organization-node.simulation-blocked .organization-node-badge { color: #fb7185; } +.organization-node.simulation-operational .organization-node-badge, .organization-node.simulation-restored .organization-node-badge { color: #4ade80; } .organization-node.has-impact-actions > span:nth-of-type(2) { padding-right: 1.35rem; } .organization-node-impact-actions { @@ -1559,6 +1562,30 @@ background: #0d1017; } +.full-impact-map-canvas .react-flow__controls { + overflow: hidden; + border: 1px solid #333849; + border-radius: 0.55rem; + box-shadow: 0 10px 24px rgb(0 0 0 / 24%); +} + +.full-impact-map-canvas .react-flow__controls-button { + border: 0; + border-bottom: 1px solid #333849; + border-radius: 0; + background: #171a24; + color: #bdc3d2; + fill: #bdc3d2; +} + +.full-impact-map-canvas .react-flow__controls-button:hover { + background: #242836; +} + +.full-impact-map-canvas .react-flow__controls-button svg { + fill: currentcolor; +} + .full-impact-map .organization-node.member { cursor: pointer; } .full-impact-map .organization-node.dimmed { opacity: 0.38; } .full-impact-map .scenario-context-menu small { color: #c7a66a; font-size: 0.58rem; line-height: 1.45; } @@ -1638,8 +1665,23 @@ .draft-recommendation-card > div > strong { font-size: 0.82rem; } .draft-recommendation-card > button { min-width: 9.5rem; } .draft-recommendation-rank { display: grid; width: 2rem; height: 2rem; place-items: center; border-radius: 50%; background: #21382c; color: #8de0b5; font-size: 0.7rem; font-weight: 900; } +.recommendation-alignment { width: fit-content; padding: 0.22rem 0.42rem; border-radius: 999px; font-size: 0.58rem; font-weight: 850; letter-spacing: 0.025em; } +.recommendation-alignment.aligned { background: #173b2a; color: #8de0b5; } +.recommendation-alignment.review { background: #332a1a; color: #f5ca72; } .draft-recommendation-evidence { display: flex; flex-wrap: wrap; gap: 0.35rem; } .draft-recommendation-evidence span { padding: 0.22rem 0.38rem; border-radius: 999px; background: #222a26; color: #9dc4ad; font-size: 0.56rem; font-weight: 700; } +.draft-alternative-recommendations { border: 1px solid #303546; border-radius: 0.75rem; background: #141821; } +.draft-alternative-recommendations summary { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; padding: 0.8rem 0.9rem; color: #c7cddd; cursor: pointer; list-style: none; } +.draft-alternative-recommendations summary::-webkit-details-marker { display: none; } +.draft-alternative-recommendations summary::after { content: '+'; color: #9c89e8; font-size: 1rem; } +.draft-alternative-recommendations[open] summary::after { content: '−'; } +.draft-alternative-recommendations summary span { font-size: 0.74rem; font-weight: 800; } +.draft-alternative-recommendations summary small { margin-left: auto; color: #777f92; font-size: 0.62rem; } +.draft-alternative-list { display: grid; gap: 1px; border-top: 1px solid #303546; background: #303546; } +.draft-alternative-card { display: grid; gap: 0.25rem; padding: 0.85rem 0.9rem; background: #151922; } +.draft-alternative-card strong { font-size: 0.78rem; } +.draft-alternative-card span { color: #9c89e8; font-size: 0.6rem; font-weight: 750; } +.draft-alternative-card p { max-width: 56rem; color: #858da1; } .draft-candidate-exclusions { border-top: 1px solid #2d3240; padding-top: 0.8rem; } .draft-candidate-exclusions summary { color: #b6bdcc; cursor: pointer; font-size: 0.7rem; font-weight: 700; } .draft-candidate-exclusions > div { display: grid; gap: 0.45rem; padding-top: 0.65rem; } @@ -1906,6 +1948,98 @@ backdrop-filter: blur(16px); } +.draft-topbar { + position: sticky; + z-index: 20; + top: 0; +} + +.organization-recovery { + display: flex; + align-items: center; + gap: 0.65rem; +} + +.organization-recovery code { + padding: 0.42rem 0.65rem; + border: 1px solid #3b4051; + border-radius: 0.55rem; + background: #11131c; + color: #d8ccff; + font-weight: 750; + letter-spacing: 0.08em; +} + +.organization-recovery button, +.organization-onboarding-actions button, +.recovery-actions button { + padding: 0.58rem 0.8rem; + border: 1px solid #47405f; + border-radius: 0.6rem; + background: #211b35; + color: #eee9ff; + font: inherit; + font-size: 0.78rem; + font-weight: 700; + cursor: pointer; +} + +.copy-feedback { + position: sticky; + z-index: 10; + top: 5.2rem; + width: fit-content; + margin: -2.4rem 0 1.25rem auto; + padding: 0.65rem 0.85rem; + border: 1px solid #3c5f51; + border-radius: 0.65rem; + background: #14251e; + color: #9df0c8; + box-shadow: 0 14px 34px rgb(0 0 0 / 28%); + font-size: 0.8rem; +} + +.organization-onboarding { + display: flex; + align-items: center; + justify-content: space-between; + gap: 2rem; + margin-bottom: 2.5rem; + padding: 1.25rem 1.4rem; + border: 1px solid #6551ad; + border-radius: 1rem; + background: linear-gradient(135deg, rgb(79 59 147 / 26%), rgb(20 22 32 / 96%)); +} + +.organization-onboarding h2, +.organization-onboarding p { + margin: 0; +} + +.organization-onboarding p:last-child { + max-width: 50rem; + margin-top: 0.55rem; + color: #aeb5c8; + line-height: 1.55; +} + +.organization-onboarding-actions, +.recovery-actions { + display: flex; + flex-wrap: wrap; + gap: 0.65rem; +} + +.organization-recovery-screen { + max-width: 42rem; + margin: 0 auto; + text-align: center; +} + +.organization-recovery-screen .recovery-actions { + justify-content: center; +} + .brand { display: inline-flex; align-items: center; @@ -3144,6 +3278,28 @@ a:focus-visible { padding: 0 1rem; } + .draft-topbar { + align-items: flex-start; + flex-direction: column; + gap: 0.75rem; + padding-top: 0.8rem; + padding-bottom: 0.8rem; + } + + .organization-recovery { + width: 100%; + flex-wrap: wrap; + } + + .organization-recovery .draft-status { + width: 100%; + } + + .organization-onboarding { + align-items: flex-start; + flex-direction: column; + } + .baseline-chip { max-width: 11rem; overflow: hidden; diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx index 4785b37..989c867 100644 --- a/frontend/src/App.test.tsx +++ b/frontend/src/App.test.tsx @@ -1,6 +1,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import { MemoryRouter } from 'react-router-dom' import { afterEach, describe, expect, it, vi } from 'vitest' import App from './App' import type { DraftCatalog } from './api/draftCatalog' @@ -13,18 +14,27 @@ afterEach(() => { localStorage.clear() }) -function renderApp() { +function renderApp(initialEntries = ['/']) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, }) return render( - - - , + + + + + , ) } +const harborlineCode = 'HBR-0123456789ABCDEF0123456789ABCDEF' +const editableCode = 'HCS-1123456789ABCDEF0123456789ABCDEF' +const blankCode = 'ATS-2123456789ABCDEF0123456789ABCDEF' +const editableMapRoute = `/organizations/${editableCode}/map` +const editableInventoryRoute = `/organizations/${editableCode}/inventory` +const editableImpactRoute = `/organizations/${editableCode}/impact` + describe('App', () => { it('renders the seeded organization dashboard', async () => { const user = userEvent.setup() @@ -129,28 +139,26 @@ describe('App', () => { expect(screen.getByLabelText('Graph state legend')).toHaveTextContent('Restored') }) - it('clones the example into an isolated editable draft', async () => { + it('opens an editable organization from its stable route', async () => { const user = userEvent.setup() - vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { const url = input.toString() - if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture) - if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture) if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture) + if (url.endsWith('/impact-previews/continuity')) return jsonResponse([]) return new Response(null, { status: 404 }) }) - renderApp() - - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) + renderApp([editableMapRoute]) expect(await screen.findByRole('heading', { name: 'Harborline Sandbox' })).toBeInTheDocument() - expect(screen.getByText('Draft · not yet published')).toBeInTheDocument() - expect(screen.getByText(/fresh identity/)).toBeInTheDocument() - expect(screen.getByLabelText('Draft catalog summary')).toHaveTextContent('1members') + expect(screen.getByText('Editable organization')).toBeInTheDocument() + expect(screen.getByText(/return later using the organization ID or link/)).toBeInTheDocument() + expect(await screen.findByLabelText('Draft catalog summary')).toHaveTextContent('1members') expect(await screen.findByRole('heading', { name: 'Map how your organization works' })).toBeInTheDocument() expect(await screen.findByLabelText('Organization relationship canvas')).toBeInTheDocument() expect(screen.getByLabelText('Organization inventory')).toHaveTextContent('Finance Approver') - expect(screen.getByRole('button', { name: 'Show full map' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Fit graph' })).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Detailed inventory' })) expect(screen.getByRole('button', { name: /Teams/ })).toHaveAttribute('aria-current', 'step') }) @@ -159,9 +167,8 @@ describe('App', () => { const user = userEvent.setup() const requests = mockEditableClone(clonedCatalogFixture) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) - await user.click(await screen.findByRole('button', { name: 'Detailed inventory' })) + renderApp([editableInventoryRoute]) + await screen.findByRole('button', { name: 'Detailed inventory' }) await user.click(screen.getByRole('button', { name: /Roles/ })) await user.type(screen.getByLabelText('Role name'), 'Release Manager') await user.type(screen.getByLabelText('Description'), 'Approves production releases') @@ -178,9 +185,8 @@ describe('App', () => { const user = userEvent.setup() const requests = mockEditableClone(clonedCatalogFixture) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) - await user.click(await screen.findByRole('button', { name: 'Detailed inventory' })) + renderApp([editableInventoryRoute]) + await screen.findByRole('button', { name: 'Detailed inventory' }) await user.click(screen.getByRole('button', { name: /Roles/ })) const financeRole = screen.getByText('Finance Approver', { selector: 'strong' }).closest('article') expect(financeRole).not.toBeNull() @@ -198,8 +204,8 @@ describe('App', () => { const user = userEvent.setup() const requests = mockEditableClone(clonedCatalogFixture) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) + renderApp([editableMapRoute]) + await screen.findByRole('button', { name: 'Add Role' }) await user.click(await screen.findByRole('button', { name: 'Add Role' })) await user.type(screen.getByLabelText('Role name'), 'Release Manager') await user.click(screen.getByRole('checkbox', { name: 'Priya Sharma' })) @@ -215,8 +221,8 @@ describe('App', () => { const user = userEvent.setup() const requests = mockEditableClone(clonedCatalogFixture) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) + renderApp([editableMapRoute]) + await screen.findByRole('button', { name: 'Add Role' }) await user.click(await screen.findByRole('button', { name: 'Add Role' })) await user.type(screen.getByLabelText('Role name'), 'Finance Approver') expect(screen.getByRole('checkbox', { name: 'Priya Sharma' })).toBeChecked() @@ -232,8 +238,8 @@ describe('App', () => { const user = userEvent.setup() mockEditableClone(clonedCatalogFixture) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) + renderApp([editableMapRoute]) + await screen.findByRole('button', { name: 'Add Role' }) await user.click(await screen.findByRole('button', { name: 'Add Role' })) await user.type(screen.getByLabelText('Role name'), 'Finance Approver') @@ -241,26 +247,24 @@ describe('App', () => { }) it('opens impact testing after a deferred continuity projection resolves', async () => { - const user = userEvent.setup() const projection = deferred() vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { const url = input.toString() - if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture) - if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture) if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture) if (url.endsWith('/impact-previews/continuity') && !init?.method) return projection.promise return new Response(null, { status: 404 }) }) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) - await user.click(await screen.findByRole('button', { name: 'Test impact' })) + renderApp([editableImpactRoute]) expect(await screen.findByRole('heading', { name: 'Loading continuity analysis' })).toBeInTheDocument() projection.resolve(jsonResponse(clonedContinuityFixture)) expect(await screen.findByRole('heading', { name: 'Test impact map' })).toBeInTheDocument() expect(screen.getByRole('button', { name: /Vendor Payment.*would block/ })).toBeInTheDocument() + expect(screen.queryByRole('heading', { name: 'Harborline Sandbox' })).not.toBeInTheDocument() + expect(screen.queryByText('Organization builder')).not.toBeInTheDocument() }) it('opens impact testing after retrying a failed continuity projection', async () => { @@ -268,8 +272,7 @@ describe('App', () => { let continuityAttempts = 0 vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { const url = input.toString() - if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture) - if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture) if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture) if (url.endsWith('/impact-previews/continuity') && !init?.method) { continuityAttempts += 1 @@ -280,9 +283,7 @@ describe('App', () => { return new Response(null, { status: 404 }) }) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) - await user.click(await screen.findByRole('button', { name: 'Test impact' })) + renderApp([editableImpactRoute]) expect(await screen.findByRole('heading', { name: 'Continuity analysis is unavailable' })).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Retry continuity analysis' })) @@ -292,7 +293,6 @@ describe('App', () => { }) it('renders a degraded engine verdict with the warning continuity treatment', async () => { - const user = userEvent.setup() const degradedContinuity = clonedContinuityFixture.map((risk) => ({ ...risk, members: risk.members.map((member) => ({ @@ -303,16 +303,13 @@ describe('App', () => { })) vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { const url = input.toString() - if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture) - if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture) if (url.endsWith('/catalog')) return jsonResponse(clonedCatalogFixture) if (url.endsWith('/impact-previews/continuity') && !init?.method) return jsonResponse(degradedContinuity) return new Response(null, { status: 404 }) }) - renderApp() - await user.click(await screen.findByRole('button', { name: 'Clone and customize' })) - await user.click(await screen.findByRole('button', { name: 'Test impact' })) + renderApp([editableImpactRoute]) const heading = await screen.findByText('This workflow would lose resilience') const signal = heading.closest('.continuity-signal') @@ -330,6 +327,7 @@ describe('App', () => { const url = input.toString() if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture) if (url.endsWith('/api/v1/workspaces') && init?.method === 'POST') return jsonResponse(blankWorkspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${blankCode}`)) return jsonResponse(blankWorkspaceFixture) if (url.endsWith('/catalog') && !init?.method) return jsonResponse(catalog) if (url.endsWith('/impact-previews/continuity') && !init?.method) { continuityRequests += 1 @@ -411,6 +409,11 @@ describe('App', () => { await user.click(screen.getByRole('button', { name: 'Create member' })) expect(await screen.findByText('Member created')).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Add Member' })) + await user.type(screen.getByLabelText('Member name'), 'Neha Kapoor') + await user.click(screen.getByRole('button', { name: 'Create member' })) + expect(await screen.findByText('Member created')).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Add Role' })) await user.type(screen.getByLabelText('Role name'), 'Release Manager') await user.selectOptions(screen.getByLabelText('Sensitivity'), 'HIGH') @@ -437,10 +440,11 @@ describe('App', () => { await user.click(screen.getByRole('button', { name: 'Organization map' })) expect(screen.getByLabelText('Organization inventory')).toHaveTextContent('Production Deployment') expect(screen.getByLabelText('Organization relationship canvas')).toBeInTheDocument() - expect(screen.getByText('6 objects · 5 connections')).toBeInTheDocument() + expect(screen.getByText('7 objects · 6 connections')).toBeInTheDocument() expect(screen.getByLabelText('Team Platform')).toBeInTheDocument() expect(screen.getByLabelText('Member Maya Singh')).toBeInTheDocument() expect(screen.getByLabelText('Member Arjun Mehta')).toBeInTheDocument() + expect(screen.getByLabelText('Member Neha Kapoor')).toBeInTheDocument() expect(screen.getByLabelText('Role Release Manager')).toBeInTheDocument() expect(screen.getByLabelText('Responsibility Release Manager responsibility')).toBeInTheDocument() expect(screen.getByLabelText('Workflow Production Deployment')).toBeInTheDocument() @@ -463,7 +467,7 @@ describe('App', () => { await user.click(screen.getByRole('button', { name: 'Organization map' })) await user.click(screen.getByRole('button', { name: 'Test this risk' })) - expect(await screen.findByRole('heading', { name: 'Test a change before it happens' })).toBeInTheDocument() + expect(await screen.findByRole('region', { name: 'Test impact workspace' })).toBeInTheDocument() expect(await screen.findByRole('heading', { name: 'Test impact map' })).toBeInTheDocument() expect(await screen.findByLabelText('Complete organization impact map')).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Show full map' })) @@ -481,6 +485,9 @@ describe('App', () => { expect(screen.getByRole('button', { name: 'Fit selection' })).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Clear selection' })) expect(screen.queryByRole('button', { name: 'Fit selection' })).not.toBeInTheDocument() + const scenarioComposer = screen.getByRole('region', { name: 'Choose what to test' }) + await user.click(within(scenarioComposer).getByRole('button', { name: /Release Manager responsibility/ })) + expect(screen.getByLabelText('Selected Responsibility Release Manager responsibility')).toHaveTextContent('Eligible now') const mayaImpactActions = document.querySelector('button[aria-label="Impact actions for Maya Singh"]') const arjunImpactActions = document.querySelector('button[aria-label="Impact actions for Arjun Mehta"]') expect(mayaImpactActions).toBeInTheDocument() @@ -497,8 +504,19 @@ describe('App', () => { expect(await screen.findByRole('heading', { name: 'A workflow would be blocked' })).toBeInTheDocument() expect(screen.getByLabelText('Complete organization impact map')).toBeInTheDocument() expect(screen.getByLabelText(/member Arjun Mehta.*Recommended #1/i)).toBeInTheDocument() + expect(screen.queryByLabelText(/member Neha Kapoor.*Recommended #2/i)).not.toBeInTheDocument() expect(screen.getByRole('button', { name: 'Reset to baseline' })).toBeInTheDocument() - expect(screen.getByRole('heading', { name: 'Test a safe replacement' })).toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Recommended replacement' })).toBeInTheDocument() + expect(screen.getByText('Best aligned · same team')).toBeInTheDocument() + expect(screen.getByText(/Ranked #1 because Arjun Mehta is in the same team as Maya Singh/)).toBeInTheDocument() + const alternatives = screen.getByRole('group', { name: 'Alternative replacements' }) + expect(within(alternatives).getByText('1 alternative')).toBeInTheDocument() + expect(alternatives).not.toHaveAttribute('open') + await user.click(within(alternatives).getByText('1 alternative')) + expect(alternatives).toHaveAttribute('open') + expect(within(alternatives).getByText('Neha Kapoor')).toBeInTheDocument() + expect(within(alternatives).getByText(/adds another dependency/i)).toBeInTheDocument() + expect(within(alternatives).queryByRole('button')).not.toBeInTheDocument() fireEvent.click(screen.getByLabelText(/member Arjun Mehta.*Recommended #1/i)) const selectedArjun = screen.getByLabelText('Selected Member Arjun Mehta') await user.click(within(selectedArjun).getByRole('button', { name: 'Try as replacement for Release Manager' })) @@ -593,8 +611,7 @@ function mockEditableClone(initialCatalog: DraftCatalog) { const memberRoleRequests: string[] = [] vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { const url = input.toString() - if (url.endsWith('/api/v1/workspaces') && !init?.method) return jsonResponse(workspaceFixture) - if (url.endsWith('/clones') && init?.method === 'POST') return jsonResponse(clonedWorkspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${editableCode}`)) return jsonResponse(clonedWorkspaceFixture) if (url.endsWith('/catalog') && !init?.method) return jsonResponse(catalog) if (url.endsWith('/impact-previews/continuity') && !init?.method) return jsonResponse([]) if (url.endsWith('/catalog/roles') && init?.method === 'POST') { @@ -639,7 +656,7 @@ const workspaceFixture = [ name: 'Harborline Commerce', status: 'PUBLISHED', currentVersion: 1, - sourceTemplateOrganizationId: null, + publicCode: harborlineCode, createdAt: '2026-08-12T20:00:00Z', updatedAt: '2026-08-12T20:00:00Z', counts: { teams: 5, members: 25, roles: 8, permissions: 23, capabilities: 10, workflows: 4 }, @@ -653,7 +670,7 @@ const clonedWorkspaceFixture = { name: 'Harborline Sandbox', status: 'DRAFT', currentVersion: 0, - sourceTemplateOrganizationId: workspaceFixture[0].id, + publicCode: editableCode, } const blankWorkspaceFixture = { @@ -663,7 +680,7 @@ const blankWorkspaceFixture = { name: 'Atlas Systems', status: 'DRAFT', currentVersion: 0, - sourceTemplateOrganizationId: null, + publicCode: blankCode, counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 }, } @@ -1015,6 +1032,15 @@ const customDraftImpactFixture: DraftImpactResult = { restoredWorkflows: [{ id: 'workflow-1', name: 'Production Deployment' }], restoredWorkflowSteps: [{ id: 'requirement-1', name: 'Release Manager responsibility' }], }, + { + ...(simulationFixture.result.recommendations[0] as DraftImpactResult['recommendations'][number]), + id: 'recommendation-2', + rank: 2, + candidate: { id: 'member-3', name: 'Neha Kapoor' }, + role: { id: 'role-1', name: 'Release Manager' }, + restoredWorkflows: [{ id: 'workflow-1', name: 'Production Deployment' }], + restoredWorkflowSteps: [{ id: 'requirement-1', name: 'Release Manager responsibility' }], + }, ], excludedCandidateReasons: [], } diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 4681d7e..7b47896 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,36 +1,33 @@ -import { lazy, Suspense, useState } from 'react' +import { lazy, Suspense } from 'react' import { useMutation, useQuery } from '@tanstack/react-query' +import { Navigate, Route, Routes, useNavigate, useParams } from 'react-router-dom' import { fetchDashboard } from './api/dashboard' import { runMitigationBranch, runPrimarySimulation } from './api/simulations' -import type { Workspace } from './api/workspaces' import WorkspaceWelcome from './components/workspaces/WorkspaceWelcome' -import DraftWorkspace from './components/workspaces/DraftWorkspace' +import OrganizationRoute from './components/workspaces/OrganizationRoute' import './App.css' const ImpactGraph = lazy(() => import('./components/ImpactGraph')) -type AppView = { page: 'home' } | { page: 'example' } | { page: 'draft'; workspace: Workspace } - export default function App() { - const [view, setView] = useState({ page: 'home' }) - - if (view.page === 'home') { - return ( - setView({ page: 'example' })} - onOpenDraft={(workspace) => setView({ page: 'draft', workspace })} - /> - ) - } - - if (view.page === 'draft') { - return setView({ page: 'home' })} /> - } + return ( + + } /> + } /> + } /> + } /> + } /> + + ) +} - return setView({ page: 'home' })} /> +function OrganizationIndexRedirect() { + const { publicCode = '' } = useParams() + return } -function HarborlineDashboard({ onBack }: { onBack: () => void }) { +function HarborlineDashboard() { + const navigate = useNavigate() const dashboardQuery = useQuery({ queryKey: ['dashboard', 'harborline-commerce'], queryFn: ({ signal }) => fetchDashboard(signal), @@ -79,7 +76,7 @@ function HarborlineDashboard({ onBack }: { onBack: () => void }) { return (
- diff --git a/frontend/src/WorkspaceRouting.test.tsx b/frontend/src/WorkspaceRouting.test.tsx new file mode 100644 index 0000000..2be9b00 --- /dev/null +++ b/frontend/src/WorkspaceRouting.test.tsx @@ -0,0 +1,192 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { cleanup, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter } from 'react-router-dom' +import { afterEach, describe, expect, it, vi } from 'vitest' +import App from './App' + +const workspaceCode = 'NMS-0123456789ABCDEF0123456789ABCDEF' +const compactWorkspaceCode = workspaceCode.replace('-', '') + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + Reflect.deleteProperty(navigator, 'clipboard') +}) + +describe('organization routing', () => { + it('replaces Harborline cloning with organization ID access', async () => { + mockWorkspaceRequests() + renderApp(['/']) + + expect(await screen.findByRole('heading', { name: 'Open your organization' })).toBeInTheDocument() + expect(screen.getByLabelText('Organization ID')).toBeInTheDocument() + expect(screen.queryByText('Clone Harborline')).not.toBeInTheDocument() + }) + + it('opens an existing organization from a code without its hyphen', async () => { + const user = userEvent.setup() + mockWorkspaceRequests() + renderApp(['/']) + + await user.type(await screen.findByLabelText('Organization ID'), compactWorkspaceCode.toLowerCase()) + await user.click(screen.getByRole('button', { name: 'Open organization' })) + + expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument() + expect(screen.getByText(workspaceCode)).toBeInTheDocument() + }) + + it('loads the inventory route directly', async () => { + mockWorkspaceRequests() + renderApp([`/organizations/${workspaceCode}/inventory`]) + + expect(await screen.findByRole('heading', { name: 'Northstar Medical Supplies' })).toBeInTheDocument() + expect(await screen.findByRole('button', { name: 'Detailed inventory' })).toHaveAttribute('aria-pressed', 'true') + }) + + it('rejects a malformed organization ID before making a lookup request', async () => { + const user = userEvent.setup() + const fetchMock = mockWorkspaceRequests() + renderApp(['/']) + + await user.type(await screen.findByLabelText('Organization ID'), 'bad-id') + await user.click(screen.getByRole('button', { name: 'Open organization' })) + + expect(screen.getByRole('alert')).toHaveTextContent('Paste the complete organization ID from your saved link') + expect(fetchMock.mock.calls.some(([input]) => input.toString().includes('/by-code/'))).toBe(false) + }) + + it('keeps an unknown organization route open and offers recovery actions', async () => { + mockWorkspaceRequests() + renderApp(['/organizations/ABC-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF/map']) + + expect(await screen.findByRole('heading', { name: 'Organization not found' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Try another organization ID' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Return home' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Create a new organization' })).toBeInTheDocument() + }) + + it('loads the impact route directly without returning to the home page', async () => { + mockWorkspaceRequests() + renderApp([`/organizations/${workspaceCode}/impact`]) + + expect(await screen.findByRole('button', { name: 'Test impact' })).toHaveAttribute('aria-pressed', 'true') + expect(await screen.findByRole('heading', { name: 'Create one workflow first' })).toBeInTheDocument() + }) + + it.each([ + `/organizations/${workspaceCode}`, + `/organizations/${workspaceCode}/not-a-view`, + ])('redirects %s to the organization map', async (entry) => { + mockWorkspaceRequests() + renderApp([entry]) + + expect(await screen.findByRole('button', { name: 'Organization map' })).toHaveAttribute('aria-pressed', 'true') + }) + + it('loads the read-only example directly', async () => { + mockWorkspaceRequests() + renderApp(['/example']) + + expect(await screen.findByRole('heading', { name: 'See the blast radius before access changes go live.' })).toBeInTheDocument() + }) + + it('copies the stable organization ID and canonical map link', async () => { + const user = userEvent.setup() + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + mockWorkspaceRequests() + renderApp([`/organizations/${workspaceCode}/inventory`]) + + await user.click(await screen.findByRole('button', { name: 'Copy organization ID' })) + await user.click(screen.getByRole('button', { name: 'Copy organization link' })) + + expect(writeText).toHaveBeenNthCalledWith(1, workspaceCode) + expect(writeText).toHaveBeenNthCalledWith( + 2, + `${window.location.origin}/organizations/${workspaceCode}/map`, + ) + expect(screen.queryByRole('heading', { name: 'Save this organization ID' })).not.toBeInTheDocument() + }) + + it('shows recovery onboarding immediately after creating an organization', async () => { + const user = userEvent.setup() + mockWorkspaceRequests() + renderApp(['/']) + + await user.type(await screen.findByLabelText('Organization name'), 'Northstar Medical Supplies') + await user.click(screen.getByRole('button', { name: 'Start blank' })) + + expect(await screen.findByRole('heading', { name: 'Save this organization ID' })).toBeInTheDocument() + expect(screen.getByText(/Anyone with this link or ID can edit this organization/)).toBeInTheDocument() + expect(screen.getByText(/Do not enter confidential company or personal information/)).toBeInTheDocument() + }) +}) + +function renderApp(initialEntries: string[]) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + + + + , + ) +} + +function mockWorkspaceRequests() { + return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const url = input.toString() + if (url.endsWith('/api/v1/dashboard')) return jsonResponse(dashboardFixture) + if (url.endsWith('/api/v1/workspaces') && init?.method === 'POST') return jsonResponse(workspaceFixture, 201) + if (url.endsWith(`/api/v1/workspaces/by-code/${workspaceCode}`)) return jsonResponse(workspaceFixture) + if (url.endsWith('/catalog')) return jsonResponse(catalogFixture) + if (url.endsWith('/impact-previews/continuity')) return jsonResponse([]) + return jsonResponse({ message: 'Organization not found' }, 404) + }) +} + +function jsonResponse(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) +} + +const workspaceFixture = { + id: '10000000-0000-0000-0000-000000000001', + slug: 'northstar-medical-supplies', + name: 'Northstar Medical Supplies', + status: 'DRAFT', + currentVersion: 0, + publicCode: workspaceCode, + createdAt: '2026-08-21T12:00:00Z', + updatedAt: '2026-08-21T12:00:00Z', + counts: { teams: 0, members: 0, roles: 0, permissions: 0, capabilities: 0, workflows: 0 }, +} + +const catalogFixture = { + workspaceId: workspaceFixture.id, + teams: [], + members: [], + roles: [], + workflows: [], +} + +const dashboardFixture = { + organization: { + id: '00000000-0000-0000-0000-000000000001', + slug: 'harborline-commerce', + name: 'Harborline Commerce', + baselineVersion: 1, + contentHash: 'dbafb569ae3beaa13277897a7700ab32867675e31ee90cad74a9dc544d5c1fb4', + }, + counts: { + employees: 25, + activeEmployees: 24, + teams: 5, + roles: 8, + applications: 6, + permissions: 23, + capabilities: 10, + workflows: 4, + }, + workflows: [], +} diff --git a/frontend/src/api/workspaces.test.ts b/frontend/src/api/workspaces.test.ts new file mode 100644 index 0000000..46f130a --- /dev/null +++ b/frontend/src/api/workspaces.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { normalizeWorkspaceCode } from './workspaces' + +describe('normalizeWorkspaceCode', () => { + it('accepts a 16-character organization edit code with or without its separator', () => { + const displayed = 'NMS-7K4P9D8XM2QR6WBC' + + expect(normalizeWorkspaceCode(displayed.toLowerCase())).toBe(displayed) + expect(normalizeWorkspaceCode(displayed.replace('-', ''))).toBe(displayed) + expect(normalizeWorkspaceCode('NMS-7K4P9D')).toBeNull() + }) + + it('keeps existing 32-character organization IDs valid', () => { + const existing = 'NMS-0123456789ABCDEF0123456789ABCDEF' + + expect(normalizeWorkspaceCode(existing)).toBe(existing) + }) +}) diff --git a/frontend/src/api/workspaces.ts b/frontend/src/api/workspaces.ts index 03b991f..f1c9aac 100644 --- a/frontend/src/api/workspaces.ts +++ b/frontend/src/api/workspaces.ts @@ -4,7 +4,7 @@ export type Workspace = { name: string status: 'DRAFT' | 'PUBLISHED' currentVersion: number - sourceTemplateOrganizationId: string | null + publicCode: string createdAt: string updatedAt: string counts: { @@ -24,27 +24,29 @@ type WorkspaceInput = { const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? '' -export async function fetchWorkspaces(signal?: AbortSignal): Promise { - const response = await fetch(`${apiBaseUrl}/api/v1/workspaces`, { signal }) - return readResponse(response, 'Workspace list could not be loaded') +export function normalizeWorkspaceCode(rawCode: string): string | null { + const candidate = rawCode.trim().toUpperCase() + if (/^[A-HJ-NP-Z2-9]{3}-[A-HJ-NP-Z2-9]{16}$/.test(candidate)) return candidate + if (/^[A-HJ-NP-Z2-9]{19}$/.test(candidate)) return `${candidate.slice(0, 3)}-${candidate.slice(3)}` + if (/^[A-HJ-NP-Z2-9]{3}-[A-F0-9]{32}$/.test(candidate)) return candidate + if (/^[A-HJ-NP-Z2-9]{3}[A-F0-9]{32}$/.test(candidate)) return `${candidate.slice(0, 3)}-${candidate.slice(3)}` + return null } -export async function createWorkspace(input: WorkspaceInput): Promise { - const response = await fetch(`${apiBaseUrl}/api/v1/workspaces`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(input), - }) - return readResponse(response, 'Workspace could not be created') +export async function fetchWorkspaceByCode(rawCode: string, signal?: AbortSignal): Promise { + const code = normalizeWorkspaceCode(rawCode) + if (!code) throw new Error('Paste the complete organization ID from your saved link') + const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/by-code/${code}`, { signal }) + return readResponse(response, 'Organization not found') } -export async function cloneWorkspace(sourceWorkspaceId: string, input: WorkspaceInput): Promise { - const response = await fetch(`${apiBaseUrl}/api/v1/workspaces/${sourceWorkspaceId}/clones`, { +export async function createWorkspace(input: WorkspaceInput): Promise { + const response = await fetch(`${apiBaseUrl}/api/v1/workspaces`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input), }) - return readResponse(response, 'Workspace could not be cloned') + return readResponse(response, 'Organization could not be created') } async function readResponse(response: Response, fallbackMessage: string): Promise { diff --git a/frontend/src/components/workspaces/DraftWorkspace.tsx b/frontend/src/components/workspaces/DraftWorkspace.tsx index 6f3d0af..a800920 100644 --- a/frontend/src/components/workspaces/DraftWorkspace.tsx +++ b/frontend/src/components/workspaces/DraftWorkspace.tsx @@ -1,32 +1,78 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' import type { Workspace } from '../../api/workspaces' -import DraftEditor from './editor/DraftEditor' +import DraftEditor, { type DraftEditorView } from './editor/DraftEditor' type DraftWorkspaceProps = { workspace: Workspace - onBack: () => void + view: DraftEditorView + newlyCreated?: boolean + onViewChange: (view: DraftEditorView) => void } -export default function DraftWorkspace({ workspace, onBack }: DraftWorkspaceProps) { +export default function DraftWorkspace({ workspace, view, newlyCreated = false, onViewChange }: DraftWorkspaceProps) { + const navigate = useNavigate() + const [showOnboarding, setShowOnboarding] = useState(newlyCreated) + const [copyMessage, setCopyMessage] = useState(null) const isEmpty = workspace.counts.members === 0 + const isImpactView = view === 'impact' + + async function copyValue(value: string, message: string) { + try { + await navigator.clipboard.writeText(value) + setCopyMessage(message) + } catch { + setCopyMessage('Copy failed. Select the organization ID and copy it manually.') + } + } + + const organizationLink = `${window.location.origin}/organizations/${workspace.publicCode}/map` + return (
-
- - Draft · not yet published +
+ Editable organization + {workspace.publicCode} + + +
-
-

Organization builder

-

{workspace.name}

-

- {isEmpty - ? 'Your organization is ready. Add its first team and build outward from there.' - : 'Your Harborline copy is ready. Every record has a fresh identity, so changes here cannot affect the example.'} -

- - +
+ {copyMessage ?

{copyMessage}

: null} + {showOnboarding && !isImpactView ? ( +
+
+

Keep access to your work

+

Save this organization ID

+

+ Bookmark this page or copy the organization ID. Anyone with this link or ID can edit this + organization. Do not enter confidential company or personal information. +

+
+
+ + +
+
+ ) : null} + {!isImpactView ? ( + <> +

Organization builder

+

{workspace.name}

+

+ {isEmpty + ? 'Your organization is ready. Add its first team and build outward from there.' + : 'Edit the model, test access changes, and return later using the organization ID or link.'} +

+ + ) : null} + +
) diff --git a/frontend/src/components/workspaces/OrganizationRoute.tsx b/frontend/src/components/workspaces/OrganizationRoute.tsx new file mode 100644 index 0000000..57fedf9 --- /dev/null +++ b/frontend/src/components/workspaces/OrganizationRoute.tsx @@ -0,0 +1,86 @@ +import { useEffect } from 'react' +import { useQuery } from '@tanstack/react-query' +import { Navigate, useLocation, useNavigate, useParams } from 'react-router-dom' +import { fetchWorkspaceByCode, normalizeWorkspaceCode } from '../../api/workspaces' +import DraftWorkspace from './DraftWorkspace' +import type { DraftEditorView } from './editor/DraftEditor' + +const validViews: DraftEditorView[] = ['map', 'impact', 'inventory'] + +export default function OrganizationRoute() { + const { publicCode = '', view = '' } = useParams() + const navigate = useNavigate() + const location = useLocation() + const routeState = location.state as { newlyCreated?: boolean } | null + const normalizedCode = normalizeWorkspaceCode(publicCode) + const validView = validViews.includes(view as DraftEditorView) ? view as DraftEditorView : null + const workspaceQuery = useQuery({ + queryKey: ['workspace', normalizedCode], + queryFn: ({ signal }) => fetchWorkspaceByCode(normalizedCode!, signal), + enabled: Boolean(normalizedCode), + retry: false, + }) + + useEffect(() => { + if (routeState?.newlyCreated) { + navigate(location.pathname, { replace: true, state: null }) + } + }, [location.pathname, navigate, routeState?.newlyCreated]) + + if (normalizedCode && !validView) { + return + } + + if (!normalizedCode) { + return + } + + if (workspaceQuery.isPending) { + return ( +
+
+ ) + } + + if (workspaceQuery.isError) { + return ( + void workspaceQuery.refetch()} + /> + ) + } + + return ( + navigate(`/organizations/${workspaceQuery.data.publicCode}/${nextView}`)} + /> + ) +} + +function OrganizationRecovery({ title, detail, onRetry }: { + title: string + detail?: string + onRetry?: () => void +}) { + const navigate = useNavigate() + return ( +
+

Organization access

+

{title}

+

{detail ?? 'Check the organization ID and try again.'}

+
+ {onRetry ? : null} + + + +
+
+ ) +} diff --git a/frontend/src/components/workspaces/WorkspaceWelcome.tsx b/frontend/src/components/workspaces/WorkspaceWelcome.tsx index 8980f51..bb219b9 100644 --- a/frontend/src/components/workspaces/WorkspaceWelcome.tsx +++ b/frontend/src/components/workspaces/WorkspaceWelcome.tsx @@ -1,50 +1,57 @@ import { useState, type FormEvent } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { cloneWorkspace, createWorkspace, fetchWorkspaces, type Workspace } from '../../api/workspaces' +import { useNavigate } from 'react-router-dom' +import { fetchDashboard } from '../../api/dashboard' +import { + createWorkspace, + fetchWorkspaceByCode, + normalizeWorkspaceCode, +} from '../../api/workspaces' -type WorkspaceWelcomeProps = { - onExploreTemplate: () => void - onOpenDraft: (workspace: Workspace) => void -} - -export default function WorkspaceWelcome({ onExploreTemplate, onOpenDraft }: WorkspaceWelcomeProps) { +export default function WorkspaceWelcome() { + const navigate = useNavigate() const queryClient = useQueryClient() + const [organizationCode, setOrganizationCode] = useState('') const [blankName, setBlankName] = useState('') - const [cloneName, setCloneName] = useState('Harborline Sandbox') - const workspacesQuery = useQuery({ - queryKey: ['workspaces'], - queryFn: ({ signal }) => fetchWorkspaces(signal), + const [codeError, setCodeError] = useState(null) + const dashboardQuery = useQuery({ + queryKey: ['dashboard', 'harborline-commerce'], + queryFn: ({ signal }) => fetchDashboard(signal), retry: 1, }) - const harborline = workspacesQuery.data?.find((workspace) => workspace.slug === 'harborline-commerce') - - const blankMutation = useMutation({ - mutationFn: createWorkspace, + const openMutation = useMutation({ + mutationFn: (code: string) => fetchWorkspaceByCode(code), onSuccess: (workspace) => { - queryClient.setQueryData(['workspaces'], (current = []) => [...current, workspace]) - onOpenDraft(workspace) + queryClient.setQueryData(['workspace', workspace.publicCode], workspace) + navigate(`/organizations/${workspace.publicCode}/map`) }, }) - const cloneMutation = useMutation({ - mutationFn: ({ sourceId, name }: { sourceId: string; name: string }) => cloneWorkspace(sourceId, { name }), + const blankMutation = useMutation({ + mutationFn: createWorkspace, onSuccess: (workspace) => { - queryClient.setQueryData(['workspaces'], (current = []) => [...current, workspace]) - onOpenDraft(workspace) + queryClient.setQueryData(['workspace', workspace.publicCode], workspace) + navigate(`/organizations/${workspace.publicCode}/map`, { state: { newlyCreated: true } }) }, }) - function submitBlank(event: FormEvent) { + function submitCode(event: FormEvent) { event.preventDefault() - if (blankName.trim()) blankMutation.mutate({ name: blankName.trim() }) + setCodeError(null) + const normalizedCode = normalizeWorkspaceCode(organizationCode) + if (!normalizedCode) { + setCodeError('Paste the complete organization ID from your saved link') + return + } + openMutation.mutate(normalizedCode) } - function submitClone(event: FormEvent) { + function submitBlank(event: FormEvent) { event.preventDefault() - if (harborline && cloneName.trim()) { - cloneMutation.mutate({ sourceId: harborline.id, name: cloneName.trim() }) - } + if (blankName.trim()) blankMutation.mutate({ name: blankName.trim() }) } + const counts = dashboardQuery.data?.counts + return (
@@ -63,81 +70,88 @@ export default function WorkspaceWelcome({ onExploreTemplate, onOpenDraft }: Wor

Model your organization

Build the access graph your business actually runs on.

- Start with a working example or build a clean model of your own people, roles, - permissions, capabilities, and workflows. + Start with a working example, reopen an existing organization, or build a clean model + of your own people, roles, responsibilities, and workflows.

- {workspacesQuery.isError ? ( -
- Workspaces could not be loaded. - -
- ) : ( -
-
- 01 -
-

Learn from the example

-

Explore Harborline

-

See Priya’s role change travel through a complete, realistic business workflow.

-
-
-
Members
{harborline?.counts.members ?? '—'}
-
Roles
{harborline?.counts.roles ?? '—'}
-
Workflows
{harborline?.counts.workflows ?? '—'}
-
- -
+
+
+ 01 +
+

Learn from the example

+

Explore Harborline

+

See Priya’s role change travel through a complete, realistic business workflow.

+
+
+
Members
{counts?.employees ?? '—'}
+
Roles
{counts?.roles ?? '—'}
+
Workflows
{counts?.workflows ?? '—'}
+
+ + {dashboardQuery.isError ? ( +

Example statistics are temporarily unavailable.

+ ) : null} +
-
- 02 -
-

Fastest way to customize

-

Clone Harborline

-

Copy the full example into an editable draft, then reshape it into your own organization.

-
-
- - setCloneName(event.target.value)} - /> - - {cloneMutation.isError ?

{cloneMutation.error.message}

: null} -
-
+
+ 02 +
+

Continue where you left off

+

Open your organization

+

Enter the editable organization ID you saved when the workspace was created.

+
+
+ + { + setOrganizationCode(event.target.value) + setCodeError(null) + openMutation.reset() + }} + /> + + {codeError ?

{codeError}

: null} + {openMutation.isError ? ( +

{openMutation.error.message}

+ ) : null} +
+
-
- 03 -
-

Start from first principles

-

Create a blank organization

-

Begin with an empty draft and add only the teams and relationships you need.

-
-
- - setBlankName(event.target.value)} - /> - - {blankMutation.isError ?

{blankMutation.error.message}

: null} -
-
-
- )} +
+ 03 +
+

Start from first principles

+

Create a blank organization

+

Begin with an empty draft and add only the teams and relationships you need.

+
+
+ + setBlankName(event.target.value)} + /> + + {blankMutation.isError ? ( +

{blankMutation.error.message}

+ ) : null} +
+
+
) diff --git a/frontend/src/components/workspaces/editor/DraftEditor.tsx b/frontend/src/components/workspaces/editor/DraftEditor.tsx index 99d1413..ee37981 100644 --- a/frontend/src/components/workspaces/editor/DraftEditor.tsx +++ b/frontend/src/components/workspaces/editor/DraftEditor.tsx @@ -25,9 +25,14 @@ const DraftImpactTesting = lazy(() => import('./DraftImpactTesting')) type EditorStage = 'teams' | 'members' | 'roles' | 'workflows' -export default function DraftEditor({ workspaceId, isTemplateClone }: { workspaceId: string; isTemplateClone: boolean }) { +export type DraftEditorView = 'map' | 'impact' | 'inventory' + +export default function DraftEditor({ workspaceId, view, onViewChange }: { + workspaceId: string + view: DraftEditorView + onViewChange: (view: DraftEditorView) => void +}) { const [stage, setStage] = useState('teams') - const [view, setView] = useState<'map' | 'impact' | 'inventory'>('map') const editorRef = useRef(null) const catalogQuery = useQuery({ queryKey: ['draft-catalog', workspaceId], @@ -67,42 +72,46 @@ export default function DraftEditor({ workspaceId, isTemplateClone }: { workspac function openInventory(nextStage?: EditorStage) { if (nextStage) setStage(nextStage) - setView('inventory') + onViewChange('inventory') window.requestAnimationFrame(() => editorRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' })) } return ( -
-
-
-

{view === 'impact' ? 'Business continuity lab' : 'Visual organization builder'}

-

{view === 'impact' ? 'Test a change before it happens' : 'Map how your organization works'}

-
+
+
+ {view !== 'impact' ? ( +
+

Visual organization builder

+

Map how your organization works

+
+ ) : null}
- - - + + +
-
- {liveCounts.map((count) => ( -
{count.value}{count.label}
- ))} -
+ {view !== 'impact' ? ( +
+ {liveCounts.map((count) => ( +
{count.value}{count.label}
+ ))} +
+ ) : null} {view === 'map' && !continuityQuery.isFetching && !continuityQuery.isError && firstBlockedRisk && firstBlockedMember ? (
{singlePointRisks.length} critical coverage gap{singlePointRisks.length === 1 ? '' : 's'} found

According to the impact engine, removing {firstBlockedRisk.roleName} from {firstBlockedMember.name} would block {firstBlockedRisk.workflowName}.

- +
) : null} {view === 'map' ? ( - Opening the organization map…

}> openInventory()} onOpenWorkflows={() => openInventory('workflows')} onTestImpact={() => setView('impact')} />
+ Opening the organization map…

}> openInventory()} onOpenWorkflows={() => openInventory('workflows')} onTestImpact={() => onViewChange('impact')} />
) : view === 'impact' ? ( - Preparing impact testing…

}> void continuityQuery.refetch()} onBackToMap={() => setView('map')} />
+ Preparing impact testing…

}> void continuityQuery.refetch()} onBackToMap={() => onViewChange('map')} />
) : ( <>