From efbbeec9ce13790ddb5f18afaad1ba999fa1a862 Mon Sep 17 00:00:00 2001 From: Jason Sylvestre Date: Tue, 27 Oct 2026 13:46:06 -0700 Subject: [PATCH 1/2] Slug for resources Introduces a new 'slug' field for resources, enabling stable and human-readable URLs. This change includes: - Client-side auto-suggestion of slugs based on the resource name, which stops updating once manually edited. - Client-side and server-side validation for slug format (lowercase, numbers, single hyphens, max 120 characters). - Server-side enforcement of slug uniqueness within a team and within a location, including inactive resources, to prevent conflicts. - Updates to the API and data models to persist the slug. --- .../src/features/resources/ResourceEditor.tsx | 74 ++++- .../resources/models/SaveResourceRequest.ts | 1 + .../(authenticated)/teams.resources.test.tsx | 126 +++++++++ .../Models/Resources/SaveResourceRequest.cs | 3 + server/Services/TeamResourceService.cs | 75 +++-- .../TeamResourcesControllerTests.cs | 257 +++++++++++++++++- 6 files changed, 510 insertions(+), 26 deletions(-) diff --git a/client/src/features/resources/ResourceEditor.tsx b/client/src/features/resources/ResourceEditor.tsx index e496718..fa09e6f 100644 --- a/client/src/features/resources/ResourceEditor.tsx +++ b/client/src/features/resources/ResourceEditor.tsx @@ -33,6 +33,17 @@ import { useAppForm } from '@/shared/forms/formContext.tsx'; const standardCategories = ['Room', 'Bench', 'Equipment']; +function suggestSlug(name: string) { + return name + .normalize('NFKD') + .replaceAll(/[\u0300-\u036f]/g, '') + .toLowerCase() + .replaceAll(/[^\da-z]+/g, '-') + .replaceAll(/^-+|-+$/g, '') + .slice(0, 120) + .replaceAll(/-+$/g, ''); +} + function readConfiguration( resource?: ResourceDetail, template?: ResourceTemplate @@ -100,6 +111,7 @@ function resourceFormValues( name: resource?.name ?? '', publicAccess: resource?.publicAccess ?? 'availability', resourceDefaults: resourceDefaultsFormValues(configuration.defaults), + slug: resource?.slug ?? '', sourceTemplateId: '', spaceId: resource ? String(resource.spaceId) @@ -134,6 +146,7 @@ export function ResourceEditor({ const [saved, setSaved] = useState(false); const [isSaving, setIsSaving] = useState(false); const saveFlowRef = useRef(false); + const slugEditedRef = useRef(Boolean(resource)); const activeTemplates = options.templates.filter( (template) => template.isActive ); @@ -155,6 +168,14 @@ export function ResourceEditor({ if (!value.name.trim() || value.name.trim().length > 200) { fields.name = 'Enter a resource name of 200 characters or fewer.'; } + if (!value.slug) { + fields.slug = 'Enter a resource slug.'; + } else if (value.slug.length > 120) { + fields.slug = 'Use 120 characters or fewer.'; + } else if (!/^[\da-z]+(?:-[\da-z]+)*$/.test(value.slug)) { + fields.slug = + 'Use lowercase letters, numbers, and single hyphens between words.'; + } if (value.category === 'Other') { if ( !value.customCategory.trim() || @@ -265,6 +286,7 @@ export function ResourceEditor({ name: value.name.trim(), publicAccess: baseline?.parentResourceId != null ? null : value.publicAccess, + slug: value.slug, spaceId: baseline?.spaceId ?? Number(value.spaceId), ...(baseline ? { @@ -694,7 +716,16 @@ export function ResourceEditor({ selector={(state) => state.values.category} > {(category) => ( - + { + if (!baseline && !slugEditedRef.current) { + form.setFieldValue('slug', suggestSlug(value)); + } + }, + }} + name="name" + > {(field) => ( + + {(field) => { + const hasError = + field.state.meta.isTouched && + !field.state.meta.isValid; + return ( + + { + slugEditedRef.current = true; + field.handleChange(event.target.value); + }} + required + spellCheck={false} + type="text" + value={field.state.value} + /> +

+ Use lowercase letters, numbers, and single hyphens + between words. You can change the suggested slug. + It must be unique within this team’s resources. +

+
+ ); + }} +
{(field) => { const hasError = diff --git a/client/src/features/resources/models/SaveResourceRequest.ts b/client/src/features/resources/models/SaveResourceRequest.ts index 77723a9..264a253 100644 --- a/client/src/features/resources/models/SaveResourceRequest.ts +++ b/client/src/features/resources/models/SaveResourceRequest.ts @@ -16,6 +16,7 @@ export interface SaveResourceRequest { isReservable: boolean; name: string; publicAccess: ResourceDetail['publicAccess']; + slug: string; sourceTemplateId?: number | null; spaceId: number; updatedAt?: string; diff --git a/client/src/test/routes/(authenticated)/teams.resources.test.tsx b/client/src/test/routes/(authenticated)/teams.resources.test.tsx index 2cd1730..d459f80 100644 --- a/client/src/test/routes/(authenticated)/teams.resources.test.tsx +++ b/client/src/test/routes/(authenticated)/teams.resources.test.tsx @@ -352,6 +352,7 @@ describe('team resources', () => { expect(requests[0]).toMatchObject({ expectedConfigId: 10, name: 'My unsaved edit', + slug: 'microscope', updatedAt: resource().updatedAt, }); expect(await screen.findByRole('alert')).toHaveTextContent( @@ -412,6 +413,9 @@ describe('team resources', () => { await screen.findByRole('textbox', { name: 'Resource name' }), { target: { value: 'New microscope' } } ); + expect(screen.getByRole('textbox', { name: 'Resource slug' })).toHaveValue( + 'new-microscope' + ); const category = screen.getByRole('combobox', { name: 'Category' }); for (const name of ['Room', 'Bench', 'Equipment', 'Other']) { expect( @@ -451,6 +455,7 @@ describe('team resources', () => { expect(requests[0]).toMatchObject({ category: 'Equipment', name: 'New microscope', + slug: 'new-microscope', sourceTemplateId: 1, spaceId: 2, }); @@ -466,6 +471,127 @@ describe('team resources', () => { ).toHaveValue('New microscope'); }); + it('suggests a normalized resource slug until it is customized and retains it after a conflict', async () => { + mockAccess(); + const saved = mockResources([]); + const requests: SaveResourceRequest[] = []; + server.use( + http.post('/api/teams/:teamSlug/resources', async ({ request }) => { + const body = (await request.json()) as SaveResourceRequest; + requests.push(body); + if (requests.length === 1) { + return HttpResponse.json( + 'This resource slug is already in use by another resource in this team.', + { status: 409 } + ); + } + const created = resource({ ...body, id: 2 }); + saved.set(created.id, created); + return HttpResponse.json(created, { status: 201 }); + }) + ); + const rendered = renderRoute({ initialPath: `${listPath}/new` }); + cleanup = rendered.cleanup; + fireEvent.change( + await screen.findByRole('combobox', { name: 'Resource template' }), + { target: { value: '1' } } + ); + const name = await screen.findByRole('textbox', { name: 'Resource name' }); + const slug = screen.getByRole('textbox', { name: 'Resource slug' }); + fireEvent.change(name, { target: { value: ' Café Microscope / #2 ' } }); + expect(slug).toHaveValue('cafe-microscope-2'); + fireEvent.change(name, { target: { value: 'Café Microscope / #3' } }); + expect(slug).toHaveValue('cafe-microscope-3'); + fireEvent.change(slug, { target: { value: 'research-scope' } }); + fireEvent.change(name, { target: { value: 'Research microscope' } }); + expect(slug).toHaveValue('research-scope'); + fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), { + target: { value: 'Equipment' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Create resource' })); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'This resource slug is already in use by another resource in this team.' + ); + expect(requests).toHaveLength(1); + expect(requests[0]).toMatchObject({ + name: 'Research microscope', + slug: 'research-scope', + }); + expect(name).toHaveValue('Research microscope'); + expect(slug).toHaveValue('research-scope'); + await waitFor(() => expect(slug).toBeEnabled()); + fireEvent.change(slug, { target: { value: 'research-scope-2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create resource' })); + await waitFor(() => expect(requests).toHaveLength(2)); + expect(requests[1]).toMatchObject({ + name: 'Research microscope', + slug: 'research-scope-2', + }); + await waitFor(() => + expect(rendered.router.state.location.pathname).toBe(`${listPath}/2`) + ); + expect( + await screen.findByRole('textbox', { name: 'Resource slug' }) + ).toHaveValue('research-scope-2'); + }); + + it('preserves an existing slug when renaming and allows an explicit slug change', async () => { + mockAccess(); + const saved = mockResources(); + const requests: SaveResourceRequest[] = []; + server.use( + http.put('/api/teams/:teamSlug/resources/:id', async ({ request }) => { + const body = (await request.json()) as SaveResourceRequest; + requests.push(body); + const updated = resource({ ...body }); + saved.set(updated.id, updated); + return HttpResponse.json(updated); + }) + ); + ({ cleanup } = renderRoute({ initialPath: `${listPath}/1` })); + const name = await screen.findByRole('textbox', { name: 'Resource name' }); + const slug = screen.getByRole('textbox', { name: 'Resource slug' }); + expect(slug).toHaveValue('microscope'); + fireEvent.change(name, { target: { value: 'Renamed microscope' } }); + expect(slug).toHaveValue('microscope'); + fireEvent.change(slug, { target: { value: 'imaging-scope-2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); + await waitFor(() => expect(requests).toHaveLength(1)); + expect(requests[0]).toMatchObject({ + expectedConfigId: 10, + name: 'Renamed microscope', + slug: 'imaging-scope-2', + updatedAt: resource().updatedAt, + }); + await waitFor(() => expect(slug).toBeEnabled()); + expect(slug).toHaveValue('imaging-scope-2'); + }); + + it.each([ + '', + 'Microscope', + 'lab scope', + 'lab_scope', + 'lab@scope', + '-microscope', + 'micro--scope', + 'microscope-', + 'a'.repeat(121), + ])('rejects invalid resource slug %j before saving', async (value) => { + mockAccess(); + mockResources(); + const update = vi.fn(() => HttpResponse.json(resource())); + server.use(http.put('/api/teams/:teamSlug/resources/:id', update)); + ({ cleanup } = renderRoute({ initialPath: `${listPath}/1` })); + const slug = await screen.findByRole('textbox', { name: 'Resource slug' }); + fireEvent.change(slug, { target: { value } }); + fireEvent.blur(slug); + fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); + await waitFor(() => expect(slug).toHaveAttribute('aria-invalid', 'true')); + expect(slug).toHaveAccessibleDescription(/slug|lowercase|120/); + expect(update).not.toHaveBeenCalled(); + }); + it('requires valid resource fields before creating a resource', async () => { mockAccess(); mockResources([]); diff --git a/server/Models/Resources/SaveResourceRequest.cs b/server/Models/Resources/SaveResourceRequest.cs index 8c020f0..abde6c2 100644 --- a/server/Models/Resources/SaveResourceRequest.cs +++ b/server/Models/Resources/SaveResourceRequest.cs @@ -11,6 +11,9 @@ public sealed class SaveResourceRequest [StringLength(200)] public string Name { get; init; } = string.Empty; + [StringLength(120)] + public string? Slug { get; init; } + [Required] [StringLength(50)] public string Category { get; init; } = string.Empty; diff --git a/server/Services/TeamResourceService.cs b/server/Services/TeamResourceService.cs index 04ae7c7..dbaafdc 100644 --- a/server/Services/TeamResourceService.cs +++ b/server/Services/TeamResourceService.cs @@ -16,6 +16,9 @@ namespace Server.Services; public sealed class TeamResourceService(AppDbContext dbContext) { private const string StaleMessage = "This resource has changed since you opened it. Reload it before saving again."; + private const string InvalidSlugMessage = "Enter a slug of no more than 120 lowercase letters, numbers, and single hyphens between words."; + private const string DuplicateSlugMessage = "A resource with that slug already exists in this team, including inactive resources. Choose another slug."; + private const string DuplicateLocationSlugMessage = "A resource with that slug already exists at this location, including inactive resources. Choose another slug."; private static readonly string[] Days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]; public Task> GetResources(int teamId, CancellationToken cancellationToken) @@ -69,7 +72,7 @@ public async Task GetOptions(int teamId, CancellationTo } // Keep resource and configuration changes together. Serializable reads also - // protect location availability, sibling names and parent activation checks against concurrent saves. + // protect location availability, sibling names, team slugs and parent activation checks against concurrent saves. await using var transaction = dbContext.Database.IsRelational() ? await dbContext.Database.BeginTransactionAsync(IsolationLevel.Serializable, cancellationToken) : null; @@ -86,11 +89,11 @@ public async Task GetOptions(int teamId, CancellationTo } catch (DbUpdateException exception) when (IsConcurrentConflict(exception.InnerException)) { - return (null, "Another resource or location was saved at the same time. Reload and check the name before trying again.", 409); + return (null, "Another resource or location was saved at the same time. Reload and check the name and slug before trying again.", 409); } catch (SqlException exception) when (IsConcurrentConflict(exception)) { - return (null, "Another resource or location was saved at the same time. Reload before trying again.", 409); + return (null, "Another resource or location was saved at the same time. Reload and check the name and slug before trying again.", 409); } } @@ -145,11 +148,25 @@ public async Task GetOptions(int teamId, CancellationTo return (null, "A resource with that name already exists at this location, including inactive resources.", 409); } + var slug = request.Slug?.Trim() ?? CreateSlug(request.Name); + if (!ValidSlug(slug)) + { + return (null, InvalidSlugMessage, 400); + } + if (await DuplicateSlug(teamId, slug, null, cancellationToken)) + { + return (null, DuplicateSlugMessage, 409); + } + if (await DuplicateLocationSlug(space.Id, slug, null, cancellationToken)) + { + return (null, DuplicateLocationSlugMessage, 409); + } + var now = DateTimeOffset.UtcNow; var resource = new Resource { TeamId = teamId, SpaceId = space.Id, Name = request.Name.Trim(), NameKey = nameKey, - Category = request.Category.Trim(), Slug = CreateSlug(request.Name), CreatedAt = now, + Category = request.Category.Trim(), Slug = slug, CreatedAt = now, }; ApplyMetadata(resource, request, nameKey, now, userId); dbContext.Resources.Add(resource); @@ -195,6 +212,15 @@ public async Task GetOptions(int teamId, CancellationTo { return (null, "A sibling resource with that name already exists at this location, including inactive resources.", 409); } + var slug = request.Slug?.Trim() ?? resource.Slug; + if (await DuplicateSlug(teamId, slug, id, cancellationToken)) + { + return (null, DuplicateSlugMessage, 409); + } + if (await DuplicateLocationSlug(resource.SpaceId, slug, id, cancellationToken)) + { + return (null, DuplicateLocationSlugMessage, 409); + } var error = await ValidateActivation(resource, request.IsActive, cancellationToken); if (error != null) { @@ -251,6 +277,7 @@ public async Task GetOptions(int teamId, CancellationTo var updated = await original.ExecuteUpdateAsync(setters => setters .SetProperty(current => current.Name, request.Name.Trim()) .SetProperty(current => current.NameKey, nameKey) + .SetProperty(current => current.Slug, slug) .SetProperty(current => current.Category, request.Category.Trim()) .SetProperty(current => current.Description, TrimOptional(request.Description)) .SetProperty(current => current.Capacity, request.Capacity) @@ -275,6 +302,7 @@ public async Task GetOptions(int teamId, CancellationTo return (null, StaleMessage, 409); } ApplyMetadata(tracked, request, nameKey, now, userId); + tracked.Slug = slug; } if (formChanged || detailsChanged) { @@ -290,6 +318,7 @@ public async Task GetOptions(int teamId, CancellationTo } await dbContext.SaveChangesAsync(cancellationToken); ApplyMetadata(resource, request, nameKey, now, userId); + resource.Slug = slug; return (ToResponse(resource, config, resource.Space), null, 200); } @@ -301,6 +330,14 @@ private Task DuplicateName(int spaceId, int? parentId, string nameKey, int => dbContext.Resources.AnyAsync(resource => resource.SpaceId == spaceId && resource.ParentResourceId == parentId && resource.NameKey == nameKey && (exceptId == null || resource.Id != exceptId), cancellationToken); + private Task DuplicateSlug(int teamId, string slug, int? exceptId, CancellationToken cancellationToken) + => dbContext.Resources.AnyAsync(resource => resource.TeamId == teamId && resource.Slug == slug && + (exceptId == null || resource.Id != exceptId), cancellationToken); + + private Task DuplicateLocationSlug(int spaceId, string slug, int? exceptId, CancellationToken cancellationToken) + => dbContext.Resources.AnyAsync(resource => resource.SpaceId == spaceId && resource.Slug == slug && + (exceptId == null || resource.Id != exceptId), cancellationToken); + private async Task ValidateActivation(Resource resource, bool isActive, CancellationToken cancellationToken) { if (!isActive) @@ -351,6 +388,10 @@ private Task DuplicateName(int spaceId, int? parentId, string nameKey, int { return "Enter a resource name of no more than 200 characters without control characters."; } + if (request.Slug != null && !ValidSlug(request.Slug.Trim())) + { + return InvalidSlugMessage; + } if (string.IsNullOrWhiteSpace(request.Category) || request.Category.Trim().Length > 50) { return "Enter a resource category of no more than 50 characters."; @@ -527,26 +568,16 @@ private static bool TryText(JsonElement element, string property, out string val private static string CreateSlug(string name) { - var normalized = name.Normalize(NormalizationForm.FormD); - var builder = new StringBuilder(); - foreach (var character in normalized) - { - if (CharUnicodeInfo.GetUnicodeCategory(character) == UnicodeCategory.NonSpacingMark) - { - continue; - } - var lower = char.ToLowerInvariant(character); - builder.Append(lower >= 'a' && lower <= 'z' || lower >= '0' && lower <= '9' ? lower : '-'); - } - var prefix = Regex.Replace(builder.ToString(), "-+", "-").Trim('-'); - if (prefix.Length == 0) - { - prefix = "resource"; - } - prefix = prefix[..Math.Min(prefix.Length, 80)].TrimEnd('-'); - return $"{prefix}-{Guid.NewGuid():N}"; + var normalized = Regex.Replace(name.Normalize(NormalizationForm.FormKD), @"[\u0300-\u036f]", string.Empty) + .ToLowerInvariant(); + var slug = Regex.Replace(normalized, "[^a-z0-9]+", "-").Trim('-'); + return slug[..Math.Min(slug.Length, 120)].TrimEnd('-'); } + private static bool ValidSlug(string slug) + => slug.Length > 0 && slug.Length <= 120 && + Regex.IsMatch(slug, @"\A[a-z0-9]+(?:-[a-z0-9]+)*\z", RegexOptions.CultureInvariant); + private static bool IsConcurrentConflict(Exception? exception) => exception is SqlException sql && (sql.Number == 2601 || sql.Number == 2627 || sql.Number == 1205); diff --git a/tests/server.tests/Controllers/TeamResourcesControllerTests.cs b/tests/server.tests/Controllers/TeamResourcesControllerTests.cs index 98f81b3..3a7f78d 100644 --- a/tests/server.tests/Controllers/TeamResourcesControllerTests.cs +++ b/tests/server.tests/Controllers/TeamResourcesControllerTests.cs @@ -149,7 +149,7 @@ public async Task Editors_and_above_create_a_root_resource_and_published_configu resource.SpaceId.Should().Be(space.Id); resource.ParentResourceId.Should().BeNull(); resource.NameKey.Should().Be("MEETING ROOM"); - resource.Slug.Should().NotBeNullOrWhiteSpace(); + resource.Slug.Should().Be("meeting-room"); resource.IsActive.Should().BeTrue(); resource.UpdatedByUserId.Should().Be(user.Id); (await db.Spaces.CountAsync()).Should().Be(1); @@ -166,6 +166,257 @@ public async Task Editors_and_above_create_a_root_resource_and_published_configu config.PublishedAt.Should().NotBeNull(); } + [Theory] + [InlineData(" Caf\u00e9 / Meeting \u2460 ", "cafe-meeting-1")] + [InlineData("Room---A & B", "room-a-b")] + public async Task Creation_suggests_a_lowercase_hyphenated_slug_from_the_name(string name, string expected) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, _) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var template = Template("Template", team.Id); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + + var response = ReadCreated(await CreateController(db).CreateResource(team.Slug, + Request(space.Id, template.Id, name: name))); + + response.Slug.Should().Be(expected); + db.ChangeTracker.Clear(); + (await db.Resources.SingleAsync()).Slug.Should().Be(expected); + } + + [Fact] + public async Task Creation_limits_generated_slugs_to_120_characters_and_accepts_a_custom_slug() + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, _) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var template = Template("Template", team.Id); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + var controller = CreateController(db); + + ReadCreated(await controller.CreateResource(team.Slug, + Request(space.Id, template.Id, name: new string('A', 119) + " room"))) + .Slug.Should().Be(new string('a', 119)); + ReadCreated(await controller.CreateResource(team.Slug, + Request(space.Id, template.Id, name: "Custom room", slug: new string('b', 120)))) + .Slug.Should().Be(new string('b', 120)); + } + + [Fact] + public async Task Names_without_slug_characters_require_a_custom_slug() + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, _) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var template = Template("Template", team.Id); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + var controller = CreateController(db); + + (await controller.CreateResource(team.Slug, Request(space.Id, template.Id, name: "---"))) + .Result.Should().BeOfType(); + (await db.Resources.AnyAsync()).Should().BeFalse(); + ReadCreated(await controller.CreateResource(team.Slug, + Request(space.Id, template.Id, name: "---", slug: "custom-room-1"))).Slug.Should().Be("custom-room-1"); + } + + [Theory] + [InlineData("custom-room-1")] + [InlineData("meeting-room")] + public async Task Updates_accept_changed_or_unchanged_slugs_without_publishing_configuration(string slug) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, user) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var (resource, config) = await SeedResource(db, team, space, user); + + ReadOk(await CreateController(db).UpdateResource(team.Slug, resource.Id, + Request(saved: resource, config: config, slug: slug))).Slug.Should().Be(slug); + + db.ChangeTracker.Clear(); + (await db.Resources.SingleAsync()).Slug.Should().Be(slug); + (await db.ResourceConfigs.SingleAsync()).Id.Should().Be(config.Id); + } + + [Theory] + [InlineData("")] + [InlineData("Meeting-room")] + [InlineData("meeting room")] + [InlineData("meeting_room")] + [InlineData("meeting/room")] + [InlineData("meeting--room")] + [InlineData("-meeting")] + [InlineData("meeting-")] + [InlineData("caf\u00e9")] + public async Task Invalid_custom_slugs_are_rejected_on_create_and_update(string slug) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, user) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var template = Template("Template", team.Id); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + var controller = CreateController(db); + + (await controller.CreateResource(team.Slug, Request(space.Id, template.Id, slug: slug))) + .Result.Should().BeOfType(); + (await db.Resources.AnyAsync()).Should().BeFalse(); + var (resource, config) = await SeedResource(db, team, space, user); + (await controller.UpdateResource(team.Slug, resource.Id, + Request(saved: resource, config: config, name: "Changed name", slug: slug))) + .Result.Should().BeOfType(); + db.ChangeTracker.Clear(); + var saved = await db.Resources.SingleAsync(); + saved.Slug.Should().Be("meeting-room"); + saved.Name.Should().Be("Meeting room"); + (await db.ResourceConfigs.CountAsync()).Should().Be(1); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Slugs_longer_than_120_characters_are_rejected(bool update) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, user) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var template = Template("Template", team.Id); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + var (resource, config) = await SeedResource(db, team, space, user); + var controller = CreateController(db); + var request = update + ? Request(saved: resource, config: config, slug: new string('a', 121)) + : Request(space.Id, template.Id, name: "Another room", slug: new string('a', 121)); + + var result = update + ? await controller.UpdateResource(team.Slug, resource.Id, request) + : await controller.CreateResource(team.Slug, request); + + result.Result.Should().BeOfType(); + db.ChangeTracker.Clear(); + (await db.Resources.SingleAsync()).Slug.Should().Be("meeting-room"); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task Team_slug_conflicts_include_other_locations_and_inactive_resources(bool update, bool isActive) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, user) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var otherSpace = await SeedSpace(db, team, "Other location"); + var template = Template("Template", team.Id); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + await SeedResource(db, team, otherSpace, user, "Existing room", isActive: isActive); + var controller = CreateController(db); + + ActionResult result; + if (update) + { + var (resource, config) = await SeedResource(db, team, space, user); + result = await controller.UpdateResource(team.Slug, resource.Id, + Request(saved: resource, config: config, name: "Changed room", slug: "existing-room")); + db.ChangeTracker.Clear(); + var unchanged = await db.Resources.SingleAsync(value => value.Id == resource.Id); + unchanged.Slug.Should().Be("meeting-room"); + unchanged.Name.Should().Be("Meeting room"); + } + else + { + // An automatically suggested slug has the same team-wide uniqueness requirement. + result = await controller.CreateResource(team.Slug, Request(space.Id, template.Id, name: "Existing room")); + (await db.Resources.CountAsync()).Should().Be(1); + } + + result.Result.Should().BeOfType().Subject.Value.Should().Be( + "A resource with that slug already exists in this team, including inactive resources. Choose another slug."); + (await db.ResourceConfigs.CountAsync()).Should().Be(update ? 2 : 1); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Different_teams_at_different_locations_can_reuse_a_slug(bool update) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, user) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var otherTeam = new Team { Name = "Other", Slug = "other" }; + var template = Template("Template", team.Id); + db.Teams.Add(otherTeam); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + var otherSpace = await SeedSpace(db, otherTeam, "Other location"); + await SeedResource(db, otherTeam, otherSpace, user, "Existing room"); + var controller = CreateController(db); + + if (update) + { + var (resource, config) = await SeedResource(db, team, space, user); + ReadOk(await controller.UpdateResource(team.Slug, resource.Id, + Request(saved: resource, config: config, slug: "existing-room"))).Slug.Should().Be("existing-room"); + } + else + { + ReadCreated(await controller.CreateResource(team.Slug, + Request(space.Id, template.Id, name: "New room", slug: "existing-room"))).Slug.Should().Be("existing-room"); + } + + db.ChangeTracker.Clear(); + (await db.Resources.CountAsync(resource => resource.Slug == "existing-room")).Should().Be(2); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task Different_teams_sharing_a_location_get_a_clear_slug_conflict(bool update, bool isActive) + { + using var db = TestDbContextFactory.CreateInMemory(); + var (team, user) = await SeedTeam(db); + var space = await SeedSpace(db, team); + var otherTeam = new Team { Name = "Other", Slug = "other" }; + var template = Template("Template", team.Id); + db.Teams.Add(otherTeam); + db.ResourceTemplates.Add(template); + await db.SaveChangesAsync(); + await SeedResource(db, otherTeam, space, user, "Existing room", isActive: isActive); + var controller = CreateController(db); + + ActionResult result; + if (update) + { + var (resource, config) = await SeedResource(db, team, space, user); + result = await controller.UpdateResource(team.Slug, resource.Id, + Request(saved: resource, config: config, name: "Changed room", slug: "existing-room")); + db.ChangeTracker.Clear(); + var unchanged = await db.Resources.SingleAsync(value => value.Id == resource.Id); + unchanged.Slug.Should().Be("meeting-room"); + unchanged.Name.Should().Be("Meeting room"); + unchanged.UpdatedAt.Should().Be(SavedAt); + } + else + { + result = await controller.CreateResource(team.Slug, + Request(space.Id, template.Id, name: "New room", slug: "existing-room")); + (await db.Resources.CountAsync()).Should().Be(1); + } + + result.Result.Should().BeOfType().Subject.Value.Should().Be( + "A resource with that slug already exists at this location, including inactive resources. Choose another slug."); + (await db.ResourceConfigs.CountAsync()).Should().Be(update ? 2 : 1); + (await db.Resources.SingleAsync(resource => resource.TeamId == otherTeam.Id)).Slug.Should().Be("existing-room"); + } + [Theory] [InlineData(TeamRole.Viewer, true, "member-iam", true)] [InlineData(TeamRole.Approver, true, "member-iam", true)] @@ -713,9 +964,9 @@ private static ResourceDetailResponse ReadCreated(ActionResult new() + string? formJson = null, string? detailsJson = null, string? slug = null) => new() { - Name = name, Category = saved?.Category ?? "room", Description = saved?.Description, + Name = name, Slug = slug, Category = saved?.Category ?? "room", Description = saved?.Description, Capacity = saved?.Capacity, IsActive = isActive, IsReservable = saved?.IsReservable ?? true, ApprovalMode = saved?.ApprovalMode ?? "manual", FollowTeamCalendar = saved?.FollowTeamCalendar ?? true, PublicAccess = saved == null ? "availability" : saved.PublicAccess, From cda8ecae24e7d73fcba8b32b4e38200c21d782df Mon Sep 17 00:00:00 2001 From: Jason Sylvestre Date: Tue, 27 Oct 2026 14:22:23 -0700 Subject: [PATCH 2/2] Require explicit slugs for spaces and resources, display client version This change removes server-side automatic slug generation for spaces and resources. Clients must now explicitly provide a valid slug during creation and update, simplifying server-side logic and standardizing slug management. Additionally, the client application's version is now displayed in the page footer. --- client/package-lock.json | 4 +- client/package.json | 2 +- client/src/shared/GeometricFooter.tsx | 13 +++- server/Controllers/AdminSpacesController.cs | 29 ++------ .../Models/Resources/SaveResourceRequest.cs | 3 +- server/Models/Spaces/SaveSpaceRequest.cs | 3 +- server/Services/TeamResourceService.cs | 18 +---- .../Controllers/AdminSpacesControllerTests.cs | 72 ++++++++++++------- .../TeamResourcesControllerTests.cs | 66 +++++++++++------ 9 files changed, 118 insertions(+), 92 deletions(-) diff --git a/client/package-lock.json b/client/package-lock.json index 5bdfa51..fb52f84 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1,12 +1,12 @@ { "name": "booking-client", - "version": "0.0.0", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "booking-client", - "version": "0.0.0", + "version": "1.0.0", "dependencies": { "@heroicons/react": "^2.2.0", "@tanstack/react-form": "^1.23.5", diff --git a/client/package.json b/client/package.json index e39e7c9..784b793 100644 --- a/client/package.json +++ b/client/package.json @@ -1,7 +1,7 @@ { "name": "booking-client", "private": true, - "version": "0.0.0", + "version": "1.0.0", "type": "module", "scripts": { "dev": "vite", diff --git a/client/src/shared/GeometricFooter.tsx b/client/src/shared/GeometricFooter.tsx index 44cb069..2f5d885 100644 --- a/client/src/shared/GeometricFooter.tsx +++ b/client/src/shared/GeometricFooter.tsx @@ -1,3 +1,5 @@ +import packageInfo from '../../package.json' with { type: 'json' }; + export function GeometricFooter() { return (