From 65f9c4eea66b91cbe5512f6d12c215d252998c9e Mon Sep 17 00:00:00 2001 From: SmithR-IS Date: Fri, 20 Nov 2026 11:47:59 +0000 Subject: [PATCH 1/2] Add company code autocomplete with organisation suggestions --- backend/openapi/UKPS.Api.json | 185 +++++++++ .../RecordForms/Dtos/RecordPageDto.cs | 6 + .../Application/RecordForms/FormVersions.cs | 2 +- .../RecordForms/RecordFormQueryService.cs | 1 + .../Records/Dtos/CompanyCodeSuggestionsDto.cs | 14 + .../Dtos/GetCompanyCodeSuggestionsQueryDto.cs | 22 + .../src/Application/Records/IRecordService.cs | 18 + .../src/Application/Records/RecordService.cs | 56 +++ .../RecordProductDetail.cs | 1 + .../FormAnnotations/FormFieldAttribute.cs | 4 +- .../WebApi/Controllers/RecordController.cs | 52 +++ .../RecordForms/MedicineFormModelTests.cs | 4 +- .../Records/RecordServiceCompanyCodeTests.cs | 228 +++++++++++ .../Controllers/RecordControllerTests.cs | 101 +++++ .../Controllers/RecordFormControllerTests.cs | 1 + .../(examples)/autocomplete/Examples.tsx | 97 +++++ .../(examples)/autocomplete/page.tsx | 19 + .../app/portal/components/_data/components.ts | 5 + .../create/CreateMedicineRecordForm.test.tsx | 35 +- .../create/CreateMedicineRecordForm.tsx | 12 +- .../client/generated/@faker-js/faker.gen.ts | 35 +- frontend/src/client/generated/index.ts | 4 +- frontend/src/client/generated/sdk.gen.ts | 8 +- frontend/src/client/generated/types.gen.ts | 73 ++++ .../Autocomplete/Autocomplete.module.scss | 85 ++++ .../Autocomplete/Autocomplete.test.tsx | 382 ++++++++++++++++++ .../components/Autocomplete/Autocomplete.tsx | 336 +++++++++++++++ .../components/DynamicForm/FormPage.test.tsx | 99 ++++- .../src/components/DynamicForm/FormPage.tsx | 6 +- .../DynamicForm/FormPageContext.tsx | 21 + .../DynamicForm/questions/TextQuestion.tsx | 44 +- .../src/lib/dynamic-form/suggestionSources.ts | 28 ++ .../src/lib/form/companyCodeSuggestions.ts | 20 + 33 files changed, 1973 insertions(+), 31 deletions(-) create mode 100644 backend/src/Application/Records/Dtos/CompanyCodeSuggestionsDto.cs create mode 100644 backend/src/Application/Records/Dtos/GetCompanyCodeSuggestionsQueryDto.cs create mode 100644 backend/tests/Application/Records/RecordServiceCompanyCodeTests.cs create mode 100644 frontend/src/app/portal/components/(examples)/autocomplete/Examples.tsx create mode 100644 frontend/src/app/portal/components/(examples)/autocomplete/page.tsx create mode 100644 frontend/src/components/Autocomplete/Autocomplete.module.scss create mode 100644 frontend/src/components/Autocomplete/Autocomplete.test.tsx create mode 100644 frontend/src/components/Autocomplete/Autocomplete.tsx create mode 100644 frontend/src/components/DynamicForm/FormPageContext.tsx create mode 100644 frontend/src/lib/dynamic-form/suggestionSources.ts create mode 100644 frontend/src/lib/form/companyCodeSuggestions.ts diff --git a/backend/openapi/UKPS.Api.json b/backend/openapi/UKPS.Api.json index 7322933e6..c37fcf473 100644 --- a/backend/openapi/UKPS.Api.json +++ b/backend/openapi/UKPS.Api.json @@ -2596,6 +2596,169 @@ } } }, + "/records/organisations/{organisationId}/company-codes": { + "get": { + "tags": [ + "Record" + ], + "summary": "Retrieves the company codes already used on an organisation's records that contain the\nsearch text, for suggesting while a user types a company code.", + "operationId": "GetOrganisationCompanyCodes", + "parameters": [ + { + "name": "organisationId", + "in": "path", + "description": "The unique identifier of the organisation.", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "Search", + "in": "query", + "description": "Gets or initialises the text the company codes must contain, ignoring case. A blank search\nreturns no suggestions.", + "schema": { + "maxLength": 200, + "type": "string" + } + }, + { + "name": "Limit", + "in": "query", + "description": "Gets or initialises the maximum number of suggestions to return.", + "schema": { + "maximum": 20, + "minimum": 1, + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "Returns the matching company codes.", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/CompanyCodeSuggestionsDto" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CompanyCodeSuggestionsDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CompanyCodeSuggestionsDto" + } + } + } + }, + "400": { + "description": "The query parameters are invalid.", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + } + }, + "403": { + "description": "The caller is not authorised to view the organisation's records.", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "The specified organisation does not exist.", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/AuthenticationProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthenticationProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/AuthenticationProblemDetails" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/AuthenticationProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthenticationProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/AuthenticationProblemDetails" + } + } + } + } + } + } + }, "/records/{id}/overview": { "get": { "tags": [ @@ -6026,6 +6189,22 @@ }, "description": "Contains why a record is being put on hold, resumed or archived." }, + "CompanyCodeSuggestionsDto": { + "required": [ + "items" + ], + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Gets the distinct matching company codes, those starting with the search first, then\nalphabetically." + } + }, + "description": "The company codes already used on an organisation's records, offered as suggestions while a\nuser types a company code." + }, "ConditionKind": { "enum": [ "AnswerIn" @@ -7088,6 +7267,7 @@ "required": [ "formVersion", "recordId", + "organisationId", "section", "task", "page", @@ -7108,6 +7288,11 @@ "description": "The record the page belongs to.", "format": "int32" }, + "organisationId": { + "type": "integer", + "description": "The organisation that owns the record; used to look up suggestions such as the\norganisation's existing company codes.", + "format": "int32" + }, "section": { "description": "The section the page belongs to.", "$ref": "#/components/schemas/RecordPageSectionDto" diff --git a/backend/src/Application/RecordForms/Dtos/RecordPageDto.cs b/backend/src/Application/RecordForms/Dtos/RecordPageDto.cs index 71b2f2967..3baffc0cc 100644 --- a/backend/src/Application/RecordForms/Dtos/RecordPageDto.cs +++ b/backend/src/Application/RecordForms/Dtos/RecordPageDto.cs @@ -11,6 +11,12 @@ public sealed record RecordPageDto /// The record the page belongs to. public required int RecordId { get; init; } + /// + /// The organisation that owns the record; used to look up suggestions such as the + /// organisation's existing company codes. + /// + public required int OrganisationId { get; init; } + /// The section the page belongs to. public required RecordPageSectionDto Section { get; init; } diff --git a/backend/src/Application/RecordForms/FormVersions.cs b/backend/src/Application/RecordForms/FormVersions.cs index e460f7067..77ef03ecc 100644 --- a/backend/src/Application/RecordForms/FormVersions.cs +++ b/backend/src/Application/RecordForms/FormVersions.cs @@ -9,7 +9,7 @@ namespace UKPS.Api.Application.RecordForms; /// internal static class FormVersions { - public const string Medicine = "2026.11.19.3"; + public const string Medicine = "2026.11.20.1"; public static string? For(RecordType recordType) => recordType switch diff --git a/backend/src/Application/RecordForms/RecordFormQueryService.cs b/backend/src/Application/RecordForms/RecordFormQueryService.cs index 3fa9126a4..f45446cf2 100644 --- a/backend/src/Application/RecordForms/RecordFormQueryService.cs +++ b/backend/src/Application/RecordForms/RecordFormQueryService.cs @@ -58,6 +58,7 @@ Dictionary> options { FormVersion = model.Version, RecordId = loaded.Record.Id, + OrganisationId = loaded.Record.OrganisationId, Section = new RecordPageSectionDto { Id = page.SectionId, Title = page.SectionTitle }, Task = new RecordPageTaskDto { Id = page.TaskId, Title = page.TaskTitle }, Page = new RecordPagePageDto diff --git a/backend/src/Application/Records/Dtos/CompanyCodeSuggestionsDto.cs b/backend/src/Application/Records/Dtos/CompanyCodeSuggestionsDto.cs new file mode 100644 index 000000000..b534f53b1 --- /dev/null +++ b/backend/src/Application/Records/Dtos/CompanyCodeSuggestionsDto.cs @@ -0,0 +1,14 @@ +namespace UKPS.Api.Application.Records.Dtos; + +/// +/// The company codes already used on an organisation's records, offered as suggestions while a +/// user types a company code. +/// +public sealed record CompanyCodeSuggestionsDto +{ + /// + /// Gets the distinct matching company codes, those starting with the search first, then + /// alphabetically. + /// + public required IReadOnlyList Items { get; init; } +} diff --git a/backend/src/Application/Records/Dtos/GetCompanyCodeSuggestionsQueryDto.cs b/backend/src/Application/Records/Dtos/GetCompanyCodeSuggestionsQueryDto.cs new file mode 100644 index 000000000..f79d2291f --- /dev/null +++ b/backend/src/Application/Records/Dtos/GetCompanyCodeSuggestionsQueryDto.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; + +namespace UKPS.Api.Application.Records.Dtos; + +/// +/// Specifies the search parameters for company code suggestions. +/// +public sealed record GetCompanyCodeSuggestionsQueryDto +{ + /// + /// Gets or initialises the text the company codes must contain, ignoring case. A blank search + /// returns no suggestions. + /// + [MaxLength(200, ErrorMessage = "Search must be 200 characters or fewer.")] + public string? Search { get; init; } + + /// + /// Gets or initialises the maximum number of suggestions to return. + /// + [Range(1, 20, ErrorMessage = "Limit must be between 1 and 20.")] + public int Limit { get; init; } = 10; +} diff --git a/backend/src/Application/Records/IRecordService.cs b/backend/src/Application/Records/IRecordService.cs index 343003107..d1e56c5b1 100644 --- a/backend/src/Application/Records/IRecordService.cs +++ b/backend/src/Application/Records/IRecordService.cs @@ -26,6 +26,24 @@ Task, GetRecordsError>> GetOrgani CancellationToken cancellationToken ); + /// + /// Retrieves the distinct company codes on the latest revisions of an organisation's records + /// that contain the search text, ignoring case, for suggesting while a user types a company + /// code. Discarded records are excluded. + /// + /// The unique identifier of the organisation. + /// The search text and the maximum number of suggestions. + /// A token to monitor for cancellation requests. + /// + /// The matching company codes, or a when the organisation does + /// not exist or the caller cannot read its records. + /// + Task> GetOrganisationCompanyCodes( + int organisationId, + GetCompanyCodeSuggestionsQueryDto query, + CancellationToken cancellationToken + ); + /// /// Discards a record that has never been submitted, setting the record and its draft /// revision to discarded. diff --git a/backend/src/Application/Records/RecordService.cs b/backend/src/Application/Records/RecordService.cs index 30d8539f3..d3ebd263c 100644 --- a/backend/src/Application/Records/RecordService.cs +++ b/backend/src/Application/Records/RecordService.cs @@ -97,6 +97,62 @@ CancellationToken cancellationToken ); } + public async Task< + Result + > GetOrganisationCompanyCodes( + int organisationId, + GetCompanyCodeSuggestionsQueryDto query, + CancellationToken cancellationToken + ) + { + GetRecordsError? organisationError = await ValidateOrganisationAsync( + organisationId, + Operation.Read, + cancellationToken + ); + + if (organisationError is not null) + { + return Result.Err(organisationError); + } + + string search = query.Search?.Trim() ?? string.Empty; + + if (search.Length == 0) + { + return Result.Ok( + new CompanyCodeSuggestionsDto { Items = [] } + ); + } + + string pattern = $"%{Helpers.EscapeLikePattern(search)}%"; + + // Discarded records are hidden by the records query filter. An organisation has one code + // per record, so the matches are few enough to rank in memory. + List matches = await JoinProductDetails(GetBaseRecordProjection()) + .Where(x => + x.OrganisationId == organisationId + && EF.Functions.ILike(x.CompanyCode, pattern, "\\") + ) + .Select(x => x.CompanyCode) + .Distinct() + .ToListAsync(cancellationToken); + + string[] items = matches + .Select(code => code.Trim()) + .Where(code => code.Length > 0) + .DistinctBy(code => code, StringComparer.OrdinalIgnoreCase) + .OrderBy(code => code.StartsWith(search, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .ThenBy(code => code, StringComparer.OrdinalIgnoreCase) + .ThenBy(code => code, StringComparer.Ordinal) + .Take(query.Limit) + .ToArray(); + + return Result.Ok( + new CompanyCodeSuggestionsDto { Items = items } + ); + } + private async Task ValidateOrganisationAsync( int organisationId, Operation operation, diff --git a/backend/src/Persistence/Entities/SharedRevisionContent/RecordProductDetail.cs b/backend/src/Persistence/Entities/SharedRevisionContent/RecordProductDetail.cs index a461456a7..8f83b1d56 100644 --- a/backend/src/Persistence/Entities/SharedRevisionContent/RecordProductDetail.cs +++ b/backend/src/Persistence/Entities/SharedRevisionContent/RecordProductDetail.cs @@ -29,6 +29,7 @@ internal sealed class RecordProductDetail "Company code", FormControl.Text, Hint = "Enter the primary internal code or working name your company uses for this product seeking market access.", + Display = "autocomplete:company-codes", Order = 10 )] [FormRequired("Enter company code")] diff --git a/backend/src/Persistence/FormAnnotations/FormFieldAttribute.cs b/backend/src/Persistence/FormAnnotations/FormFieldAttribute.cs index 2266672ac..20e3fa5b7 100644 --- a/backend/src/Persistence/FormAnnotations/FormFieldAttribute.cs +++ b/backend/src/Persistence/FormAnnotations/FormFieldAttribute.cs @@ -35,7 +35,9 @@ internal sealed class FormFieldAttribute(string id, string label, FormControl co /// /// A rendering hint for the frontend, for example combobox. It does not change - /// validation, and the frontend ignores hints it does not know. + /// validation, and the frontend ignores hints it does not know. A text field suggests values + /// as the user types with autocomplete:<source>, where the source names where the + /// suggestions come from, for example autocomplete:company-codes. /// public string? Display { get; set; } diff --git a/backend/src/WebApi/Controllers/RecordController.cs b/backend/src/WebApi/Controllers/RecordController.cs index fe0ab580c..8d3c2d6a9 100644 --- a/backend/src/WebApi/Controllers/RecordController.cs +++ b/backend/src/WebApi/Controllers/RecordController.cs @@ -81,6 +81,58 @@ CancellationToken cancellationToken ); } + /// + /// Retrieves the company codes already used on an organisation's records that contain the + /// search text, for suggesting while a user types a company code. + /// + /// The unique identifier of the organisation. + /// The search text and the maximum number of suggestions. + /// A token to monitor for cancellation requests. + /// The matching company codes. + /// Returns the matching company codes. + /// The query parameters are invalid. + /// The caller is not authorised to view the organisation's records. + /// The specified organisation does not exist. + [HttpGet( + "organisations/{organisationId:int}/company-codes", + Name = nameof(GetOrganisationCompanyCodes) + )] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task> GetOrganisationCompanyCodes( + [FromRoute] int organisationId, + [FromQuery] GetCompanyCodeSuggestionsQueryDto query, + CancellationToken cancellationToken + ) + { + var result = await recordService.GetOrganisationCompanyCodes( + organisationId, + query, + cancellationToken + ); + + return result.Match>( + items => Ok(items), + error => + error switch + { + GetRecordsError.OrganisationNotFound => Problem( + statusCode: StatusCodes.Status404NotFound, + title: "Not Found", + detail: "Organisation not found." + ), + GetRecordsError.NotAllowed => Problem( + statusCode: StatusCodes.Status403Forbidden, + title: "Forbidden", + detail: "You are not authorised to view records." + ), + _ => throw new UnreachableException("Unhandled GetRecordsError variant."), + } + ); + } + /// /// Retrieves a record's status, permitted actions and identifying details, whatever its /// status, without its answers. diff --git a/backend/tests/Application/RecordForms/MedicineFormModelTests.cs b/backend/tests/Application/RecordForms/MedicineFormModelTests.cs index b6f10fd2c..ae7795296 100644 --- a/backend/tests/Application/RecordForms/MedicineFormModelTests.cs +++ b/backend/tests/Application/RecordForms/MedicineFormModelTests.cs @@ -15,9 +15,9 @@ namespace UKPS.Api.Tests.Application.RecordForms; public class MedicineFormModelTests { // Bump FormVersions.Medicine whenever this changes, then update both values. - private const string ExpectedVersion = "2026.11.19.3"; + private const string ExpectedVersion = "2026.11.20.1"; private const string ExpectedFingerprint = - "3fb0b6e0254be0dee88764755ec3b4225d82650e1c5ee81771534e99b5d68576"; + "ce86733b124a99fcf825caf45f6af84a50e3587c5ea27607628db6112e458ed4"; private static readonly OptionProviderRegistry _options = OptionProviderRegistry.CreateDefault(); diff --git a/backend/tests/Application/Records/RecordServiceCompanyCodeTests.cs b/backend/tests/Application/Records/RecordServiceCompanyCodeTests.cs new file mode 100644 index 000000000..daa368c1c --- /dev/null +++ b/backend/tests/Application/Records/RecordServiceCompanyCodeTests.cs @@ -0,0 +1,228 @@ +using Shouldly; +using UKPS.Api.Application.Records; +using UKPS.Api.Application.Records.Dtos; +using UKPS.Api.Application.Records.Errors; +using UKPS.Api.Persistence.Data.Fakers; +using UKPS.Api.Persistence.Entities.RecordWorkflow; +using UKPS.Api.Persistence.Entities.SharedRevisionContent; +using UKPS.Api.Persistence.Enums; +using UKPS.Api.Tests.Utilities.AssertionHelpers; +using UKPS.Api.Tests.Utilities.Fixtures; +using UKPS.Api.Tests.Utilities.Harnesses; +using CompanyCodesResult = UKPS.Api.Application.Common.Result< + UKPS.Api.Application.Records.Dtos.CompanyCodeSuggestionsDto, + UKPS.Api.Application.Records.Errors.GetRecordsError +>; +using Record = UKPS.Api.Persistence.Entities.RecordWorkflow.Record; + +namespace UKPS.Api.Tests.Application.Records; + +[Collection(DatabaseCollection.Name)] +public class RecordServiceCompanyCodeTests(PostgresFixture fixture) : DatabaseTestBase(fixture) +{ + private IServiceTestHarness _harness = null!; + private IRecordService Service => _harness.Service; + private int _organisationId; + private int _otherOrganisationId; + + public override async ValueTask InitializeAsync() + { + await base.InitializeAsync(); + + var organisations = ( + await AddEntities( + new OrganisationFaker().Generate(2), + TestContext.Current.CancellationToken + ) + ).ToArray(); + _organisationId = organisations[0].Id; + _otherOrganisationId = organisations[1].Id; + + _harness = new ServiceTestHarness(Context).UpdateCurrentUser(x => + x with + { + UserRole = UserRole.Standard, + OrganisationId = _organisationId, + } + ); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_ReturnsCodesContainingSearch_IgnoringCase() + { + await AddRecords(_organisationId, "ABC-123", "xabc-9", "DEF-456"); + + CompanyCodeSuggestionsDto dto = (await Search("abc")).ShouldBeSuccess(); + + dto.Items.ShouldBe(["ABC-123", "xabc-9"]); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_ListsCodesStartingWithSearchFirst_ThenAlphabetically() + { + await AddRecords(_organisationId, "ZZ-AB", "AB-2", "c-ab", "ab-1"); + + CompanyCodeSuggestionsDto dto = (await Search("ab")).ShouldBeSuccess(); + + dto.Items.ShouldBe(["ab-1", "AB-2", "c-ab", "ZZ-AB"]); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_RemovesDuplicates_IgnoringCaseAndSpaces() + { + await AddRecords(_organisationId, "ABC-123", "abc-123", " ABC-123 "); + + CompanyCodeSuggestionsDto dto = (await Search("abc")).ShouldBeSuccess(); + + dto.Items.ShouldHaveSingleItem().ToUpperInvariant().ShouldBe("ABC-123"); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_ExcludesOtherOrganisationsAndDiscardedRecords() + { + await AddRecords(_organisationId, "ABC-1"); + await AddRecords(_otherOrganisationId, "ABC-2"); + await AddRecords(_organisationId, RecordStatus.Discarded, "ABC-3"); + + CompanyCodeSuggestionsDto dto = (await Search("abc")).ShouldBeSuccess(); + + dto.Items.ShouldBe(["ABC-1"]); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_UsesLatestRevisionCode() + { + Record record = await AddRecord(_organisationId, RecordStatus.Unpublished, "ABC-OLD"); + await AddRevision(record, "ABC-NEW", new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc)); + + CompanyCodeSuggestionsDto dto = (await Search("abc")).ShouldBeSuccess(); + + dto.Items.ShouldBe(["ABC-NEW"]); + } + + [Theory] + [InlineData("%")] + [InlineData("_")] + [InlineData("\\")] + public async Task GetOrganisationCompanyCodes_TreatsLikeWildcardsAsText(string search) + { + await AddRecords(_organisationId, "ABC-123", $"AB{search}C"); + + CompanyCodeSuggestionsDto dto = (await Search(search)).ShouldBeSuccess(); + + dto.Items.ShouldBe([$"AB{search}C"]); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetOrganisationCompanyCodes_ReturnsNothing_WhenSearchIsBlank(string? search) + { + await AddRecords(_organisationId, "ABC-123"); + + CompanyCodeSuggestionsDto dto = (await Search(search)).ShouldBeSuccess(); + + dto.Items.ShouldBeEmpty(); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_ReturnsAtMostLimitCodes() + { + await AddRecords(_organisationId, "A-1", "A-2", "A-3", "A-4"); + + CompanyCodeSuggestionsDto dto = (await Search("a-", limit: 2)).ShouldBeSuccess(); + + dto.Items.ShouldBe(["A-1", "A-2"]); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_ReturnsNotAllowed_ForAnotherOrganisation() + { + await AddRecords(_otherOrganisationId, "ABC-1"); + + CompanyCodesResult result = await Service.GetOrganisationCompanyCodes( + _otherOrganisationId, + new GetCompanyCodeSuggestionsQueryDto { Search = "abc" }, + TestContext.Current.CancellationToken + ); + + result.ShouldBeError(); + result.Error.ShouldBeOfType(); + } + + [Fact] + public async Task GetOrganisationCompanyCodes_ReturnsOrganisationNotFound_WhenOrganisationDoesNotExist() + { + const int missingOrganisationId = int.MaxValue; + _harness.UpdateCurrentUser(x => x with { OrganisationId = missingOrganisationId }); + + CompanyCodesResult result = await Service.GetOrganisationCompanyCodes( + missingOrganisationId, + new GetCompanyCodeSuggestionsQueryDto { Search = "abc" }, + TestContext.Current.CancellationToken + ); + + result.ShouldBeError(); + result.Error.ShouldBeOfType(); + } + + private Task Search(string? search, int limit = 10) => + Service.GetOrganisationCompanyCodes( + _organisationId, + new GetCompanyCodeSuggestionsQueryDto { Search = search, Limit = limit }, + TestContext.Current.CancellationToken + ); + + private Task AddRecords(int organisationId, params string[] companyCodes) => + AddRecords(organisationId, RecordStatus.Unpublished, companyCodes); + + private async Task AddRecords( + int organisationId, + RecordStatus status, + params string[] companyCodes + ) + { + foreach (string companyCode in companyCodes) + { + await AddRecord(organisationId, status, companyCode); + } + } + + private async Task AddRecord( + int organisationId, + RecordStatus status, + string companyCode + ) + { + Record record = new RecordFaker() + .RuleFor(x => x.OrganisationId, organisationId) + .RuleFor(x => x.RecordType, RecordType.Medicine) + .RuleFor(x => x.RecordStatus, status) + .RuleFor(x => x.CreatedByUser, _ => new UserFaker().Generate()) + .Generate(); + + await AddRevision(record, companyCode, new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + return record; + } + + private async Task AddRevision(Record record, string companyCode, DateTime createdAt) + { + // A saved record is linked by ID, so it is not inserted again. + RecordRevision revision = new RecordRevisionFaker() + .RuleFor(x => x.Record, _ => record.Id == 0 ? record : null) + .RuleFor(x => x.RecordId, _ => record.Id) + .RuleFor(x => x.WorkflowStatus, WorkflowStatus.Draft) + .RuleFor(x => x.CreatedAt, createdAt) + .RuleFor(x => x.CreatedByUser, _ => new UserFaker().Generate()) + .Generate(); + + RecordProductDetail detail = new RecordProductDetailFaker(RecordType.Medicine) + .RuleFor(x => x.Revision, revision) + .RuleFor(x => x.CompanyCode, companyCode) + .Generate(); + + await AddEntities([detail], TestContext.Current.CancellationToken); + Context.ChangeTracker.Clear(); + } +} diff --git a/backend/tests/WebApi/Controllers/RecordControllerTests.cs b/backend/tests/WebApi/Controllers/RecordControllerTests.cs index 1546e17de..2cde1d85e 100644 --- a/backend/tests/WebApi/Controllers/RecordControllerTests.cs +++ b/backend/tests/WebApi/Controllers/RecordControllerTests.cs @@ -21,6 +21,10 @@ using UKPS.Api.Tests.Utilities.Fixtures; using UKPS.Api.WebApi; using UKPS.Api.WebApi.InternalServices.Authentication; +using CompanyCodesResult = UKPS.Api.Application.Common.Result< + UKPS.Api.Application.Records.Dtos.CompanyCodeSuggestionsDto, + UKPS.Api.Application.Records.Errors.GetRecordsError +>; using CreateRecordResult = UKPS.Api.Application.Common.Result< UKPS.Api.Application.Records.Dtos.CreateRecordDto, UKPS.Api.Application.Records.Errors.CreateRecordError @@ -33,6 +37,8 @@ public class RecordControllerTests : IClassFixture( + TestJsonOptions.Default, + TestContext.Current.CancellationToken + ); + content.ShouldNotBeNull(); + content.Items.ShouldBe(expected.Items); + } + + [Fact] + public async Task GetCompanyCodes_PassesRouteAndQueryValuesToService() + { + SetUpCompanyCodes(CompanyCodesResult.Ok(new CompanyCodeSuggestionsDto { Items = [] })); + + await GetCompanyCodes("search=ab%25c&limit=5"); + + await _mockRecordService + .Received(1) + .GetOrganisationCompanyCodes( + OrganisationId, + Arg.Is(x => x.Search == "ab%c" && x.Limit == 5), + Arg.Any() + ); + } + + [Fact] + public async Task GetCompanyCodes_ReturnsNotFound_WhenOrganisationNotFound() + { + SetUpCompanyCodes( + CompanyCodesResult.Err(new GetRecordsError.OrganisationNotFound(OrganisationId)) + ); + + var response = await GetCompanyCodes("search=abc"); + + response.StatusCode.ShouldBe(HttpStatusCode.NotFound); + } + + [Fact] + public async Task GetCompanyCodes_ReturnsForbidden_WhenNotAllowed() + { + SetUpCompanyCodes(CompanyCodesResult.Err(new GetRecordsError.NotAllowed(OrganisationId))); + + var response = await GetCompanyCodes("search=abc"); + + response.StatusCode.ShouldBe(HttpStatusCode.Forbidden); + } + + [Theory] + [InlineData("limit=0")] + [InlineData("limit=21")] + [InlineData("limit=-1")] + public async Task GetCompanyCodes_ReturnsBadRequest_WhenLimitIsOutsideAllowedRange(string limit) + { + var response = await GetCompanyCodes($"search=abc&{limit}"); + + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + await _mockRecordService + .DidNotReceiveWithAnyArgs() + .GetOrganisationCompanyCodes(default, default!, TestContext.Current.CancellationToken); + } + + [Fact] + public async Task GetCompanyCodes_ReturnsBadRequest_WhenSearchIsTooLong() + { + var response = await GetCompanyCodes($"search={new string('a', 201)}"); + + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + await _mockRecordService + .DidNotReceiveWithAnyArgs() + .GetOrganisationCompanyCodes(default, default!, TestContext.Current.CancellationToken); + } + + private Task GetCompanyCodes(string query) => + _client.GetAsync( + new Uri($"{_companyCodesUrl}?{query}", UriKind.Relative), + TestContext.Current.CancellationToken + ); + + private void SetUpCompanyCodes(CompanyCodesResult result) => + _mockRecordService + .GetOrganisationCompanyCodes( + Arg.Any(), + Arg.Any(), + Arg.Any() + ) + .Returns(result); + [Fact] public async Task CreateRecord_ShouldPassProvidedValuesToTheService() { diff --git a/backend/tests/WebApi/Controllers/RecordFormControllerTests.cs b/backend/tests/WebApi/Controllers/RecordFormControllerTests.cs index deaaebb77..5022fc209 100644 --- a/backend/tests/WebApi/Controllers/RecordFormControllerTests.cs +++ b/backend/tests/WebApi/Controllers/RecordFormControllerTests.cs @@ -260,6 +260,7 @@ private static RecordPageDto CreatePage() => { FormVersion = "2026.10.4", RecordId = 5, + OrganisationId = 3, Section = new RecordPageSectionDto { Id = "indication-details", diff --git a/frontend/src/app/portal/components/(examples)/autocomplete/Examples.tsx b/frontend/src/app/portal/components/(examples)/autocomplete/Examples.tsx new file mode 100644 index 000000000..b626ce2d3 --- /dev/null +++ b/frontend/src/app/portal/components/(examples)/autocomplete/Examples.tsx @@ -0,0 +1,97 @@ +'use client' + +import { useState } from 'react' + +import { Autocomplete } from '@/components/Autocomplete/Autocomplete' +import type { AutocompleteProps, GetSuggestions } from '@/components/Autocomplete/Autocomplete' + +import { Example } from '../../_components/Example' + +const companyCodes = [ + 'ABC-123', + 'ABC-123-XR', + 'AZD1222', + 'BNT162b2', + 'GS-7977', + 'LY3298176', + 'mRNA-1273', + 'MK-3475', + 'NVX-CoV2373', + 'V116', +] + +/** Stands in for a request to the server, matching anywhere in the code, ignoring case. */ +const getCompanyCodes: GetSuggestions = async (query) => { + const lowered = query.toLowerCase() + return companyCodes + .filter((code) => code.toLowerCase().includes(lowered)) + .sort( + (a, b) => + Number(!a.toLowerCase().startsWith(lowered)) - + Number(!b.toLowerCase().startsWith(lowered)) || a.localeCompare(b), + ) +} + +const noSuggestions: GetSuggestions = async () => [] + +type ExampleAutocompleteProps = Omit & { + getSuggestions?: GetSuggestions + initialValue?: string +} + +function ExampleAutocomplete({ + getSuggestions = getCompanyCodes, + initialValue = '', + ...props +}: ExampleAutocompleteProps) { + const [value, setValue] = useState(initialValue) + return ( + + ) +} + +export function Examples() { + return ( + <> + +

Type “abc”, “mk” or “v” to see suggestions.

+ +
+ + + + + + + +

Any value can be entered when nothing matches.

+ +
+ + + + + ) +} diff --git a/frontend/src/app/portal/components/(examples)/autocomplete/page.tsx b/frontend/src/app/portal/components/(examples)/autocomplete/page.tsx new file mode 100644 index 000000000..6ac3f0b75 --- /dev/null +++ b/frontend/src/app/portal/components/(examples)/autocomplete/page.tsx @@ -0,0 +1,19 @@ +import { ComponentPage } from '../../_components/ComponentPage' +import { getComponentDefinition } from '../../_data/components' + +import { Examples } from './Examples' + +const component = getComponentDefinition('autocomplete') + +export const metadata = { + description: component.description, + title: component.label, +} + +export default function AutocompletePage() { + return ( + + + + ) +} diff --git a/frontend/src/app/portal/components/_data/components.ts b/frontend/src/app/portal/components/_data/components.ts index 1a22a1e26..8d2b608b4 100644 --- a/frontend/src/app/portal/components/_data/components.ts +++ b/frontend/src/app/portal/components/_data/components.ts @@ -25,6 +25,11 @@ export const componentDefinitions = [ label: 'Alphabet', slug: 'alphabet', }, + { + description: 'Suggest matching values as users type, while still accepting any value.', + label: 'Autocomplete', + slug: 'autocomplete', + }, { description: 'Help users go back to the previous page in a multi-page transaction.', label: 'Back link', diff --git a/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.test.tsx b/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.test.tsx index 09b645556..edb6136a2 100644 --- a/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.test.tsx +++ b/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.test.tsx @@ -9,6 +9,7 @@ import CreateMedicineRecordForm from './CreateMedicineRecordForm' const mocks = vi.hoisted(() => ({ push: vi.fn(), createRecord: vi.fn(), + getOrganisationCompanyCodes: vi.fn(), })) vi.mock('next/navigation', () => ({ @@ -19,7 +20,11 @@ vi.mock('next/navigation', () => ({ vi.mock('@/client/generated', async (importOriginal) => { const original = await importOriginal() - return { ...original, createRecord: mocks.createRecord } + return { + ...original, + createRecord: mocks.createRecord, + getOrganisationCompanyCodes: mocks.getOrganisationCompanyCodes, + } }) const renderComponent = (organisationId = 1) => { @@ -73,6 +78,7 @@ const clickSubmitButton = () => { } beforeEach(() => { + mocks.getOrganisationCompanyCodes.mockResolvedValue({ data: { items: [] } }) mocks.createRecord.mockResolvedValue({ error: undefined, response: { ok: true }, @@ -92,10 +98,10 @@ describe('CreateMedicineRecordForm', () => { expect(screen.getByRole('button', { name: 'Save and continue' })).toBeDefined() }) - it('renders the default company code field', () => { + it('renders the company code field as a type-ahead', () => { renderComponent() - expect(screen.getByLabelText('Company code')).toBeDefined() + expect(screen.getByRole('combobox', { name: 'Company code' })).toBeDefined() }) it('renders the default generic name field', () => { @@ -386,6 +392,29 @@ describe('CreateMedicineRecordForm', () => { }) }) + it("sends a company code chosen from the organisation's suggestions", async () => { + mocks.getOrganisationCompanyCodes.mockResolvedValue({ data: { items: ['CC1-ALPHA'] } }) + renderComponent(123) + + fillInForm(validFormValues) + fireEvent.click(await screen.findByRole('option', { name: 'CC1-ALPHA' })) + clickSubmitButton() + + await waitFor(() => { + expect(mocks.createRecord).toHaveBeenCalled() + }) + + expect(mocks.getOrganisationCompanyCodes).toHaveBeenCalledWith( + expect.objectContaining({ + path: { organisationId: 123 }, + query: expect.objectContaining({ Search: 'cc1' }), + }), + ) + expect(mocks.createRecord).toHaveBeenCalledWith({ + body: expect.objectContaining({ companyCode: 'CC1-ALPHA' }), + }) + }) + it('navigates to the records page after successful submission', async () => { renderComponent(123) diff --git a/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.tsx b/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.tsx index 4e328f3fa..51e233660 100644 --- a/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.tsx +++ b/frontend/src/app/portal/organisations/[id]/records/create/CreateMedicineRecordForm.tsx @@ -2,15 +2,17 @@ import { revalidateLogic, useForm } from '@tanstack/react-form' import { useRouter } from 'next/navigation' -import { ChangeEvent, useState } from 'react' +import { ChangeEvent, useMemo, useState } from 'react' import z from 'zod' import { createRecord, CreateRecordCommand } from '@/client/generated' import { AddAnother } from '@/components/AddAnother/AddAnother' +import { Autocomplete } from '@/components/Autocomplete/Autocomplete' import { Button } from '@/components/Button/Button' import { Input } from '@/components/Input/Input' import { ErrorState } from '@/components/Placeholder/ErrorState' import { Textarea } from '@/components/Textarea/Textarea' +import { getCompanyCodeSuggestions } from '@/lib/form/companyCodeSuggestions' import { errorMessages } from '@/lib/form/errorMessages' import { updateFormApiErrors } from '@/lib/form/formErrorHandling' import { getFieldErrorMessage } from '@/lib/form/getFieldErrorMessage' @@ -52,6 +54,7 @@ const CreateMedicineRecordForm = ({ organisationId }: CreateMedicineRecordFormPr const router = useRouter() const [error, setError] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false) + const getSuggestions = useMemo(() => getCompanyCodeSuggestions(organisationId), [organisationId]) const defaultValues: CreateRecordCommand = { organisationId, companyCode: '', @@ -114,16 +117,15 @@ const CreateMedicineRecordForm = ({ organisationId }: CreateMedicineRecordFormPr {(field) => { const errorMessage = getFieldErrorMessage(field.state.meta.errors) return ( - ) => - field.handleChange(event.target.value) - } + onChange={field.handleChange} value={field.state.value} width={inputWidth} /> diff --git a/frontend/src/client/generated/@faker-js/faker.gen.ts b/frontend/src/client/generated/@faker-js/faker.gen.ts index 6f9641105..f006cd2c7 100644 --- a/frontend/src/client/generated/@faker-js/faker.gen.ts +++ b/frontend/src/client/generated/@faker-js/faker.gen.ts @@ -3,7 +3,7 @@ import type { Faker } from '@faker-js/faker'; import { faker } from '@faker-js/faker/locale/en_GB'; -import type { ApproveData, ApproveErrors, ApproveResponses, ArchiveRecordData, ArchiveRecordErrors, ArchiveRecordResponses, AuthenticationFailCode, AuthenticationProblemDetails, CancelPendingEmailChangeData, CancelPendingEmailChangeErrors, CancelPendingEmailChangeResponses, ChangeRecordStatusCommand, ConditionKind, ConfirmNewPasswordCommand, ConfirmNewPasswordData, ConfirmNewPasswordErrors, ConfirmNewPasswordResponses, CreateOrganisationDto, CreateRecordCommand, CreateRecordData, CreateRecordDto, CreateRecordErrors, CreateRecordResponses, DeactivateMembershipData, DeactivateMembershipErrors, DeactivateMembershipResponses, DiscardRecordData, DiscardRecordErrors, DiscardRecordResponses, EditableUserDetail, FormControl, GetAuthValidateSetupTokenData, GetAuthValidateSetupTokenErrors, GetAuthValidateSetupTokenResponses, GetCurrentOrganisationChampionsErrors, GetCurrentOrganisationChampionsResponses, GetCurrentUserOrganisationsErrors, GetCurrentUserOrganisationsResponses, GetOrganisationByIdData, GetOrganisationByIdErrors, GetOrganisationByIdResponses, GetOrganisationRecordsData, GetOrganisationRecordsErrors, GetOrganisationRecordsResponses, GetOrganisationsPublicOptionsResponse, GetRecordCheckAnswersData, GetRecordCheckAnswersErrors, GetRecordCheckAnswersResponses, GetRecordDetailData, GetRecordDetailErrors, GetRecordDetailResponses, GetRecordFormPageData, GetRecordFormPageErrors, GetRecordFormPageResponses, GetRecordOverviewData, GetRecordOverviewErrors, GetRecordOverviewResponses, GetRecordsQuerySortValue, GetRecordTaskListData, GetRecordTaskListErrors, GetRecordTaskListResponses, GetUserDetailsWithinOrganisationData, GetUserDetailsWithinOrganisationErrors, GetUserDetailsWithinOrganisationResponses, GetUserRegistrationByIdData, GetUserRegistrationByIdErrors, GetUserRegistrationByIdResponses, GetUsersData, GetUsersErrors, GetUsersMeErrors, GetUsersMeResponses, GetUsersQuerySortValue, GetUsersResponses, InitiateForgottenPasswordProcedureCommand, InitiateForgottenPasswordProcedureData, InitiateForgottenPasswordProcedureErrors, InitiateForgottenPasswordProcedureResponses, InitiateUpdateMultiFactorAuthenticationErrors, InitiateUpdateMultiFactorAuthenticationResponses, InvalidRecordProblemDetails, LoginRequest, MultiFactorAuthenticationSetupDto, MultiFactorAuthenticationUpdateDto, OnboardedUserDto, OnboardUserCommandDto, OrganisationDetailsDto, OrganisationListDto, OrganisationMembershipDto, OrganisationType, PaginatedResponseDtoOfRecordListItemDto, PaginatedResponseDtoOfUserListItemDto, PendingWorkEmailChangeDto, PharmaceuticalEntity, PostAuthLoginData, PostAuthLoginErrors, PostAuthLoginResponses, PostAuthRefreshErrors, PostAuthRefreshResponses, PostAuthResendSetupTokenData, PostAuthResendSetupTokenErrors, PostAuthResendSetupTokenResponses, PostAuthSetupSmsMfaData, PostAuthSetupSmsMfaErrors, PostAuthSetupSmsMfaResponses, PostAuthSetupUserData, PostAuthSetupUserErrors, PostAuthSetupUserResponses, PostAuthSignOutErrors, PostAuthSignOutResponses, PostAuthVerifyMfaData, PostAuthVerifyMfaErrors, PostAuthVerifyMfaResponses, PostAuthVerifySmsMfaData, PostAuthVerifySmsMfaErrors, PostAuthVerifySmsMfaResponses, PostOrganisationsData, PostOrganisationsErrors, PostOrganisationsResponses, PostUsersOnboardData, PostUsersOnboardErrors, PostUsersOnboardResponses, ProblemDetails, PutRecordOnHoldData, PutRecordOnHoldErrors, PutRecordOnHoldResponses, ReactivateMembershipData, ReactivateMembershipErrors, ReactivateMembershipResponses, RecordAction, RecordAnswersGroupItemDto, RecordAnswersOptionDto, RecordAnswersQuestionDto, RecordAnswersSectionDto, RecordAnswersTaskDto, RecordCheckAnswersDto, RecordDetailDto, RecordDisplayStatus, RecordListItemDto, RecordOverviewDto, RecordPageConditionDto, RecordPageDto, RecordPageOptionDto, RecordPagePageDto, RecordPageQuestionDto, RecordPageRuleDto, RecordPageSectionDto, RecordPageTaskDto, RecordStatus, RecordStatusChangeReason, RecordTaskListDto, RecordTaskListSectionDto, RecordTaskListTaskDto, RecordTaskStatus, RecordType, RegisterUserCommandDto, RegisterUserConfirmationDto, RegisterUserData, RegisterUserDetailsDto, RegisterUserErrors, RegisterUserResponses, RejectData, RejectErrors, RejectResponses, RemovedUserDto, RemoveUserData, RemoveUserErrors, RemoveUserResponses, ResendSetupTokenCommand, ResendSetupTokenResponse, ResendVerificationEmailData, ResendVerificationEmailErrors, ResendVerificationEmailResponses, RespondToMultiFactorAuthenticationChallengeCommand, RespondToMultiFactorAuthenticationChallengeData, RespondToMultiFactorAuthenticationChallengeErrors, RespondToMultiFactorAuthenticationChallengeResponses, ResumeRecordData, ResumeRecordErrors, ResumeRecordResponses, RuleKind, SaveRecordFormPageData, SaveRecordFormPageErrors, SaveRecordFormPageResponses, SaveRecordPageCommand, SaveRecordPageDto, SetupSmsMfaCommand, SetupUserCommand, SmsMultiFactorAuthenticationSetupDto, SortDirection, SubmissionConflictProblemDetails, SubmissionErrorDto, SubmitRecordCommand, SubmitRecordData, SubmitRecordErrors, UkpsChallengeType, UpdateCurrentOrganisationCommand, UpdateCurrentOrganisationData, UpdateCurrentOrganisationErrors, UpdateCurrentOrganisationResponses, UpdateOrganisationDetailsData, UpdateOrganisationDetailsDto, UpdateOrganisationDetailsErrors, UpdateOrganisationDetailsResponses, UpdateOrgMembershipUserRoleCommandDto, UpdateStatus, UpdateUserDetailsCommand, UpdateUserDetailsData, UpdateUserDetailsErrors, UpdateUserDetailsResponses, UpdateUserEmailCommand, UpdateUserEmailData, UpdateUserEmailErrors, UpdateUserEmailResponses, UpdateUserRoleData, UpdateUserRoleErrors, UpdateUserRoleResponses, UserDetailsDto, UserInformationDto, UserListItemDto, UserMembershipAction, UserOrgStatus, UserRole, UserType, ValidationProblemDetails, VerifyMultiFactorAuthenticationCommand, VerifyMultiFactorAuthenticationUpdateCommand, VerifyMultiFactorAuthenticationUpdateData, VerifyMultiFactorAuthenticationUpdateErrors, VerifyMultiFactorAuthenticationUpdateResponses, VerifyPendingEmailAddressCommand, VerifyPendingEmailAddressData, VerifyPendingEmailAddressErrors, VerifyPendingEmailAddressResponses, VerifySmsMultiFactorAuthenticationCommand } from '../types.gen'; +import type { ApproveData, ApproveErrors, ApproveResponses, ArchiveRecordData, ArchiveRecordErrors, ArchiveRecordResponses, AuthenticationFailCode, AuthenticationProblemDetails, CancelPendingEmailChangeData, CancelPendingEmailChangeErrors, CancelPendingEmailChangeResponses, ChangeRecordStatusCommand, CompanyCodeSuggestionsDto, ConditionKind, ConfirmNewPasswordCommand, ConfirmNewPasswordData, ConfirmNewPasswordErrors, ConfirmNewPasswordResponses, CreateOrganisationDto, CreateRecordCommand, CreateRecordData, CreateRecordDto, CreateRecordErrors, CreateRecordResponses, DeactivateMembershipData, DeactivateMembershipErrors, DeactivateMembershipResponses, DiscardRecordData, DiscardRecordErrors, DiscardRecordResponses, EditableUserDetail, FormControl, GetAuthValidateSetupTokenData, GetAuthValidateSetupTokenErrors, GetAuthValidateSetupTokenResponses, GetCurrentOrganisationChampionsErrors, GetCurrentOrganisationChampionsResponses, GetCurrentUserOrganisationsErrors, GetCurrentUserOrganisationsResponses, GetOrganisationByIdData, GetOrganisationByIdErrors, GetOrganisationByIdResponses, GetOrganisationCompanyCodesData, GetOrganisationCompanyCodesErrors, GetOrganisationCompanyCodesResponses, GetOrganisationRecordsData, GetOrganisationRecordsErrors, GetOrganisationRecordsResponses, GetOrganisationsPublicOptionsResponse, GetRecordCheckAnswersData, GetRecordCheckAnswersErrors, GetRecordCheckAnswersResponses, GetRecordDetailData, GetRecordDetailErrors, GetRecordDetailResponses, GetRecordFormPageData, GetRecordFormPageErrors, GetRecordFormPageResponses, GetRecordOverviewData, GetRecordOverviewErrors, GetRecordOverviewResponses, GetRecordsQuerySortValue, GetRecordTaskListData, GetRecordTaskListErrors, GetRecordTaskListResponses, GetUserDetailsWithinOrganisationData, GetUserDetailsWithinOrganisationErrors, GetUserDetailsWithinOrganisationResponses, GetUserRegistrationByIdData, GetUserRegistrationByIdErrors, GetUserRegistrationByIdResponses, GetUsersData, GetUsersErrors, GetUsersMeErrors, GetUsersMeResponses, GetUsersQuerySortValue, GetUsersResponses, InitiateForgottenPasswordProcedureCommand, InitiateForgottenPasswordProcedureData, InitiateForgottenPasswordProcedureErrors, InitiateForgottenPasswordProcedureResponses, InitiateUpdateMultiFactorAuthenticationErrors, InitiateUpdateMultiFactorAuthenticationResponses, InvalidRecordProblemDetails, LoginRequest, MultiFactorAuthenticationSetupDto, MultiFactorAuthenticationUpdateDto, OnboardedUserDto, OnboardUserCommandDto, OrganisationDetailsDto, OrganisationListDto, OrganisationMembershipDto, OrganisationType, PaginatedResponseDtoOfRecordListItemDto, PaginatedResponseDtoOfUserListItemDto, PendingWorkEmailChangeDto, PharmaceuticalEntity, PostAuthLoginData, PostAuthLoginErrors, PostAuthLoginResponses, PostAuthRefreshErrors, PostAuthRefreshResponses, PostAuthResendSetupTokenData, PostAuthResendSetupTokenErrors, PostAuthResendSetupTokenResponses, PostAuthSetupSmsMfaData, PostAuthSetupSmsMfaErrors, PostAuthSetupSmsMfaResponses, PostAuthSetupUserData, PostAuthSetupUserErrors, PostAuthSetupUserResponses, PostAuthSignOutErrors, PostAuthSignOutResponses, PostAuthVerifyMfaData, PostAuthVerifyMfaErrors, PostAuthVerifyMfaResponses, PostAuthVerifySmsMfaData, PostAuthVerifySmsMfaErrors, PostAuthVerifySmsMfaResponses, PostOrganisationsData, PostOrganisationsErrors, PostOrganisationsResponses, PostUsersOnboardData, PostUsersOnboardErrors, PostUsersOnboardResponses, ProblemDetails, PutRecordOnHoldData, PutRecordOnHoldErrors, PutRecordOnHoldResponses, ReactivateMembershipData, ReactivateMembershipErrors, ReactivateMembershipResponses, RecordAction, RecordAnswersGroupItemDto, RecordAnswersOptionDto, RecordAnswersQuestionDto, RecordAnswersSectionDto, RecordAnswersTaskDto, RecordCheckAnswersDto, RecordDetailDto, RecordDisplayStatus, RecordListItemDto, RecordOverviewDto, RecordPageConditionDto, RecordPageDto, RecordPageOptionDto, RecordPagePageDto, RecordPageQuestionDto, RecordPageRuleDto, RecordPageSectionDto, RecordPageTaskDto, RecordStatus, RecordStatusChangeReason, RecordTaskListDto, RecordTaskListSectionDto, RecordTaskListTaskDto, RecordTaskStatus, RecordType, RegisterUserCommandDto, RegisterUserConfirmationDto, RegisterUserData, RegisterUserDetailsDto, RegisterUserErrors, RegisterUserResponses, RejectData, RejectErrors, RejectResponses, RemovedUserDto, RemoveUserData, RemoveUserErrors, RemoveUserResponses, ResendSetupTokenCommand, ResendSetupTokenResponse, ResendVerificationEmailData, ResendVerificationEmailErrors, ResendVerificationEmailResponses, RespondToMultiFactorAuthenticationChallengeCommand, RespondToMultiFactorAuthenticationChallengeData, RespondToMultiFactorAuthenticationChallengeErrors, RespondToMultiFactorAuthenticationChallengeResponses, ResumeRecordData, ResumeRecordErrors, ResumeRecordResponses, RuleKind, SaveRecordFormPageData, SaveRecordFormPageErrors, SaveRecordFormPageResponses, SaveRecordPageCommand, SaveRecordPageDto, SetupSmsMfaCommand, SetupUserCommand, SmsMultiFactorAuthenticationSetupDto, SortDirection, SubmissionConflictProblemDetails, SubmissionErrorDto, SubmitRecordCommand, SubmitRecordData, SubmitRecordErrors, UkpsChallengeType, UpdateCurrentOrganisationCommand, UpdateCurrentOrganisationData, UpdateCurrentOrganisationErrors, UpdateCurrentOrganisationResponses, UpdateOrganisationDetailsData, UpdateOrganisationDetailsDto, UpdateOrganisationDetailsErrors, UpdateOrganisationDetailsResponses, UpdateOrgMembershipUserRoleCommandDto, UpdateStatus, UpdateUserDetailsCommand, UpdateUserDetailsData, UpdateUserDetailsErrors, UpdateUserDetailsResponses, UpdateUserEmailCommand, UpdateUserEmailData, UpdateUserEmailErrors, UpdateUserEmailResponses, UpdateUserRoleData, UpdateUserRoleErrors, UpdateUserRoleResponses, UserDetailsDto, UserInformationDto, UserListItemDto, UserMembershipAction, UserOrgStatus, UserRole, UserType, ValidationProblemDetails, VerifyMultiFactorAuthenticationCommand, VerifyMultiFactorAuthenticationUpdateCommand, VerifyMultiFactorAuthenticationUpdateData, VerifyMultiFactorAuthenticationUpdateErrors, VerifyMultiFactorAuthenticationUpdateResponses, VerifyPendingEmailAddressCommand, VerifyPendingEmailAddressData, VerifyPendingEmailAddressErrors, VerifyPendingEmailAddressResponses, VerifySmsMultiFactorAuthenticationCommand } from '../types.gen'; export type Options = { faker?: Faker; @@ -40,6 +40,13 @@ export const fakeAuthenticationFailCode = (options?: Options): AuthenticationFai ]); }; +export const fakeCompanyCodeSuggestionsDto = (options?: Options): CompanyCodeSuggestionsDto => { + const f = options?.faker ?? faker; + return { + items: f.helpers.multiple(() => f.string.sample()) + }; +}; + export const fakeConditionKind = (): ConditionKind => 'AnswerIn'; export const fakeConfirmNewPasswordCommand = (options?: Options): ConfirmNewPasswordCommand => { @@ -523,6 +530,7 @@ export const fakeRecordPageDto = (options?: Options): RecordPageDto => { return { formVersion: f.string.sample(), recordId: f.number.int(), + organisationId: f.number.int(), section: fakeRecordPageSectionDto(options), task: fakeRecordPageTaskDto(options), page: fakeRecordPagePageDto(options), @@ -1260,6 +1268,31 @@ export const fakeGetOrganisationRecordsResponse404 = (options?: Options): GetOrg export const fakeGetOrganisationRecordsResponse409 = (options?: Options): GetOrganisationRecordsErrors[409] => fakeAuthenticationProblemDetails(options); +export const fakeGetOrganisationCompanyCodesRequest = (options?: Options): Omit => { + const f = options?.faker ?? faker; + return { + path: { + organisationId: f.number.int() + }, + query: { + ...!resolveCondition(options?.includeOptional ?? true, f) ? {} : { Search: f.string.alpha({ length: { min: 0, max: 200 } }) }, + ...!resolveCondition(options?.includeOptional ?? true, f) ? {} : { Limit: f.number.int({ min: 1, max: 20 }) } + } + }; +}; + +export const fakeGetOrganisationCompanyCodesResponse200 = (options?: Options): GetOrganisationCompanyCodesResponses[200] => fakeCompanyCodeSuggestionsDto(options); + +export const fakeGetOrganisationCompanyCodesResponse400 = (options?: Options): GetOrganisationCompanyCodesErrors[400] => fakeValidationProblemDetails(options); + +export const fakeGetOrganisationCompanyCodesResponse401 = (options?: Options): GetOrganisationCompanyCodesErrors[401] => fakeAuthenticationProblemDetails(options); + +export const fakeGetOrganisationCompanyCodesResponse403 = (options?: Options): GetOrganisationCompanyCodesErrors[403] => fakeProblemDetails(options); + +export const fakeGetOrganisationCompanyCodesResponse404 = (options?: Options): GetOrganisationCompanyCodesErrors[404] => fakeProblemDetails(options); + +export const fakeGetOrganisationCompanyCodesResponse409 = (options?: Options): GetOrganisationCompanyCodesErrors[409] => fakeAuthenticationProblemDetails(options); + export const fakeGetRecordOverviewRequest = (options?: Options): Omit => { const f = options?.faker ?? faker; return { diff --git a/frontend/src/client/generated/index.ts b/frontend/src/client/generated/index.ts index 93311e498..96e1d51bb 100644 --- a/frontend/src/client/generated/index.ts +++ b/frontend/src/client/generated/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { approve, archiveRecord, cancelPendingEmailChange, confirmNewPassword, createRecord, deactivateMembership, discardRecord, getAuthValidateSetupToken, getCurrentOrganisationChampions, getCurrentUserOrganisations, getOrganisationById, getOrganisationRecords, getOrganisationsPublicOptions, getRecordCheckAnswers, getRecordDetail, getRecordFormPage, getRecordOverview, getRecordTaskList, getUserDetailsWithinOrganisation, getUserRegistrationById, getUsers, getUsersMe, initiateForgottenPasswordProcedure, initiateUpdateMultiFactorAuthentication, type Options, postAuthLogin, postAuthRefresh, postAuthResendSetupToken, postAuthSetupSmsMfa, postAuthSetupUser, postAuthSignOut, postAuthVerifyMfa, postAuthVerifySmsMfa, postOrganisations, postUsersOnboard, putRecordOnHold, reactivateMembership, registerUser, reject, removeUser, resendVerificationEmail, respondToMultiFactorAuthenticationChallenge, resumeRecord, saveRecordFormPage, submitRecord, updateCurrentOrganisation, updateOrganisationDetails, updateUserDetails, updateUserEmail, updateUserRole, verifyMultiFactorAuthenticationUpdate, verifyPendingEmailAddress } from './sdk.gen'; -export { type ApproveData, type ApproveError, type ApproveErrors, type ApproveResponses, type ArchiveRecordData, type ArchiveRecordError, type ArchiveRecordErrors, type ArchiveRecordResponses, AuthenticationFailCode, type AuthenticationProblemDetails, type CancelPendingEmailChangeData, type CancelPendingEmailChangeError, type CancelPendingEmailChangeErrors, type CancelPendingEmailChangeResponses, type ChangeRecordStatusCommand, type ClientOptions, ConditionKind, type ConfirmNewPasswordCommand, type ConfirmNewPasswordData, type ConfirmNewPasswordError, type ConfirmNewPasswordErrors, type ConfirmNewPasswordResponses, type CreateOrganisationDto, type CreateRecordCommand, type CreateRecordData, type CreateRecordDto, type CreateRecordError, type CreateRecordErrors, type CreateRecordResponse, type CreateRecordResponses, type DeactivateMembershipData, type DeactivateMembershipError, type DeactivateMembershipErrors, type DeactivateMembershipResponse, type DeactivateMembershipResponses, type DiscardRecordData, type DiscardRecordError, type DiscardRecordErrors, type DiscardRecordResponses, EditableUserDetail, FormControl, type GetAuthValidateSetupTokenData, type GetAuthValidateSetupTokenError, type GetAuthValidateSetupTokenErrors, type GetAuthValidateSetupTokenResponses, type GetCurrentOrganisationChampionsData, type GetCurrentOrganisationChampionsError, type GetCurrentOrganisationChampionsErrors, type GetCurrentOrganisationChampionsResponse, type GetCurrentOrganisationChampionsResponses, type GetCurrentUserOrganisationsData, type GetCurrentUserOrganisationsError, type GetCurrentUserOrganisationsErrors, type GetCurrentUserOrganisationsResponse, type GetCurrentUserOrganisationsResponses, type GetOrganisationByIdData, type GetOrganisationByIdError, type GetOrganisationByIdErrors, type GetOrganisationByIdResponse, type GetOrganisationByIdResponses, type GetOrganisationRecordsData, type GetOrganisationRecordsError, type GetOrganisationRecordsErrors, type GetOrganisationRecordsResponse, type GetOrganisationRecordsResponses, type GetOrganisationsPublicOptionsData, type GetOrganisationsPublicOptionsResponse, type GetOrganisationsPublicOptionsResponses, type GetRecordCheckAnswersData, type GetRecordCheckAnswersError, type GetRecordCheckAnswersErrors, type GetRecordCheckAnswersResponse, type GetRecordCheckAnswersResponses, type GetRecordDetailData, type GetRecordDetailError, type GetRecordDetailErrors, type GetRecordDetailResponse, type GetRecordDetailResponses, type GetRecordFormPageData, type GetRecordFormPageError, type GetRecordFormPageErrors, type GetRecordFormPageResponse, type GetRecordFormPageResponses, type GetRecordOverviewData, type GetRecordOverviewError, type GetRecordOverviewErrors, type GetRecordOverviewResponse, type GetRecordOverviewResponses, GetRecordsQuerySortValue, type GetRecordTaskListData, type GetRecordTaskListError, type GetRecordTaskListErrors, type GetRecordTaskListResponse, type GetRecordTaskListResponses, type GetUserDetailsWithinOrganisationData, type GetUserDetailsWithinOrganisationError, type GetUserDetailsWithinOrganisationErrors, type GetUserDetailsWithinOrganisationResponse, type GetUserDetailsWithinOrganisationResponses, type GetUserRegistrationByIdData, type GetUserRegistrationByIdError, type GetUserRegistrationByIdErrors, type GetUserRegistrationByIdResponse, type GetUserRegistrationByIdResponses, type GetUsersData, type GetUsersError, type GetUsersErrors, type GetUsersMeData, type GetUsersMeError, type GetUsersMeErrors, type GetUsersMeResponse, type GetUsersMeResponses, GetUsersQuerySortValue, type GetUsersResponse, type GetUsersResponses, type InitiateForgottenPasswordProcedureCommand, type InitiateForgottenPasswordProcedureData, type InitiateForgottenPasswordProcedureError, type InitiateForgottenPasswordProcedureErrors, type InitiateForgottenPasswordProcedureResponses, type InitiateUpdateMultiFactorAuthenticationData, type InitiateUpdateMultiFactorAuthenticationError, type InitiateUpdateMultiFactorAuthenticationErrors, type InitiateUpdateMultiFactorAuthenticationResponse, type InitiateUpdateMultiFactorAuthenticationResponses, type InvalidRecordProblemDetails, type LoginRequest, type MultiFactorAuthenticationSetupDto, type MultiFactorAuthenticationUpdateDto, type OnboardedUserDto, type OnboardUserCommandDto, type OrganisationDetailsDto, type OrganisationListDto, type OrganisationMembershipDto, OrganisationType, type PaginatedResponseDtoOfRecordListItemDto, type PaginatedResponseDtoOfUserListItemDto, type PendingWorkEmailChangeDto, PharmaceuticalEntity, type PostAuthLoginData, type PostAuthLoginError, type PostAuthLoginErrors, type PostAuthLoginResponses, type PostAuthRefreshData, type PostAuthRefreshError, type PostAuthRefreshErrors, type PostAuthRefreshResponses, type PostAuthResendSetupTokenData, type PostAuthResendSetupTokenError, type PostAuthResendSetupTokenErrors, type PostAuthResendSetupTokenResponse, type PostAuthResendSetupTokenResponses, type PostAuthSetupSmsMfaData, type PostAuthSetupSmsMfaError, type PostAuthSetupSmsMfaErrors, type PostAuthSetupSmsMfaResponse, type PostAuthSetupSmsMfaResponses, type PostAuthSetupUserData, type PostAuthSetupUserError, type PostAuthSetupUserErrors, type PostAuthSetupUserResponse, type PostAuthSetupUserResponses, type PostAuthSignOutData, type PostAuthSignOutError, type PostAuthSignOutErrors, type PostAuthSignOutResponses, type PostAuthVerifyMfaData, type PostAuthVerifyMfaError, type PostAuthVerifyMfaErrors, type PostAuthVerifyMfaResponses, type PostAuthVerifySmsMfaData, type PostAuthVerifySmsMfaError, type PostAuthVerifySmsMfaErrors, type PostAuthVerifySmsMfaResponses, type PostOrganisationsData, type PostOrganisationsError, type PostOrganisationsErrors, type PostOrganisationsResponse, type PostOrganisationsResponses, type PostUsersOnboardData, type PostUsersOnboardError, type PostUsersOnboardErrors, type PostUsersOnboardResponse, type PostUsersOnboardResponses, type ProblemDetails, type PutRecordOnHoldData, type PutRecordOnHoldError, type PutRecordOnHoldErrors, type PutRecordOnHoldResponses, type ReactivateMembershipData, type ReactivateMembershipError, type ReactivateMembershipErrors, type ReactivateMembershipResponse, type ReactivateMembershipResponses, RecordAction, type RecordAnswersGroupItemDto, type RecordAnswersOptionDto, type RecordAnswersQuestionDto, type RecordAnswersSectionDto, type RecordAnswersTaskDto, type RecordCheckAnswersDto, type RecordDetailDto, RecordDisplayStatus, type RecordListItemDto, type RecordOverviewDto, type RecordPageConditionDto, type RecordPageDto, type RecordPageOptionDto, type RecordPagePageDto, type RecordPageQuestionDto, type RecordPageRuleDto, type RecordPageSectionDto, type RecordPageTaskDto, RecordStatus, RecordStatusChangeReason, type RecordTaskListDto, type RecordTaskListSectionDto, type RecordTaskListTaskDto, RecordTaskStatus, RecordType, type RegisterUserCommandDto, type RegisterUserConfirmationDto, type RegisterUserData, type RegisterUserDetailsDto, type RegisterUserError, type RegisterUserErrors, type RegisterUserResponse, type RegisterUserResponses, type RejectData, type RejectError, type RejectErrors, type RejectResponses, type RemovedUserDto, type RemoveUserData, type RemoveUserError, type RemoveUserErrors, type RemoveUserResponse, type RemoveUserResponses, type ResendSetupTokenCommand, type ResendSetupTokenResponse, type ResendVerificationEmailData, type ResendVerificationEmailError, type ResendVerificationEmailErrors, type ResendVerificationEmailResponses, type RespondToMultiFactorAuthenticationChallengeCommand, type RespondToMultiFactorAuthenticationChallengeData, type RespondToMultiFactorAuthenticationChallengeError, type RespondToMultiFactorAuthenticationChallengeErrors, type RespondToMultiFactorAuthenticationChallengeResponses, type ResumeRecordData, type ResumeRecordError, type ResumeRecordErrors, type ResumeRecordResponses, RuleKind, type SaveRecordFormPageData, type SaveRecordFormPageError, type SaveRecordFormPageErrors, type SaveRecordFormPageResponse, type SaveRecordFormPageResponses, type SaveRecordPageCommand, type SaveRecordPageDto, type SetupSmsMfaCommand, type SetupUserCommand, type SmsMultiFactorAuthenticationSetupDto, SortDirection, type SubmissionConflictProblemDetails, type SubmissionErrorDto, type SubmitRecordCommand, type SubmitRecordData, type SubmitRecordError, type SubmitRecordErrors, type SubmitRecordResponse, type SubmitRecordResponses, UkpsChallengeType, type UpdateCurrentOrganisationCommand, type UpdateCurrentOrganisationData, type UpdateCurrentOrganisationError, type UpdateCurrentOrganisationErrors, type UpdateCurrentOrganisationResponses, type UpdateOrganisationDetailsData, type UpdateOrganisationDetailsDto, type UpdateOrganisationDetailsError, type UpdateOrganisationDetailsErrors, type UpdateOrganisationDetailsResponse, type UpdateOrganisationDetailsResponses, type UpdateOrgMembershipUserRoleCommandDto, UpdateStatus, type UpdateUserDetailsCommand, type UpdateUserDetailsData, type UpdateUserDetailsError, type UpdateUserDetailsErrors, type UpdateUserDetailsResponse, type UpdateUserDetailsResponses, type UpdateUserEmailCommand, type UpdateUserEmailData, type UpdateUserEmailError, type UpdateUserEmailErrors, type UpdateUserEmailResponses, type UpdateUserRoleData, type UpdateUserRoleError, type UpdateUserRoleErrors, type UpdateUserRoleResponse, type UpdateUserRoleResponses, type UserDetailsDto, type UserInformationDto, type UserListItemDto, UserMembershipAction, UserOrgStatus, UserRole, UserType, type ValidationProblemDetails, type VerifyMultiFactorAuthenticationCommand, type VerifyMultiFactorAuthenticationUpdateCommand, type VerifyMultiFactorAuthenticationUpdateData, type VerifyMultiFactorAuthenticationUpdateError, type VerifyMultiFactorAuthenticationUpdateErrors, type VerifyMultiFactorAuthenticationUpdateResponses, type VerifyPendingEmailAddressCommand, type VerifyPendingEmailAddressData, type VerifyPendingEmailAddressError, type VerifyPendingEmailAddressErrors, type VerifyPendingEmailAddressResponses, type VerifySmsMultiFactorAuthenticationCommand } from './types.gen'; +export { approve, archiveRecord, cancelPendingEmailChange, confirmNewPassword, createRecord, deactivateMembership, discardRecord, getAuthValidateSetupToken, getCurrentOrganisationChampions, getCurrentUserOrganisations, getOrganisationById, getOrganisationCompanyCodes, getOrganisationRecords, getOrganisationsPublicOptions, getRecordCheckAnswers, getRecordDetail, getRecordFormPage, getRecordOverview, getRecordTaskList, getUserDetailsWithinOrganisation, getUserRegistrationById, getUsers, getUsersMe, initiateForgottenPasswordProcedure, initiateUpdateMultiFactorAuthentication, type Options, postAuthLogin, postAuthRefresh, postAuthResendSetupToken, postAuthSetupSmsMfa, postAuthSetupUser, postAuthSignOut, postAuthVerifyMfa, postAuthVerifySmsMfa, postOrganisations, postUsersOnboard, putRecordOnHold, reactivateMembership, registerUser, reject, removeUser, resendVerificationEmail, respondToMultiFactorAuthenticationChallenge, resumeRecord, saveRecordFormPage, submitRecord, updateCurrentOrganisation, updateOrganisationDetails, updateUserDetails, updateUserEmail, updateUserRole, verifyMultiFactorAuthenticationUpdate, verifyPendingEmailAddress } from './sdk.gen'; +export { type ApproveData, type ApproveError, type ApproveErrors, type ApproveResponses, type ArchiveRecordData, type ArchiveRecordError, type ArchiveRecordErrors, type ArchiveRecordResponses, AuthenticationFailCode, type AuthenticationProblemDetails, type CancelPendingEmailChangeData, type CancelPendingEmailChangeError, type CancelPendingEmailChangeErrors, type CancelPendingEmailChangeResponses, type ChangeRecordStatusCommand, type ClientOptions, type CompanyCodeSuggestionsDto, ConditionKind, type ConfirmNewPasswordCommand, type ConfirmNewPasswordData, type ConfirmNewPasswordError, type ConfirmNewPasswordErrors, type ConfirmNewPasswordResponses, type CreateOrganisationDto, type CreateRecordCommand, type CreateRecordData, type CreateRecordDto, type CreateRecordError, type CreateRecordErrors, type CreateRecordResponse, type CreateRecordResponses, type DeactivateMembershipData, type DeactivateMembershipError, type DeactivateMembershipErrors, type DeactivateMembershipResponse, type DeactivateMembershipResponses, type DiscardRecordData, type DiscardRecordError, type DiscardRecordErrors, type DiscardRecordResponses, EditableUserDetail, FormControl, type GetAuthValidateSetupTokenData, type GetAuthValidateSetupTokenError, type GetAuthValidateSetupTokenErrors, type GetAuthValidateSetupTokenResponses, type GetCurrentOrganisationChampionsData, type GetCurrentOrganisationChampionsError, type GetCurrentOrganisationChampionsErrors, type GetCurrentOrganisationChampionsResponse, type GetCurrentOrganisationChampionsResponses, type GetCurrentUserOrganisationsData, type GetCurrentUserOrganisationsError, type GetCurrentUserOrganisationsErrors, type GetCurrentUserOrganisationsResponse, type GetCurrentUserOrganisationsResponses, type GetOrganisationByIdData, type GetOrganisationByIdError, type GetOrganisationByIdErrors, type GetOrganisationByIdResponse, type GetOrganisationByIdResponses, type GetOrganisationCompanyCodesData, type GetOrganisationCompanyCodesError, type GetOrganisationCompanyCodesErrors, type GetOrganisationCompanyCodesResponse, type GetOrganisationCompanyCodesResponses, type GetOrganisationRecordsData, type GetOrganisationRecordsError, type GetOrganisationRecordsErrors, type GetOrganisationRecordsResponse, type GetOrganisationRecordsResponses, type GetOrganisationsPublicOptionsData, type GetOrganisationsPublicOptionsResponse, type GetOrganisationsPublicOptionsResponses, type GetRecordCheckAnswersData, type GetRecordCheckAnswersError, type GetRecordCheckAnswersErrors, type GetRecordCheckAnswersResponse, type GetRecordCheckAnswersResponses, type GetRecordDetailData, type GetRecordDetailError, type GetRecordDetailErrors, type GetRecordDetailResponse, type GetRecordDetailResponses, type GetRecordFormPageData, type GetRecordFormPageError, type GetRecordFormPageErrors, type GetRecordFormPageResponse, type GetRecordFormPageResponses, type GetRecordOverviewData, type GetRecordOverviewError, type GetRecordOverviewErrors, type GetRecordOverviewResponse, type GetRecordOverviewResponses, GetRecordsQuerySortValue, type GetRecordTaskListData, type GetRecordTaskListError, type GetRecordTaskListErrors, type GetRecordTaskListResponse, type GetRecordTaskListResponses, type GetUserDetailsWithinOrganisationData, type GetUserDetailsWithinOrganisationError, type GetUserDetailsWithinOrganisationErrors, type GetUserDetailsWithinOrganisationResponse, type GetUserDetailsWithinOrganisationResponses, type GetUserRegistrationByIdData, type GetUserRegistrationByIdError, type GetUserRegistrationByIdErrors, type GetUserRegistrationByIdResponse, type GetUserRegistrationByIdResponses, type GetUsersData, type GetUsersError, type GetUsersErrors, type GetUsersMeData, type GetUsersMeError, type GetUsersMeErrors, type GetUsersMeResponse, type GetUsersMeResponses, GetUsersQuerySortValue, type GetUsersResponse, type GetUsersResponses, type InitiateForgottenPasswordProcedureCommand, type InitiateForgottenPasswordProcedureData, type InitiateForgottenPasswordProcedureError, type InitiateForgottenPasswordProcedureErrors, type InitiateForgottenPasswordProcedureResponses, type InitiateUpdateMultiFactorAuthenticationData, type InitiateUpdateMultiFactorAuthenticationError, type InitiateUpdateMultiFactorAuthenticationErrors, type InitiateUpdateMultiFactorAuthenticationResponse, type InitiateUpdateMultiFactorAuthenticationResponses, type InvalidRecordProblemDetails, type LoginRequest, type MultiFactorAuthenticationSetupDto, type MultiFactorAuthenticationUpdateDto, type OnboardedUserDto, type OnboardUserCommandDto, type OrganisationDetailsDto, type OrganisationListDto, type OrganisationMembershipDto, OrganisationType, type PaginatedResponseDtoOfRecordListItemDto, type PaginatedResponseDtoOfUserListItemDto, type PendingWorkEmailChangeDto, PharmaceuticalEntity, type PostAuthLoginData, type PostAuthLoginError, type PostAuthLoginErrors, type PostAuthLoginResponses, type PostAuthRefreshData, type PostAuthRefreshError, type PostAuthRefreshErrors, type PostAuthRefreshResponses, type PostAuthResendSetupTokenData, type PostAuthResendSetupTokenError, type PostAuthResendSetupTokenErrors, type PostAuthResendSetupTokenResponse, type PostAuthResendSetupTokenResponses, type PostAuthSetupSmsMfaData, type PostAuthSetupSmsMfaError, type PostAuthSetupSmsMfaErrors, type PostAuthSetupSmsMfaResponse, type PostAuthSetupSmsMfaResponses, type PostAuthSetupUserData, type PostAuthSetupUserError, type PostAuthSetupUserErrors, type PostAuthSetupUserResponse, type PostAuthSetupUserResponses, type PostAuthSignOutData, type PostAuthSignOutError, type PostAuthSignOutErrors, type PostAuthSignOutResponses, type PostAuthVerifyMfaData, type PostAuthVerifyMfaError, type PostAuthVerifyMfaErrors, type PostAuthVerifyMfaResponses, type PostAuthVerifySmsMfaData, type PostAuthVerifySmsMfaError, type PostAuthVerifySmsMfaErrors, type PostAuthVerifySmsMfaResponses, type PostOrganisationsData, type PostOrganisationsError, type PostOrganisationsErrors, type PostOrganisationsResponse, type PostOrganisationsResponses, type PostUsersOnboardData, type PostUsersOnboardError, type PostUsersOnboardErrors, type PostUsersOnboardResponse, type PostUsersOnboardResponses, type ProblemDetails, type PutRecordOnHoldData, type PutRecordOnHoldError, type PutRecordOnHoldErrors, type PutRecordOnHoldResponses, type ReactivateMembershipData, type ReactivateMembershipError, type ReactivateMembershipErrors, type ReactivateMembershipResponse, type ReactivateMembershipResponses, RecordAction, type RecordAnswersGroupItemDto, type RecordAnswersOptionDto, type RecordAnswersQuestionDto, type RecordAnswersSectionDto, type RecordAnswersTaskDto, type RecordCheckAnswersDto, type RecordDetailDto, RecordDisplayStatus, type RecordListItemDto, type RecordOverviewDto, type RecordPageConditionDto, type RecordPageDto, type RecordPageOptionDto, type RecordPagePageDto, type RecordPageQuestionDto, type RecordPageRuleDto, type RecordPageSectionDto, type RecordPageTaskDto, RecordStatus, RecordStatusChangeReason, type RecordTaskListDto, type RecordTaskListSectionDto, type RecordTaskListTaskDto, RecordTaskStatus, RecordType, type RegisterUserCommandDto, type RegisterUserConfirmationDto, type RegisterUserData, type RegisterUserDetailsDto, type RegisterUserError, type RegisterUserErrors, type RegisterUserResponse, type RegisterUserResponses, type RejectData, type RejectError, type RejectErrors, type RejectResponses, type RemovedUserDto, type RemoveUserData, type RemoveUserError, type RemoveUserErrors, type RemoveUserResponse, type RemoveUserResponses, type ResendSetupTokenCommand, type ResendSetupTokenResponse, type ResendVerificationEmailData, type ResendVerificationEmailError, type ResendVerificationEmailErrors, type ResendVerificationEmailResponses, type RespondToMultiFactorAuthenticationChallengeCommand, type RespondToMultiFactorAuthenticationChallengeData, type RespondToMultiFactorAuthenticationChallengeError, type RespondToMultiFactorAuthenticationChallengeErrors, type RespondToMultiFactorAuthenticationChallengeResponses, type ResumeRecordData, type ResumeRecordError, type ResumeRecordErrors, type ResumeRecordResponses, RuleKind, type SaveRecordFormPageData, type SaveRecordFormPageError, type SaveRecordFormPageErrors, type SaveRecordFormPageResponse, type SaveRecordFormPageResponses, type SaveRecordPageCommand, type SaveRecordPageDto, type SetupSmsMfaCommand, type SetupUserCommand, type SmsMultiFactorAuthenticationSetupDto, SortDirection, type SubmissionConflictProblemDetails, type SubmissionErrorDto, type SubmitRecordCommand, type SubmitRecordData, type SubmitRecordError, type SubmitRecordErrors, type SubmitRecordResponse, type SubmitRecordResponses, UkpsChallengeType, type UpdateCurrentOrganisationCommand, type UpdateCurrentOrganisationData, type UpdateCurrentOrganisationError, type UpdateCurrentOrganisationErrors, type UpdateCurrentOrganisationResponses, type UpdateOrganisationDetailsData, type UpdateOrganisationDetailsDto, type UpdateOrganisationDetailsError, type UpdateOrganisationDetailsErrors, type UpdateOrganisationDetailsResponse, type UpdateOrganisationDetailsResponses, type UpdateOrgMembershipUserRoleCommandDto, UpdateStatus, type UpdateUserDetailsCommand, type UpdateUserDetailsData, type UpdateUserDetailsError, type UpdateUserDetailsErrors, type UpdateUserDetailsResponse, type UpdateUserDetailsResponses, type UpdateUserEmailCommand, type UpdateUserEmailData, type UpdateUserEmailError, type UpdateUserEmailErrors, type UpdateUserEmailResponses, type UpdateUserRoleData, type UpdateUserRoleError, type UpdateUserRoleErrors, type UpdateUserRoleResponse, type UpdateUserRoleResponses, type UserDetailsDto, type UserInformationDto, type UserListItemDto, UserMembershipAction, UserOrgStatus, UserRole, UserType, type ValidationProblemDetails, type VerifyMultiFactorAuthenticationCommand, type VerifyMultiFactorAuthenticationUpdateCommand, type VerifyMultiFactorAuthenticationUpdateData, type VerifyMultiFactorAuthenticationUpdateError, type VerifyMultiFactorAuthenticationUpdateErrors, type VerifyMultiFactorAuthenticationUpdateResponses, type VerifyPendingEmailAddressCommand, type VerifyPendingEmailAddressData, type VerifyPendingEmailAddressError, type VerifyPendingEmailAddressErrors, type VerifyPendingEmailAddressResponses, type VerifySmsMultiFactorAuthenticationCommand } from './types.gen'; diff --git a/frontend/src/client/generated/sdk.gen.ts b/frontend/src/client/generated/sdk.gen.ts index 2cf279af6..49c697adb 100644 --- a/frontend/src/client/generated/sdk.gen.ts +++ b/frontend/src/client/generated/sdk.gen.ts @@ -2,7 +2,7 @@ import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client'; import { client } from './client.gen'; -import type { ApproveData, ApproveErrors, ApproveResponses, ArchiveRecordData, ArchiveRecordErrors, ArchiveRecordResponses, CancelPendingEmailChangeData, CancelPendingEmailChangeErrors, CancelPendingEmailChangeResponses, ConfirmNewPasswordData, ConfirmNewPasswordErrors, ConfirmNewPasswordResponses, CreateRecordData, CreateRecordErrors, CreateRecordResponses, DeactivateMembershipData, DeactivateMembershipErrors, DeactivateMembershipResponses, DiscardRecordData, DiscardRecordErrors, DiscardRecordResponses, GetAuthValidateSetupTokenData, GetAuthValidateSetupTokenErrors, GetAuthValidateSetupTokenResponses, GetCurrentOrganisationChampionsData, GetCurrentOrganisationChampionsErrors, GetCurrentOrganisationChampionsResponses, GetCurrentUserOrganisationsData, GetCurrentUserOrganisationsErrors, GetCurrentUserOrganisationsResponses, GetOrganisationByIdData, GetOrganisationByIdErrors, GetOrganisationByIdResponses, GetOrganisationRecordsData, GetOrganisationRecordsErrors, GetOrganisationRecordsResponses, GetOrganisationsPublicOptionsData, GetOrganisationsPublicOptionsResponses, GetRecordCheckAnswersData, GetRecordCheckAnswersErrors, GetRecordCheckAnswersResponses, GetRecordDetailData, GetRecordDetailErrors, GetRecordDetailResponses, GetRecordFormPageData, GetRecordFormPageErrors, GetRecordFormPageResponses, GetRecordOverviewData, GetRecordOverviewErrors, GetRecordOverviewResponses, GetRecordTaskListData, GetRecordTaskListErrors, GetRecordTaskListResponses, GetUserDetailsWithinOrganisationData, GetUserDetailsWithinOrganisationErrors, GetUserDetailsWithinOrganisationResponses, GetUserRegistrationByIdData, GetUserRegistrationByIdErrors, GetUserRegistrationByIdResponses, GetUsersData, GetUsersErrors, GetUsersMeData, GetUsersMeErrors, GetUsersMeResponses, GetUsersResponses, InitiateForgottenPasswordProcedureData, InitiateForgottenPasswordProcedureErrors, InitiateForgottenPasswordProcedureResponses, InitiateUpdateMultiFactorAuthenticationData, InitiateUpdateMultiFactorAuthenticationErrors, InitiateUpdateMultiFactorAuthenticationResponses, PostAuthLoginData, PostAuthLoginErrors, PostAuthLoginResponses, PostAuthRefreshData, PostAuthRefreshErrors, PostAuthRefreshResponses, PostAuthResendSetupTokenData, PostAuthResendSetupTokenErrors, PostAuthResendSetupTokenResponses, PostAuthSetupSmsMfaData, PostAuthSetupSmsMfaErrors, PostAuthSetupSmsMfaResponses, PostAuthSetupUserData, PostAuthSetupUserErrors, PostAuthSetupUserResponses, PostAuthSignOutData, PostAuthSignOutErrors, PostAuthSignOutResponses, PostAuthVerifyMfaData, PostAuthVerifyMfaErrors, PostAuthVerifyMfaResponses, PostAuthVerifySmsMfaData, PostAuthVerifySmsMfaErrors, PostAuthVerifySmsMfaResponses, PostOrganisationsData, PostOrganisationsErrors, PostOrganisationsResponses, PostUsersOnboardData, PostUsersOnboardErrors, PostUsersOnboardResponses, PutRecordOnHoldData, PutRecordOnHoldErrors, PutRecordOnHoldResponses, ReactivateMembershipData, ReactivateMembershipErrors, ReactivateMembershipResponses, RegisterUserData, RegisterUserErrors, RegisterUserResponses, RejectData, RejectErrors, RejectResponses, RemoveUserData, RemoveUserErrors, RemoveUserResponses, ResendVerificationEmailData, ResendVerificationEmailErrors, ResendVerificationEmailResponses, RespondToMultiFactorAuthenticationChallengeData, RespondToMultiFactorAuthenticationChallengeErrors, RespondToMultiFactorAuthenticationChallengeResponses, ResumeRecordData, ResumeRecordErrors, ResumeRecordResponses, SaveRecordFormPageData, SaveRecordFormPageErrors, SaveRecordFormPageResponses, SubmitRecordData, SubmitRecordErrors, SubmitRecordResponses, UpdateCurrentOrganisationData, UpdateCurrentOrganisationErrors, UpdateCurrentOrganisationResponses, UpdateOrganisationDetailsData, UpdateOrganisationDetailsErrors, UpdateOrganisationDetailsResponses, UpdateUserDetailsData, UpdateUserDetailsErrors, UpdateUserDetailsResponses, UpdateUserEmailData, UpdateUserEmailErrors, UpdateUserEmailResponses, UpdateUserRoleData, UpdateUserRoleErrors, UpdateUserRoleResponses, VerifyMultiFactorAuthenticationUpdateData, VerifyMultiFactorAuthenticationUpdateErrors, VerifyMultiFactorAuthenticationUpdateResponses, VerifyPendingEmailAddressData, VerifyPendingEmailAddressErrors, VerifyPendingEmailAddressResponses } from './types.gen'; +import type { ApproveData, ApproveErrors, ApproveResponses, ArchiveRecordData, ArchiveRecordErrors, ArchiveRecordResponses, CancelPendingEmailChangeData, CancelPendingEmailChangeErrors, CancelPendingEmailChangeResponses, ConfirmNewPasswordData, ConfirmNewPasswordErrors, ConfirmNewPasswordResponses, CreateRecordData, CreateRecordErrors, CreateRecordResponses, DeactivateMembershipData, DeactivateMembershipErrors, DeactivateMembershipResponses, DiscardRecordData, DiscardRecordErrors, DiscardRecordResponses, GetAuthValidateSetupTokenData, GetAuthValidateSetupTokenErrors, GetAuthValidateSetupTokenResponses, GetCurrentOrganisationChampionsData, GetCurrentOrganisationChampionsErrors, GetCurrentOrganisationChampionsResponses, GetCurrentUserOrganisationsData, GetCurrentUserOrganisationsErrors, GetCurrentUserOrganisationsResponses, GetOrganisationByIdData, GetOrganisationByIdErrors, GetOrganisationByIdResponses, GetOrganisationCompanyCodesData, GetOrganisationCompanyCodesErrors, GetOrganisationCompanyCodesResponses, GetOrganisationRecordsData, GetOrganisationRecordsErrors, GetOrganisationRecordsResponses, GetOrganisationsPublicOptionsData, GetOrganisationsPublicOptionsResponses, GetRecordCheckAnswersData, GetRecordCheckAnswersErrors, GetRecordCheckAnswersResponses, GetRecordDetailData, GetRecordDetailErrors, GetRecordDetailResponses, GetRecordFormPageData, GetRecordFormPageErrors, GetRecordFormPageResponses, GetRecordOverviewData, GetRecordOverviewErrors, GetRecordOverviewResponses, GetRecordTaskListData, GetRecordTaskListErrors, GetRecordTaskListResponses, GetUserDetailsWithinOrganisationData, GetUserDetailsWithinOrganisationErrors, GetUserDetailsWithinOrganisationResponses, GetUserRegistrationByIdData, GetUserRegistrationByIdErrors, GetUserRegistrationByIdResponses, GetUsersData, GetUsersErrors, GetUsersMeData, GetUsersMeErrors, GetUsersMeResponses, GetUsersResponses, InitiateForgottenPasswordProcedureData, InitiateForgottenPasswordProcedureErrors, InitiateForgottenPasswordProcedureResponses, InitiateUpdateMultiFactorAuthenticationData, InitiateUpdateMultiFactorAuthenticationErrors, InitiateUpdateMultiFactorAuthenticationResponses, PostAuthLoginData, PostAuthLoginErrors, PostAuthLoginResponses, PostAuthRefreshData, PostAuthRefreshErrors, PostAuthRefreshResponses, PostAuthResendSetupTokenData, PostAuthResendSetupTokenErrors, PostAuthResendSetupTokenResponses, PostAuthSetupSmsMfaData, PostAuthSetupSmsMfaErrors, PostAuthSetupSmsMfaResponses, PostAuthSetupUserData, PostAuthSetupUserErrors, PostAuthSetupUserResponses, PostAuthSignOutData, PostAuthSignOutErrors, PostAuthSignOutResponses, PostAuthVerifyMfaData, PostAuthVerifyMfaErrors, PostAuthVerifyMfaResponses, PostAuthVerifySmsMfaData, PostAuthVerifySmsMfaErrors, PostAuthVerifySmsMfaResponses, PostOrganisationsData, PostOrganisationsErrors, PostOrganisationsResponses, PostUsersOnboardData, PostUsersOnboardErrors, PostUsersOnboardResponses, PutRecordOnHoldData, PutRecordOnHoldErrors, PutRecordOnHoldResponses, ReactivateMembershipData, ReactivateMembershipErrors, ReactivateMembershipResponses, RegisterUserData, RegisterUserErrors, RegisterUserResponses, RejectData, RejectErrors, RejectResponses, RemoveUserData, RemoveUserErrors, RemoveUserResponses, ResendVerificationEmailData, ResendVerificationEmailErrors, ResendVerificationEmailResponses, RespondToMultiFactorAuthenticationChallengeData, RespondToMultiFactorAuthenticationChallengeErrors, RespondToMultiFactorAuthenticationChallengeResponses, ResumeRecordData, ResumeRecordErrors, ResumeRecordResponses, SaveRecordFormPageData, SaveRecordFormPageErrors, SaveRecordFormPageResponses, SubmitRecordData, SubmitRecordErrors, SubmitRecordResponses, UpdateCurrentOrganisationData, UpdateCurrentOrganisationErrors, UpdateCurrentOrganisationResponses, UpdateOrganisationDetailsData, UpdateOrganisationDetailsErrors, UpdateOrganisationDetailsResponses, UpdateUserDetailsData, UpdateUserDetailsErrors, UpdateUserDetailsResponses, UpdateUserEmailData, UpdateUserEmailErrors, UpdateUserEmailResponses, UpdateUserRoleData, UpdateUserRoleErrors, UpdateUserRoleResponses, VerifyMultiFactorAuthenticationUpdateData, VerifyMultiFactorAuthenticationUpdateErrors, VerifyMultiFactorAuthenticationUpdateResponses, VerifyPendingEmailAddressData, VerifyPendingEmailAddressErrors, VerifyPendingEmailAddressResponses } from './types.gen'; export type Options = Options2 & { /** @@ -252,6 +252,12 @@ export const getOrganisationsPublicOptions = (options: Options): RequestResult => (options.client ?? client).get({ url: '/records/organisations/{organisationId}', ...options }); +/** + * Retrieves the company codes already used on an organisation's records that contain the + * search text, for suggesting while a user types a company code. + */ +export const getOrganisationCompanyCodes = (options: Options): RequestResult => (options.client ?? client).get({ url: '/records/organisations/{organisationId}/company-codes', ...options }); + /** * Retrieves a record's status, permitted actions and identifying details, whatever its * status, without its answers. diff --git a/frontend/src/client/generated/types.gen.ts b/frontend/src/client/generated/types.gen.ts index 07f2df043..66cd7e994 100644 --- a/frontend/src/client/generated/types.gen.ts +++ b/frontend/src/client/generated/types.gen.ts @@ -52,6 +52,18 @@ export type ChangeRecordStatusCommand = { note?: null | string; }; +/** + * The company codes already used on an organisation's records, offered as suggestions while a + * user types a company code. + */ +export type CompanyCodeSuggestionsDto = { + /** + * Gets the distinct matching company codes, those starting with the search first, then + * alphabetically. + */ + items: Array; +}; + /** * The kind of a condition that decides whether a question applies. Part of the HTTP API * contract: the member names are sent to the frontend, so never rename or remove one. @@ -839,6 +851,11 @@ export type RecordPageDto = { * The record the page belongs to. */ recordId: number; + /** + * The organisation that owns the record; used to look up suggestions such as the + * organisation's existing company codes. + */ + organisationId: number; /** * The section the page belongs to. */ @@ -2728,6 +2745,62 @@ export type GetOrganisationRecordsResponses = { export type GetOrganisationRecordsResponse = GetOrganisationRecordsResponses[keyof GetOrganisationRecordsResponses]; +export type GetOrganisationCompanyCodesData = { + body?: never; + path: { + /** + * The unique identifier of the organisation. + */ + organisationId: number; + }; + query?: { + /** + * Gets or initialises the text the company codes must contain, ignoring case. A blank search + * returns no suggestions. + */ + Search?: string; + /** + * Gets or initialises the maximum number of suggestions to return. + */ + Limit?: number; + }; + url: '/records/organisations/{organisationId}/company-codes'; +}; + +export type GetOrganisationCompanyCodesErrors = { + /** + * The query parameters are invalid. + */ + 400: ValidationProblemDetails; + /** + * Unauthorized + */ + 401: AuthenticationProblemDetails; + /** + * The caller is not authorised to view the organisation's records. + */ + 403: ProblemDetails; + /** + * The specified organisation does not exist. + */ + 404: ProblemDetails; + /** + * Conflict + */ + 409: AuthenticationProblemDetails; +}; + +export type GetOrganisationCompanyCodesError = GetOrganisationCompanyCodesErrors[keyof GetOrganisationCompanyCodesErrors]; + +export type GetOrganisationCompanyCodesResponses = { + /** + * Returns the matching company codes. + */ + 200: CompanyCodeSuggestionsDto; +}; + +export type GetOrganisationCompanyCodesResponse = GetOrganisationCompanyCodesResponses[keyof GetOrganisationCompanyCodesResponses]; + export type GetRecordOverviewData = { body?: never; path: { diff --git a/frontend/src/components/Autocomplete/Autocomplete.module.scss b/frontend/src/components/Autocomplete/Autocomplete.module.scss new file mode 100644 index 000000000..97626035a --- /dev/null +++ b/frontend/src/components/Autocomplete/Autocomplete.module.scss @@ -0,0 +1,85 @@ +@use '@/styles/colours'; +@use '@/styles/spacing'; +@use '@/styles/typography'; +@use '@/styles/utils'; + +// The field and its suggestions share this box, so the list is always the field's width and +// never wider than the screen (WCAG 1.4.10 reflow). +.wrapper { + max-width: 100%; + position: relative; +} + +.input { + // NDS gives the input `width: 100%`; the width modifier sits on the wrapper instead. + max-width: 100%; +} + +.listbox { + background-color: colours.$fill-white-background; + border: utils.rem(spacing.$xx-small) solid colours.$border-dark; + border-top: 0; + box-sizing: border-box; + left: 0; + list-style: none; + margin: 0; + // A short list keeps the field and nearby content in view (WCAG 2.4.11). + max-height: utils.rem(300); + overflow-y: auto; + padding: 0; + position: absolute; + right: 0; + top: 100%; + z-index: 100; + + &[hidden] { + display: none; + } +} + +.option { + border-bottom: utils.rem(1) solid colours.$border; + // Shows the active option without relying on colour alone (WCAG 1.4.1). + border-left: utils.rem(spacing.$x-small) solid transparent; + cursor: pointer; + margin: 0; + max-width: none; + // A target at least 44px tall, beyond WCAG 2.5.8's 24px minimum. + min-height: utils.rem(44); + overflow-wrap: anywhere; + padding: utils.rem(spacing.$small) utils.rem(spacing.$small); + + &:last-child { + border-bottom: 0; + } + + &:hover { + background-color: colours.$filter-option-hover; + } +} + +.optionActive, +.optionActive:hover { + background-color: colours.$btn-primary; + border-left-color: colours.$focus; + color: colours.$text-inverse; + outline: utils.rem(spacing.$xx-small) solid transparent; +} + +.match { + font-weight: bold; +} + +@media (forced-colors: active) { + .optionActive, + .optionActive:hover { + background-color: Highlight; + border-left-color: HighlightText; + color: HighlightText; + forced-color-adjust: none; + } +} + +:global(.input__label).leadLabel { + @include typography.lead-label; +} diff --git a/frontend/src/components/Autocomplete/Autocomplete.test.tsx b/frontend/src/components/Autocomplete/Autocomplete.test.tsx new file mode 100644 index 000000000..6c136d014 --- /dev/null +++ b/frontend/src/components/Autocomplete/Autocomplete.test.tsx @@ -0,0 +1,382 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { useState } from 'react' +import { describe, expect, it, vi } from 'vitest' + +import { Autocomplete } from './Autocomplete' + +import type { AutocompleteProps, GetSuggestions } from './Autocomplete' + +const codes = ['ABC-123', 'ABC-456', 'XABC-9', 'DEF-1'] + +const filterCodes: GetSuggestions = (query) => + Promise.resolve(codes.filter((code) => code.toLowerCase().includes(query.toLowerCase()))) + +type HarnessProps = Partial & { onSubmit?: (value: string) => void } + +function Harness({ onSubmit, getSuggestions = filterCodes, ...props }: HarnessProps) { + const [value, setValue] = useState('') + return ( +
{ + event.preventDefault() + onSubmit?.(value) + }} + > + + + + ) +} + +const combobox = () => screen.getByRole('combobox', { name: 'Company code' }) + +describe('Autocomplete', () => { + it('renders a collapsed combobox described by its hint and usage instructions', () => { + render() + + const input = combobox() + expect(input).toHaveAttribute('aria-autocomplete', 'list') + expect(input).toHaveAttribute('aria-expanded', 'false') + expect(input).toHaveAttribute('aria-controls', 'companyCode-listbox') + expect(input).toHaveAttribute('autocomplete', 'off') + expect(input).not.toHaveAttribute('aria-activedescendant') + expect(input).toHaveAccessibleDescription( + expect.stringContaining('Enter the company code When suggestions are available'), + ) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + }) + + it('shows matching suggestions as the user types and announces how many', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + + const options = await screen.findAllByRole('option') + expect(options.map((option) => option.textContent)).toEqual(['ABC-123', 'ABC-456', 'XABC-9']) + expect(combobox()).toHaveAttribute('aria-expanded', 'true') + expect(screen.getByRole('listbox', { name: 'Company code suggestions' })).toBeVisible() + expect(screen.getByRole('status')).toHaveTextContent('3 suggestions available.') + }) + + it('moves through suggestions with the arrow keys, returning to the input after the last', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'def') + await screen.findByRole('option', { name: 'DEF-1' }) + + await user.keyboard('{ArrowDown}') + expect(combobox()).toHaveAttribute('aria-activedescendant', 'companyCode-option-0') + expect(screen.getByRole('option', { name: 'DEF-1' })).toHaveAttribute('aria-selected', 'true') + + await user.keyboard('{ArrowDown}') + expect(combobox()).not.toHaveAttribute('aria-activedescendant') + + await user.keyboard('{ArrowUp}') + expect(combobox()).toHaveAttribute('aria-activedescendant', 'companyCode-option-0') + }) + + it('selects the active suggestion with Enter without submitting the form', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await screen.findAllByRole('option') + await user.keyboard('{ArrowDown}{ArrowDown}{Enter}') + + expect(combobox()).toHaveValue('ABC-456') + expect(combobox()).toHaveFocus() + expect(combobox()).toHaveAttribute('aria-expanded', 'false') + expect(onSubmit).not.toHaveBeenCalled() + }) + + it('submits the typed text with Enter when no suggestion is active', async () => { + const onSubmit = vi.fn() + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await screen.findAllByRole('option') + await user.keyboard('{Enter}') + + expect(onSubmit).toHaveBeenCalledWith('abc') + }) + + it('drops old suggestions and the active selection as soon as the query changes', async () => { + const onSubmit = vi.fn() + const getSuggestions: GetSuggestions = (query, signal) => + query.startsWith('abc-') ? new Promise(() => undefined) : filterCodes(query, signal) + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await screen.findAllByRole('option') + await user.keyboard('{ArrowDown}') + expect(combobox()).toHaveAttribute('aria-activedescendant', 'companyCode-option-0') + + await user.type(combobox(), '-9') + + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(combobox()).not.toHaveAttribute('aria-activedescendant') + expect(screen.getByRole('status')).toBeEmptyDOMElement() + await user.keyboard('{ArrowDown}{Enter}') + + expect(combobox()).toHaveValue('abc-9') + expect(onSubmit).toHaveBeenCalledWith('abc-9') + }) + + it('keeps free text that matches no suggestion', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'NEW-CODE') + + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent('No suggestions available.'), + ) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(combobox()).toHaveValue('NEW-CODE') + }) + + it('closes the suggestions with Escape, keeping the typed text', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await screen.findAllByRole('option') + await user.keyboard('{ArrowDown}{Escape}') + + expect(combobox()).toHaveAttribute('aria-expanded', 'false') + expect(combobox()).not.toHaveAttribute('aria-activedescendant') + expect(combobox()).toHaveValue('abc') + + await user.keyboard('{ArrowDown}') + expect(combobox()).toHaveAttribute('aria-expanded', 'true') + }) + + it('cancels a running fetch with Escape before the list has opened', async () => { + let resolve: (value: string[]) => void = () => undefined + let signal: AbortSignal | undefined + const getSuggestions = vi.fn((_query, requestSignal) => { + signal = requestSignal + return new Promise((resolver) => (resolve = resolver)) + }) + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await waitFor(() => + expect(getSuggestions).toHaveBeenLastCalledWith('abc', expect.any(AbortSignal)), + ) + await user.keyboard('{Escape}') + + expect(signal?.aborted).toBe(true) + await act(async () => resolve(['ABC-123'])) + + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(combobox()).toHaveAttribute('aria-expanded', 'false') + expect(combobox()).toHaveValue('abc') + }) + + it('cancels the debounce with Escape before a fetch starts', () => { + vi.useFakeTimers() + try { + const getSuggestions = vi.fn(filterCodes) + render() + + fireEvent.change(combobox(), { target: { value: 'abc' } }) + fireEvent.keyDown(combobox(), { key: 'Escape' }) + act(() => vi.advanceTimersByTime(250)) + + expect(getSuggestions).not.toHaveBeenCalled() + expect(combobox()).toHaveAttribute('aria-expanded', 'false') + expect(combobox()).toHaveValue('abc') + } finally { + vi.useRealTimers() + } + }) + + it('opens without choosing a suggestion with Alt+Down', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await screen.findAllByRole('option') + await user.keyboard('{Escape}{Alt>}{ArrowDown}{/Alt}') + + expect(combobox()).toHaveAttribute('aria-expanded', 'true') + expect(combobox()).not.toHaveAttribute('aria-activedescendant') + }) + + it('closes without selecting when the user tabs away', async () => { + const onBlur = vi.fn() + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await screen.findAllByRole('option') + await user.keyboard('{ArrowDown}') + await user.tab() + + expect(combobox()).toHaveValue('abc') + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(onBlur).toHaveBeenCalled() + }) + + it('does not open the suggestions when a fetch finishes after the user has left the field', async () => { + let resolve: (value: string[]) => void = () => undefined + let signal: AbortSignal | undefined + const getSuggestions = vi.fn((_query, requestSignal) => { + signal = requestSignal + return new Promise((resolver) => (resolve = resolver)) + }) + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await waitFor(() => expect(getSuggestions).toHaveBeenCalled()) + await user.tab() + resolve(['ABC-123']) + await Promise.resolve() + + expect(signal?.aborted).toBe(true) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(combobox()).toHaveAttribute('aria-expanded', 'false') + }) + + it('does not fetch when the user leaves the field before typing pauses', async () => { + const getSuggestions = vi.fn(filterCodes) + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await user.tab() + await new Promise((resolve) => setTimeout(resolve, 100)) + + expect(getSuggestions).not.toHaveBeenCalled() + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + }) + + it('does not offer the old suggestions again after one is chosen', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await user.click(await screen.findByRole('option', { name: 'ABC-123' })) + await user.keyboard('{ArrowDown}') + + expect(combobox()).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + }) + + it('changes the status text when two results in a row have the same count', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc-1') + await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('1 suggestion')) + const first = screen.getByRole('status').textContent + + await user.type(combobox(), '2') + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent('1 suggestion available.'), + ) + expect(screen.getByRole('status').textContent).not.toBe(first) + }) + + it('selects a suggestion with a click and keeps focus on the input', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + await user.click(await screen.findByRole('option', { name: 'XABC-9' })) + + expect(combobox()).toHaveValue('XABC-9') + expect(combobox()).toHaveFocus() + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + }) + + it('emphasises the part of each suggestion that matches the query', async () => { + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + + const option = await screen.findByRole('option', { name: 'XABC-9' }) + expect(option.querySelector('strong')).toHaveTextContent('ABC') + }) + + it('does not fetch until the query is long enough', async () => { + const getSuggestions = vi.fn(filterCodes) + const user = userEvent.setup() + render() + + await user.type(combobox(), ' a ') + expect(getSuggestions).not.toHaveBeenCalled() + + await user.type(combobox(), 'b') + await waitFor(() => expect(getSuggestions).toHaveBeenCalledWith('a b', expect.any(AbortSignal))) + }) + + it('fetches once typing pauses, aborting a request the user has typed past', async () => { + let resolveFirst: (value: string[]) => void = () => undefined + const signals: AbortSignal[] = [] + const getSuggestions = vi.fn((query, signal) => { + signals.push(signal) + return query === 'a' + ? new Promise((resolve) => (resolveFirst = resolve)) + : filterCodes(query, signal) + }) + const user = userEvent.setup() + render() + + await user.type(combobox(), 'a') + await waitFor(() => expect(getSuggestions).toHaveBeenCalledTimes(1)) + await user.type(combobox(), 'bc-4') + await screen.findByRole('option', { name: 'ABC-456' }) + + expect(signals[0].aborted).toBe(true) + resolveFirst(['STALE']) + await Promise.resolve() + expect(screen.queryByRole('option', { name: 'STALE' })).not.toBeInTheDocument() + }) + + it('stays a plain text input when suggestions cannot be fetched', async () => { + const getSuggestions = vi.fn(() => Promise.reject(new Error('Network'))) + const user = userEvent.setup() + render() + + await user.type(combobox(), 'abc') + + await waitFor(() => expect(getSuggestions).toHaveBeenCalled()) + expect(screen.queryByRole('listbox')).not.toBeInTheDocument() + expect(combobox()).toHaveValue('abc') + }) + + it('marks the input as invalid and associates its error message', () => { + render() + + expect(combobox()).toBeInvalid() + expect(combobox()).toHaveAccessibleDescription( + expect.stringContaining('Error: Enter company code'), + ) + }) + + it('applies the width to the field and its suggestions together', () => { + render() + + expect(combobox().parentElement?.style.width).toBe('66.6667%') + }) +}) diff --git a/frontend/src/components/Autocomplete/Autocomplete.tsx b/frontend/src/components/Autocomplete/Autocomplete.tsx new file mode 100644 index 000000000..76fe44cf8 --- /dev/null +++ b/frontend/src/components/Autocomplete/Autocomplete.tsx @@ -0,0 +1,336 @@ +'use client' + +import clsx from 'clsx' +import { useEffect, useRef, useState } from 'react' + +import '@nice-digital/nds-input/scss/input.scss' + +import { inputWidthStyles } from '@/components/Input/Input' +import type { InputWidth, LabelSize } from '@/components/Input/Input' + +import styles from './Autocomplete.module.scss' + +import type { KeyboardEvent, ReactNode, Ref } from 'react' + +/** Fetches the suggestions for a query. Abort the request when `signal` aborts. */ +export type GetSuggestions = (query: string, signal: AbortSignal) => Promise + +export type AutocompleteProps = { + className?: string + /** Milliseconds to wait after the last keystroke before fetching suggestions. */ + debounceMs?: number + error?: boolean + errorMessage?: string + getSuggestions: GetSuggestions + hint?: string + id?: string + inputRef?: Ref + label: string | null + /** As for `Input`: the standard bold label, or bold lead text on a page of several questions. */ + labelSize?: LabelSize + /** The fewest characters, ignoring surrounding spaces, that fetch suggestions. */ + minQueryLength?: number + name: string + onBlur?: () => void + onChange: (value: string) => void + value: string + /** As for `Input`: applied to the field, which the suggestions match in width. */ + width?: InputWidth +} + +const usageHint = + 'When suggestions are available, use up and down arrows to review and enter to select. ' + + 'Touch device users, explore by touch or with swipe gestures.' + +/** + * The status read out by screen readers. `alternate` adds a non-breaking space on alternate + * updates, so a result with the same count as the last one still changes the text and is read + * out again, as in GOV.UK's accessible-autocomplete. + */ +const statusText = (count: number, alternate: boolean) => + (count === 0 + ? 'No suggestions available.' + : `${count} ${count === 1 ? 'suggestion' : 'suggestions'} available.`) + + (alternate ? '\u00a0' : '') + +/** Emphasises the first part of the suggestion that matches the query, ignoring case. */ +const highlightMatch = (suggestion: string, query: string): ReactNode => { + const start = suggestion.toLowerCase().indexOf(query.toLowerCase()) + if (!query || start === -1) { + return suggestion + } + const end = start + query.length + return ( + <> + {suggestion.slice(0, start)} + {suggestion.slice(start, end)} + {suggestion.slice(end)} + + ) +} + +const isAbortError = (error: unknown) => + error instanceof DOMException && error.name === 'AbortError' + +/** + * A text input that suggests values as the user types, following the WAI-ARIA 1.2 combobox + * pattern with list autocomplete. Suggestions are optional: any text the user enters is kept. + * https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-list/ + */ +export function Autocomplete({ + className, + debounceMs = 250, + error, + errorMessage, + getSuggestions, + hint, + id, + inputRef, + label, + labelSize = 'default', + minQueryLength = 1, + name, + onBlur, + onChange, + value, + width, +}: AutocompleteProps) { + const inputId = id ?? name + const listboxId = `${inputId}-listbox` + const optionId = (index: number) => `${inputId}-option-${index}` + const hintId = hint ? `${inputId}-hint` : undefined + const errorId = error && errorMessage ? `${inputId}-error` : undefined + const usageHintId = `${inputId}-usage` + const describedBy = [hintId, errorId, usageHintId].filter(Boolean).join(' ') + + const [suggestions, setSuggestions] = useState([]) + const [query, setQuery] = useState('') + const [isOpen, setIsOpen] = useState(false) + const [activeIndex, setActiveIndex] = useState(-1) + const [status, setStatus] = useState('') + + const timer = useRef>(undefined) + const request = useRef(undefined) + const listbox = useRef(null) + const alternateStatus = useRef(false) + + const cancelPending = () => { + clearTimeout(timer.current) + request.current?.abort() + } + + useEffect(() => cancelPending, []) + + // Keep the active suggestion in view as the user arrows through a scrolling list. + useEffect(() => { + if (activeIndex >= 0) { + listbox.current?.children[activeIndex]?.scrollIntoView?.({ block: 'nearest' }) + } + }, [activeIndex]) + + const close = () => { + setIsOpen(false) + setActiveIndex(-1) + } + + const fetchSuggestions = (text: string) => { + cancelPending() + // Results and the active selection belong to the previous query, not the new input. + setSuggestions([]) + setStatus('') + close() + const trimmed = text.trim() + + if (trimmed.length < minQueryLength) { + return + } + + timer.current = setTimeout(() => { + const controller = new AbortController() + request.current = controller + + getSuggestions(trimmed, controller.signal).then( + (results) => { + if (controller.signal.aborted) { + return + } + alternateStatus.current = !alternateStatus.current + setSuggestions(results) + setQuery(trimmed) + setActiveIndex(-1) + setIsOpen(results.length > 0) + setStatus(statusText(results.length, alternateStatus.current)) + }, + (reason: unknown) => { + // Suggestions are optional, so a failure leaves a plain text input. + if (!isAbortError(reason) && !controller.signal.aborted) { + setSuggestions([]) + setStatus('') + close() + } + }, + ) + }, debounceMs) + } + + const select = (index: number) => { + cancelPending() + onChange(suggestions[index]) + // The suggestions were for the text before the choice, so they are not offered again. + setSuggestions([]) + setStatus('') + close() + } + + // Leaving the field also drops a fetch still waiting or running, so its results can't open + // the list under a field that no longer has focus. + const leave = () => { + cancelPending() + close() + } + + const handleKeyDown = (event: KeyboardEvent) => { + const count = suggestions.length + + switch (event.key) { + case 'ArrowDown': { + if (count === 0) { + return + } + event.preventDefault() + if (!isOpen) { + setIsOpen(true) + // Alt+Down opens the list without choosing a suggestion. + setActiveIndex(event.altKey ? -1 : 0) + return + } + // After the last suggestion, return to the text the user typed. + setActiveIndex((index) => (index + 1 >= count ? -1 : index + 1)) + return + } + case 'ArrowUp': { + if (count === 0) { + return + } + event.preventDefault() + if (!isOpen) { + setIsOpen(true) + setActiveIndex(count - 1) + return + } + setActiveIndex((index) => (index < 0 ? count - 1 : index - 1)) + return + } + case 'Enter': { + // Without an active suggestion, Enter submits the form as usual. + if (isOpen && activeIndex >= 0) { + event.preventDefault() + select(activeIndex) + } + return + } + case 'Escape': { + if (isOpen) { + event.preventDefault() + } + // Dismiss pending results too, even if the list has not opened yet. + cancelPending() + close() + setStatus('') + return + } + case 'Tab': { + leave() + return + } + } + } + + const expanded = isOpen && suggestions.length > 0 + + return ( +
+ {label && ( + + )} + {hint && ( +

+ {hint} +

+ )} + {errorId && ( +

+ Error: {errorMessage} +

+ )} +
+ = 0 ? optionId(activeIndex) : undefined} + aria-autocomplete="list" + aria-controls={listboxId} + aria-describedby={describedBy} + aria-expanded={expanded} + aria-invalid={error ? true : undefined} + autoCapitalize="none" + autoComplete="off" + className={clsx('input__input', styles.input)} + id={inputId} + name={name} + onBlur={() => { + leave() + onBlur?.() + }} + onChange={(event) => { + onChange(event.target.value) + fetchSuggestions(event.target.value) + }} + onKeyDown={handleKeyDown} + ref={inputRef} + role="combobox" + spellCheck={false} + type="text" + value={value} + /> + +
+

+ {usageHint} +

+
+ {status} +
+
+ ) +} diff --git a/frontend/src/components/DynamicForm/FormPage.test.tsx b/frontend/src/components/DynamicForm/FormPage.test.tsx index 388e452bd..472ccc5f7 100644 --- a/frontend/src/components/DynamicForm/FormPage.test.tsx +++ b/frontend/src/components/DynamicForm/FormPage.test.tsx @@ -9,6 +9,7 @@ import { FormPage } from './FormPage' const mocks = vi.hoisted(() => ({ push: vi.fn(), saveRecordFormPage: vi.fn(), + getOrganisationCompanyCodes: vi.fn(), })) vi.mock('next/navigation', () => ({ @@ -17,7 +18,11 @@ vi.mock('next/navigation', () => ({ vi.mock('@/client/generated', async (importOriginal) => { const original = await importOriginal() - return { ...original, saveRecordFormPage: mocks.saveRecordFormPage } + return { + ...original, + saveRecordFormPage: mocks.saveRecordFormPage, + getOrganisationCompanyCodes: mocks.getOrganisationCompanyCodes, + } }) const question = (overrides: Partial): RecordPageQuestionDto => ({ @@ -55,6 +60,7 @@ const page = (overrides: Partial = {}): RecordPageDto => ({ formVersion: '2026.10.1', pageHash: 'page-hash', recordId: 5, + organisationId: 3, section: { id: 'product-indication', title: 'Product indication' }, task: { id: 'indication-details', title: 'Indication details' }, page: { id: 'indication', title: 'Indication', commercialInConfidence: false }, @@ -2022,6 +2028,97 @@ describe('FormPage names and identifiers', () => { expect(mocks.saveRecordFormPage).not.toHaveBeenCalled() }) + describe('company code', () => { + const companyCode = question({ + id: 'record_product_detail.company_code', + type: 'Text', + label: 'Company code', + hint: 'Enter the primary internal code or working name your company uses.', + display: 'autocomplete:company-codes', + rules: [{ kind: 'Required', value: null, message: 'Enter company code' }], + }) + + const companyCodePage = (overrides: Partial = {}) => + page({ + ...namesPage(), + questions: [{ ...companyCode, ...overrides }, genericNames], + answers: { [companyCode.id]: 'ABC', [genericNames.id]: ['sofosbuvir'] }, + }) + + beforeEach(() => { + mocks.getOrganisationCompanyCodes.mockResolvedValue({ + data: { items: ['ABC-123', 'ABC-456'] }, + }) + }) + + it("suggests the organisation's company codes and saves the one chosen", async () => { + const user = userEvent.setup() + render() + + const input = screen.getByRole('combobox', { name: 'Company code' }) + expect(input).toHaveValue('ABC') + await user.type(input, '-4') + await user.click(await screen.findByRole('option', { name: 'ABC-456' })) + saveAndReturn() + + await waitFor(() => expect(mocks.saveRecordFormPage).toHaveBeenCalledTimes(1)) + expect(mocks.getOrganisationCompanyCodes).toHaveBeenCalledWith( + expect.objectContaining({ + path: { organisationId: 3 }, + query: expect.objectContaining({ Search: 'ABC-4' }), + }), + ) + expect(sentAnswers()).toEqual({ + [companyCode.id]: 'ABC-456', + [genericNames.id]: ['sofosbuvir'], + }) + }) + + it('saves a company code that is not among the suggestions', async () => { + const user = userEvent.setup() + render() + + const input = screen.getByRole('combobox', { name: 'Company code' }) + await user.clear(input) + await user.type(input, 'NEW-1') + saveAndReturn() + + await waitFor(() => expect(mocks.saveRecordFormPage).toHaveBeenCalledTimes(1)) + expect(sentAnswers()).toMatchObject({ [companyCode.id]: 'NEW-1' }) + }) + + it('still requires a company code', async () => { + const user = userEvent.setup() + render() + + await user.clear(screen.getByRole('combobox', { name: 'Company code' })) + saveAndReturn() + + expect(await screen.findByText('Enter company code', { selector: 'p *, p' })).toBeVisible() + expect(mocks.saveRecordFormPage).not.toHaveBeenCalled() + }) + + it('is a plain text input without the autocomplete display hint', () => { + render() + + expect(screen.queryByRole('combobox')).not.toBeInTheDocument() + expect(screen.getByRole('textbox', { name: 'Company code' })).toHaveValue('ABC') + }) + + it('is a plain text input when the display hint names an unknown source', () => { + render() + + expect(screen.queryByRole('combobox')).not.toBeInTheDocument() + expect(screen.getByRole('textbox', { name: 'Company code' })).toHaveValue('ABC') + }) + + it('is a plain text input for the bare autocomplete hint, which names no source', () => { + render() + + expect(screen.queryByRole('combobox')).not.toBeInTheDocument() + }) + }) + it('shows a server error on an entry against the entry it names', async () => { mocks.saveRecordFormPage.mockResolvedValue({ error: { errors: { [`${genericNames.id}[1]`]: ['Server says this one is repeated'] } }, diff --git a/frontend/src/components/DynamicForm/FormPage.tsx b/frontend/src/components/DynamicForm/FormPage.tsx index 27f02d1d5..695fe3058 100644 --- a/frontend/src/components/DynamicForm/FormPage.tsx +++ b/frontend/src/components/DynamicForm/FormPage.tsx @@ -28,6 +28,7 @@ import { import { isValidationProblemDetails } from '@/lib/responses/typeGuards' import styles from './DynamicForm.module.scss' +import { FormPageContextProvider } from './FormPageContext' import { questionRegistry } from './questionRegistry' import type { LabelStyle } from './labelStyle' @@ -62,6 +63,7 @@ export function FormPage({ const [otherErrors, setOtherErrors] = useState([]) const schema = useMemo(() => buildZodSchema(questions), [questions]) const layout = useMemo(() => pageLayout(questions), [questions]) + const context = useMemo(() => ({ organisationId: page.organisationId }), [page.organisationId]) // A page whose other questions are all revealed beneath one question reads as a // single-question page. const singleQuestion = layout.topLevel.length === 1 @@ -143,7 +145,7 @@ export function FormPage({ ) return ( - <> + {saveState.kind === 'conflict' && ( @@ -258,6 +260,6 @@ export function FormPage({ Return to {exitLabel} - + ) } diff --git a/frontend/src/components/DynamicForm/FormPageContext.tsx b/frontend/src/components/DynamicForm/FormPageContext.tsx new file mode 100644 index 000000000..4bcfbf4fc --- /dev/null +++ b/frontend/src/components/DynamicForm/FormPageContext.tsx @@ -0,0 +1,21 @@ +'use client' + +import { createContext, useContext } from 'react' + +export type FormPageContextValue = { + /** + * The organisation that owns the record, for suggestions such as its company codes. + * + * `FormPage` always provides it, from `RecordPageDto.organisationId`. It is optional so that a + * question rendered outside a form page, such as in a component test or the component library, + * still works: without it, questions that would offer suggestions fall back to plain inputs. + */ + organisationId?: number +} + +const FormPageContext = createContext({}) + +export const FormPageContextProvider = FormPageContext.Provider + +/** The record context of the form page a question is rendered on. */ +export const useFormPageContext = () => useContext(FormPageContext) diff --git a/frontend/src/components/DynamicForm/questions/TextQuestion.tsx b/frontend/src/components/DynamicForm/questions/TextQuestion.tsx index 590056347..04d298f2e 100644 --- a/frontend/src/components/DynamicForm/questions/TextQuestion.tsx +++ b/frontend/src/components/DynamicForm/questions/TextQuestion.tsx @@ -1,5 +1,10 @@ +import { useMemo } from 'react' + +import { Autocomplete } from '@/components/Autocomplete/Autocomplete' import { Input } from '@/components/Input/Input' +import { getSuggestionSource } from '@/lib/dynamic-form/suggestionSources' +import { useFormPageContext } from '../FormPageContext' import { labelSizeFor } from '../labelStyle' import type { QuestionProps } from '../types' @@ -14,6 +19,28 @@ export function TextQuestion({ labelStyle, }: QuestionProps) { const labelAsHeading = labelStyle === 'heading' + const { organisationId } = useFormPageContext() + // A text question whose display hint names an autocomplete source suggests values from it. + const getSuggestions = useMemo( + () => + organisationId === undefined + ? undefined + : getSuggestionSource(question.display, organisationId), + [question.display, organisationId], + ) + + const fieldProps = { + error: Boolean(error), + errorMessage: error, + hint: question.hint ?? undefined, + label: labelAsHeading ? null : question.label, + labelSize: labelSizeFor(labelStyle), + name, + onBlur, + value, + width: 'two-thirds', + } as const + return ( <> {labelAsHeading && ( @@ -21,18 +48,11 @@ export function TextQuestion({ {question.label} )} - onChange(event.target.value)} - value={value} - width="two-thirds" - /> + {getSuggestions ? ( + + ) : ( + onChange(event.target.value)} /> + )} ) } diff --git a/frontend/src/lib/dynamic-form/suggestionSources.ts b/frontend/src/lib/dynamic-form/suggestionSources.ts new file mode 100644 index 000000000..d5b0c3eed --- /dev/null +++ b/frontend/src/lib/dynamic-form/suggestionSources.ts @@ -0,0 +1,28 @@ +import type { GetSuggestions } from '@/components/Autocomplete/Autocomplete' +import { getCompanyCodeSuggestions } from '@/lib/form/companyCodeSuggestions' + +/** + * The prefix of the display hint that asks for a text question to suggest values as the user + * types. The rest of the hint names the source, as in `autocomplete:company-codes`. + */ +const autocompleteDisplayPrefix = 'autocomplete:' + +/** Where autocomplete questions get their suggestions, keyed by the source named in the hint. */ +const suggestionSources: Partial GetSuggestions>> = { + 'company-codes': getCompanyCodeSuggestions, +} + +/** + * The suggestions for a question whose display hint names a known autocomplete source, or + * undefined otherwise, so it is shown as a plain text input. + */ +export const getSuggestionSource = ( + display: string | null | undefined, + organisationId: number, +): GetSuggestions | undefined => { + if (!display?.startsWith(autocompleteDisplayPrefix)) { + return undefined + } + const source = display.slice(autocompleteDisplayPrefix.length) + return suggestionSources[source]?.(organisationId) +} diff --git a/frontend/src/lib/form/companyCodeSuggestions.ts b/frontend/src/lib/form/companyCodeSuggestions.ts new file mode 100644 index 000000000..b6036ac9b --- /dev/null +++ b/frontend/src/lib/form/companyCodeSuggestions.ts @@ -0,0 +1,20 @@ +import { getOrganisationCompanyCodes } from '@/client/generated' +import type { GetSuggestions } from '@/components/Autocomplete/Autocomplete' + +/** How many company codes to suggest at once. */ +export const companyCodeSuggestionLimit = 10 + +/** + * Suggests the company codes already used on the organisation's records that contain the query. + * Suggestions are optional, so a failed request suggests nothing rather than showing an error. + */ +export const getCompanyCodeSuggestions = + (organisationId: number): GetSuggestions => + async (query, signal) => { + const { data } = await getOrganisationCompanyCodes({ + path: { organisationId }, + query: { Search: query, Limit: companyCodeSuggestionLimit }, + signal, + }) + return data?.items ?? [] + } From c137a1d6de873bf7a4124a255a2a0c132e6c41d0 Mon Sep 17 00:00:00 2001 From: SmithR-IS Date: Fri, 20 Nov 2026 15:22:28 +0000 Subject: [PATCH 2/2] Add TODO to restrict company code suggestions to the current record type --- backend/src/Application/Records/RecordService.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/src/Application/Records/RecordService.cs b/backend/src/Application/Records/RecordService.cs index d3ebd263c..1805ee205 100644 --- a/backend/src/Application/Records/RecordService.cs +++ b/backend/src/Application/Records/RecordService.cs @@ -129,6 +129,8 @@ CancellationToken cancellationToken // Discarded records are hidden by the records query filter. An organisation has one code // per record, so the matches are few enough to rank in memory. + // TODO: when vaccine records are built, only suggest codes from records of the same type + // (medicine or vaccine) as the one being populated, still scoped to the organisation. List matches = await JoinProductDetails(GetBaseRecordProjection()) .Where(x => x.OrganisationId == organisationId