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/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/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 (
-
- © 2026–2027 Regents of the University of California
-
+
+
+ © 2026–2027 Regents of the University of California
+
+
+ Version {packageInfo.version}
+
+
{
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/Controllers/AdminSpacesController.cs b/server/Controllers/AdminSpacesController.cs
index 75c51c8..e53cac4 100644
--- a/server/Controllers/AdminSpacesController.cs
+++ b/server/Controllers/AdminSpacesController.cs
@@ -1,5 +1,4 @@
using System.Data;
-using System.Text;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -59,7 +58,7 @@ public async Task> GetSpace(int id, CancellationToke
public async Task> CreateSpace(
[FromBody] SaveSpaceRequest request, CancellationToken cancellationToken = default)
{
- var error = ValidateRequest(request, isNew: true, out var name, out var slug);
+ var error = ValidateRequest(request, out var name, out var slug);
if (error != null)
{
return BadRequest(error);
@@ -98,7 +97,7 @@ await OfficialReferenceExists(TrimOptional(request.ReferenceNumber), null, cance
public async Task> UpdateSpace(
int id, [FromBody] SaveSpaceRequest request, CancellationToken cancellationToken = default)
{
- var error = ValidateRequest(request, isNew: false, out var name, out _);
+ var error = ValidateRequest(request, out var name, out _);
if (error != null)
{
return BadRequest(error);
@@ -109,7 +108,7 @@ public async Task> UpdateSpace(
{
return NotFound("That space could not be found.");
}
- if (request.Slug != null && request.Slug != space.Slug)
+ if (request.Slug != space.Slug)
{
return BadRequest("A space's slug cannot be changed after it is created.");
}
@@ -331,7 +330,7 @@ private ConflictObjectResult DuplicateConflict(string code)
Extensions = { ["code"] = code },
});
- private static string? ValidateRequest(SaveSpaceRequest request, bool isNew, out string name, out string slug)
+ private static string? ValidateRequest(SaveSpaceRequest request, out string name, out string slug)
{
name = request.Name?.Trim() ?? string.Empty;
slug = request.Slug?.Trim() ?? string.Empty;
@@ -353,26 +352,6 @@ private ConflictObjectResult DuplicateConflict(string code)
{
return "A reference number is required for an official facility.";
}
- if (!isNew)
- {
- return null;
- }
-
- if (request.Slug == null)
- {
- try
- {
- var normalized = Regex.Replace(name.Normalize(NormalizationForm.FormKD), @"[\u0300-\u036f]", string.Empty)
- .ToLowerInvariant();
- slug = Regex.Replace(normalized, "[^a-z0-9]+", "-").Trim('-');
- slug = slug[..Math.Min(slug.Length, 120)].TrimEnd('-');
- }
- catch (ArgumentException)
- {
- return "Enter a valid space name.";
- }
- }
-
if (slug.Length == 0 || slug.Length > 120 ||
!Regex.IsMatch(slug, @"\A[a-z0-9]+(?:-[a-z0-9]+)*\z", RegexOptions.CultureInvariant))
{
diff --git a/server/Models/Resources/SaveResourceRequest.cs b/server/Models/Resources/SaveResourceRequest.cs
index 8c020f0..4e248fe 100644
--- a/server/Models/Resources/SaveResourceRequest.cs
+++ b/server/Models/Resources/SaveResourceRequest.cs
@@ -11,6 +11,10 @@ public sealed class SaveResourceRequest
[StringLength(200)]
public string Name { get; init; } = string.Empty;
+ [Required]
+ [StringLength(120)]
+ public string Slug { get; init; } = string.Empty;
+
[Required]
[StringLength(50)]
public string Category { get; init; } = string.Empty;
diff --git a/server/Models/Spaces/SaveSpaceRequest.cs b/server/Models/Spaces/SaveSpaceRequest.cs
index 4278d5c..55609ac 100644
--- a/server/Models/Spaces/SaveSpaceRequest.cs
+++ b/server/Models/Spaces/SaveSpaceRequest.cs
@@ -10,8 +10,9 @@ public sealed class SaveSpaceRequest
[StringLength(200)]
public string Name { get; init; } = string.Empty;
+ [Required]
[StringLength(120)]
- public string? Slug { get; init; }
+ public string Slug { get; init; } = string.Empty;
public string? Description { get; init; }
diff --git a/server/Services/TeamResourceService.cs b/server/Services/TeamResourceService.cs
index 04ae7c7..477bce1 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,21 @@ 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();
+ 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 +208,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();
+ 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 +273,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 +298,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 +314,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 +326,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 +384,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 (string.IsNullOrWhiteSpace(request.Slug) || !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.";
@@ -525,27 +562,9 @@ private static bool TryText(JsonElement element, string property, out string val
private static string? TrimOptional(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
- 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}";
- }
+ 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/AdminSpacesControllerTests.cs b/tests/server.tests/Controllers/AdminSpacesControllerTests.cs
index e995f6f..bdbbf10 100644
--- a/tests/server.tests/Controllers/AdminSpacesControllerTests.cs
+++ b/tests/server.tests/Controllers/AdminSpacesControllerTests.cs
@@ -1,3 +1,4 @@
+using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Text.Json;
using FluentAssertions;
@@ -74,7 +75,7 @@ public async Task Create_and_reads_include_trimmed_metadata_and_preserve_explici
var result = await controller.CreateSpace(new SaveSpaceRequest
{
- Name = " North Hall ", Description = " A teaching space. ", Address = " 123 Main St ",
+ Name = " North Hall ", Slug = "north-hall", Description = " A teaching space. ", Address = " 123 Main St ",
IsOfficialFacility = true, IsActive = false, ReferenceNumber = " FAC-123 ",
});
@@ -126,7 +127,7 @@ public async Task Official_facilities_require_a_reference_on_create_and_update(s
var controller = new AdminSpacesController(db);
var request = new SaveSpaceRequest
{
- Name = "Official Hall", IsOfficialFacility = true, ReferenceNumber = referenceNumber,
+ Name = "Official Hall", Slug = original.Slug, IsOfficialFacility = true, ReferenceNumber = referenceNumber,
};
(await controller.CreateSpace(request)).Result.Should().BeOfType();
@@ -148,7 +149,7 @@ public async Task Oversized_address_and_reference_are_rejected_on_create_and_upd
var controller = new AdminSpacesController(db);
var request = new SaveSpaceRequest
{
- Name = "Updated Hall", Address = new string('a', addressLength), ReferenceNumber = new string('a', referenceLength),
+ Name = "Updated Hall", Slug = original.Slug, Address = new string('a', addressLength), ReferenceNumber = new string('a', referenceLength),
};
(await controller.CreateSpace(request)).Result.Should().BeOfType();
@@ -162,26 +163,45 @@ public async Task Oversized_address_and_reference_are_rejected_on_create_and_upd
[InlineData(" North Hall ", "north-hall")]
[InlineData("Café & Conference Hall", "cafe-conference-hall")]
[InlineData("Full Width", "full-width")]
- public async Task Create_defaults_an_omitted_slug_from_the_name(string name, string expectedSlug)
+ public async Task Create_uses_the_explicit_slug(string name, string expectedSlug)
{
using var db = TestDbContextFactory.CreateInMemory();
- var result = await new AdminSpacesController(db).CreateSpace(new SaveSpaceRequest { Name = name });
+ var result = await new AdminSpacesController(db).CreateSpace(new SaveSpaceRequest { Name = name, Slug = expectedSlug });
result.Result.Should().BeOfType();
(await db.Spaces.SingleAsync()).Slug.Should().Be(expectedSlug);
}
- [Fact]
- public async Task Generated_slug_respects_its_limit_without_ending_in_a_hyphen()
+ [Theory]
+ [InlineData("{\"name\":\"Updated Hall\"}")]
+ [InlineData("{\"name\":\"Updated Hall\",\"slug\":null}")]
+ [InlineData("{\"name\":\"Updated Hall\",\"slug\":\"\"}")]
+ [InlineData("{\"name\":\"Updated Hall\",\"slug\":\" \"}")]
+ public async Task Create_and_update_require_an_explicit_nonblank_slug(string json)
{
using var db = TestDbContextFactory.CreateInMemory();
- var name = new string('a', 119) + " West Wing";
+ var original = CreateSpace("Original Hall", "original-hall");
+ db.Spaces.Add(original);
+ await db.SaveChangesAsync();
+ var updatedAt = original.UpdatedAt;
+ var controller = new AdminSpacesController(db);
+ var request = JsonSerializer.Deserialize(json,
+ new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
+ var validationResults = new List();
- var result = await new AdminSpacesController(db).CreateSpace(new SaveSpaceRequest { Name = name });
+ Validator.TryValidateObject(request, new ValidationContext(request), validationResults, validateAllProperties: true)
+ .Should().BeFalse();
+ validationResults.Should().Contain(result => result.MemberNames.Contains(nameof(SaveSpaceRequest.Slug)));
+ (await controller.CreateSpace(request)).Result.Should().BeOfType();
+ (await controller.UpdateSpace(original.Id, request)).Result.Should().BeOfType();
- result.Result.Should().BeOfType();
- (await db.Spaces.SingleAsync()).Slug.Should().Be(new string('a', 119));
+ db.ChangeTracker.HasChanges().Should().BeFalse();
+ db.ChangeTracker.Clear();
+ var saved = await db.Spaces.SingleAsync();
+ saved.Name.Should().Be("Original Hall");
+ saved.Slug.Should().Be("original-hall");
+ saved.UpdatedAt.Should().Be(updatedAt);
}
[Theory]
@@ -197,7 +217,7 @@ public async Task Generated_slug_respects_its_limit_without_ending_in_a_hyphen()
[InlineData("Hall", "north_hall")]
[InlineData("Hall", "north/hall")]
[InlineData("Hall", "háll")]
- public async Task Create_and_update_reject_invalid_identity_without_changes(string name, string? slug)
+ public async Task Create_and_update_reject_invalid_identity_without_changes(string name, string slug)
{
using var db = TestDbContextFactory.CreateInMemory();
var original = CreateSpace("Original", "original");
@@ -216,14 +236,14 @@ public async Task Create_and_update_reject_invalid_identity_without_changes(stri
}
[Fact]
- public async Task Create_rejects_a_name_without_an_automatic_slug()
+ public async Task Create_accepts_an_explicit_slug_independent_of_the_name()
{
using var db = TestDbContextFactory.CreateInMemory();
- var result = await new AdminSpacesController(db).CreateSpace(new SaveSpaceRequest { Name = "???" });
+ var result = await new AdminSpacesController(db).CreateSpace(new SaveSpaceRequest { Name = "???", Slug = "custom-location" });
- result.Result.Should().BeOfType();
- (await db.Spaces.AnyAsync()).Should().BeFalse();
+ result.Result.Should().BeOfType();
+ (await db.Spaces.SingleAsync()).Slug.Should().Be("custom-location");
}
[Theory]
@@ -275,7 +295,7 @@ public async Task Update_changes_editable_fields_preserving_slug_timezone_and_cr
var response = ReadOk(await new AdminSpacesController(db).UpdateSpace(original.Id,
new SaveSpaceRequest
{
- Name = " New Hall ", Description = " Updated description ", Address = " Updated address ",
+ Name = " New Hall ", Slug = original.Slug, Description = " Updated description ", Address = " Updated address ",
IsOfficialFacility = false, IsActive = true, ReferenceNumber = " 67890 ",
}));
@@ -344,7 +364,7 @@ public async Task Update_rejects_slug_changes_before_mutating_any_fields(string
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
- public async Task Update_clears_blank_optional_fields_and_preserves_an_omitted_slug(string? value)
+ public async Task Update_clears_blank_optional_fields_with_the_explicit_existing_slug(string? value)
{
using var db = TestDbContextFactory.CreateInMemory();
var space = CreateSpace("Hall", "hall");
@@ -357,7 +377,7 @@ public async Task Update_clears_blank_optional_fields_and_preserves_an_omitted_s
var response = ReadOk(await new AdminSpacesController(db).UpdateSpace(space.Id, new SaveSpaceRequest
{
- Name = "???", Description = value, Address = value, ReferenceNumber = value,
+ Name = "???", Slug = space.Slug, Description = value, Address = value, ReferenceNumber = value,
IsOfficialFacility = false, IsActive = false,
}));
@@ -390,7 +410,7 @@ public async Task Official_reference_conflicts_include_inactive_facilities_and_d
var controller = new AdminSpacesController(db);
var request = new SaveSpaceRequest
{
- Name = "Replacement", IsOfficialFacility = true, ReferenceNumber = " FAC-123 ",
+ Name = "Replacement", Slug = "replacement", IsOfficialFacility = true, ReferenceNumber = " FAC-123 ",
};
var conflict = ReadConflict(await controller.CreateSpace(request));
@@ -399,7 +419,10 @@ public async Task Official_reference_conflicts_include_inactive_facilities_and_d
conflict.Detail.Should().Contain("reference number");
using var json = JsonDocument.Parse(JsonSerializer.Serialize(conflict));
json.RootElement.GetProperty("code").GetString().Should().Be("duplicate_reference_number");
- ReadConflict(await controller.UpdateSpace(original.Id, request)).Extensions["code"]
+ ReadConflict(await controller.UpdateSpace(original.Id, new SaveSpaceRequest
+ {
+ Name = request.Name, Slug = original.Slug, IsOfficialFacility = true, ReferenceNumber = request.ReferenceNumber,
+ })).Extensions["code"]
.Should().Be("duplicate_reference_number");
db.ChangeTracker.HasChanges().Should().BeFalse();
@@ -420,7 +443,7 @@ public async Task Nonofficial_spaces_can_retain_duplicate_references_and_officia
var result = await controller.CreateSpace(new SaveSpaceRequest
{
- Name = "Unofficial Space", ReferenceNumber = " FAC-123 ",
+ Name = "Unofficial Space", Slug = "unofficial-space", ReferenceNumber = " FAC-123 ",
});
var response = result.Result.Should().BeOfType().Subject.Value
.Should().BeOfType().Subject;
@@ -428,7 +451,7 @@ public async Task Nonofficial_spaces_can_retain_duplicate_references_and_officia
response.ReferenceNumber.Should().Be("FAC-123");
ReadOk(await controller.UpdateSpace(official.Id, new SaveSpaceRequest
{
- Name = "Renamed Official Hall", IsOfficialFacility = true, ReferenceNumber = "FAC-123",
+ Name = "Renamed Official Hall", Slug = official.Slug, IsOfficialFacility = true, ReferenceNumber = "FAC-123",
})).ReferenceNumber.Should().Be("FAC-123");
}
@@ -449,7 +472,8 @@ public async Task Concurrent_official_reference_conflict_discards_unsaved_create
var controller = new AdminSpacesController(db);
var request = new SaveSpaceRequest
{
- Name = "Candidate Hall", IsOfficialFacility = true, ReferenceNumber = "FAC-123", IsActive = false,
+ Name = "Candidate Hall", Slug = update ? original.Slug : "candidate-hall",
+ IsOfficialFacility = true, ReferenceNumber = "FAC-123", IsActive = false,
};
var result = update
diff --git a/tests/server.tests/Controllers/TeamResourcesControllerTests.cs b/tests/server.tests/Controllers/TeamResourcesControllerTests.cs
index 98f81b3..ccb176d 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,282 @@ public async Task Editors_and_above_create_a_root_resource_and_published_configu
config.PublishedAt.Should().NotBeNull();
}
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task Missing_or_null_slugs_are_rejected_on_create_and_update(bool omitSlug)
+ {
+ 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);
+ var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
+
+ SaveResourceRequest WithoutSlug(SaveResourceRequest request)
+ {
+ var json = JsonSerializer.SerializeToNode(request, options)!.AsObject();
+ if (omitSlug)
+ {
+ json.Remove("slug");
+ }
+ else
+ {
+ json["slug"] = null;
+ }
+ return json.Deserialize(options)!;
+ }
+
+ (await controller.CreateResource(team.Slug, WithoutSlug(Request(space.Id, template.Id))))
+ .Result.Should().BeOfType().Subject.Value.Should().Be(
+ "Enter a slug of no more than 120 lowercase letters, numbers, and single hyphens between words.");
+ (await db.Resources.AnyAsync()).Should().BeFalse();
+ (await db.ResourceConfigs.AnyAsync()).Should().BeFalse();
+
+ var (resource, config) = await SeedResource(db, team, space, user);
+ (await controller.UpdateResource(team.Slug, resource.Id,
+ WithoutSlug(Request(saved: resource, config: config, name: "Changed name"))))
+ .Result.Should().BeOfType().Subject.Value.Should().Be(
+ "Enter a slug of no more than 120 lowercase letters, numbers, and single hyphens between words.");
+ db.ChangeTracker.Clear();
+ var unchanged = await db.Resources.SingleAsync();
+ unchanged.Slug.Should().Be(resource.Slug);
+ unchanged.Name.Should().Be(resource.Name);
+ unchanged.UpdatedAt.Should().Be(SavedAt);
+ (await db.ResourceConfigs.SingleAsync()).Id.Should().Be(config.Id);
+ }
+
+ [Fact]
+ public async Task Creation_uses_the_explicit_slug_and_accepts_120_characters()
+ {
+ 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: "Meeting room", slug: " selected-room-1 ")))
+ .Slug.Should().Be("selected-room-1");
+ 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_accept_an_explicit_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: "---", 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(" ")]
+ [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
+ {
+ result = await controller.CreateResource(team.Slug,
+ Request(space.Id, template.Id, name: "Existing 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 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)]
@@ -475,7 +751,7 @@ public async Task Updates_require_both_concurrency_values(string missingValue, i
var (resource, config) = await SeedResource(db, team, space, user);
var request = new SaveResourceRequest
{
- Name = "Changed", Category = "room",
+ Name = "Changed", Slug = resource.Slug, Category = "room",
UpdatedAt = missingValue == "timestamp" ? null : resource.UpdatedAt,
ExpectedConfigId = missingValue == "configuration" ? null : config.Id,
};
@@ -584,7 +860,7 @@ public async Task Renaming_a_child_preserves_its_slug_hierarchy_and_inherited_pu
var originalSlug = child.Slug;
var request = new SaveResourceRequest
{
- Name = "Renamed child", Category = child.Category, Capacity = child.Capacity,
+ Name = "Renamed child", Slug = child.Slug, Category = child.Category, Capacity = child.Capacity,
PublicAccess = "details", UpdatedAt = child.UpdatedAt, ExpectedConfigId = config.Id,
};
@@ -713,9 +989,10 @@ 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 ?? saved?.Slug ?? "meeting-room",
+ 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,