From 6eea962f9128de1032425f3d72d01593cdfc812c Mon Sep 17 00:00:00 2001 From: Jimmy Palelil BCGOV Date: Fri, 27 Nov 2026 13:29:52 -0700 Subject: [PATCH] fix(api,web): REGBACKLOG-445 debounce account search and cache service token --- strr-api/poetry.lock | 2 +- strr-api/pyproject.toml | 3 +- .../src/strr_api/services/auth_service.py | 59 +++-- .../tests/unit/services/test_auth_service.py | 84 +++++++ .../app/pages/auth/account/create-new.vue | 111 +++++++-- strr-host-pm-web/package.json | 2 +- .../tests/e2e/create-new-account.test.ts | 93 ++++++++ .../tests/e2e/test-utils/auth-setup.ts | 2 +- .../unit/create-new-account-page.spec.ts | 219 ++++++++++++++++++ 9 files changed, 533 insertions(+), 42 deletions(-) create mode 100644 strr-host-pm-web/tests/e2e/create-new-account.test.ts create mode 100644 strr-host-pm-web/tests/unit/create-new-account-page.spec.ts diff --git a/strr-api/poetry.lock b/strr-api/poetry.lock index d13a6c98d..9b8cfbb4d 100644 --- a/strr-api/poetry.lock +++ b/strr-api/poetry.lock @@ -5187,4 +5187,4 @@ test = ["pytest"] [metadata] lock-version = "2.1" python-versions = ">=3.12.2,<3.15" -content-hash = "6ee0e053ec02ca3da29f1bca0b516e3b18326294c706609dcc8364bfae76320d" +content-hash = "fda33a73b552e1f00c31241c0c13a35f8ccd9be5ff52e3b76d3cfe881d7a7357" diff --git a/strr-api/pyproject.toml b/strr-api/pyproject.toml index b3a18205a..537308b30 100644 --- a/strr-api/pyproject.toml +++ b/strr-api/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "strr-api" -version = "0.3.46" +version = "0.3.47" description = "" authors = ["thorwolpert "] license = "BSD 3-Clause" @@ -38,6 +38,7 @@ nanoid = "^2.0.0" sql-versioning = { git = "https://github.com/bcgov/sbc-connect-common.git", subdirectory = "python/sql-versioning", branch = "main" } gcp-queue = { git = "https://github.com/bcgov/sbc-connect-common.git", subdirectory = "python/gcp-queue", branch = "main" } testcontainers = "^4.14.0" +cachelib = "^0.13.0" [tool.poetry.group.test.dependencies] freezegun = "^1.2.2" diff --git a/strr-api/src/strr_api/services/auth_service.py b/strr-api/src/strr_api/services/auth_service.py index a44558b9e..d7b836857 100644 --- a/strr-api/src/strr_api/services/auth_service.py +++ b/strr-api/src/strr_api/services/auth_service.py @@ -33,9 +33,12 @@ # POSSIBILITY OF SUCH DAMAGE. """Manages Auth service interactions.""" +import hashlib +import threading from http import HTTPStatus import requests +from cachelib import SimpleCache from flask import current_app from requests.exceptions import HTTPError @@ -49,6 +52,21 @@ class AuthService: """Wrapper service to interact with the Auth API.""" + _DEFAULT_TOKEN_TTL = 270 + _token_cache = SimpleCache(default_timeout=_DEFAULT_TOKEN_TTL) + _token_lock = threading.Lock() + + @staticmethod + def _compute_token_ttl(expires_in) -> int | None: + """Compute safe cache TTL in seconds, or None if the token should not be cached.""" + if expires_in is None: + return AuthService._DEFAULT_TOKEN_TTL + try: + ttl = int(expires_in) + except (TypeError, ValueError): + return None + return ttl - min(30, ttl // 5) if ttl > 0 else None + @classmethod def get_service_client_token( cls, @@ -67,27 +85,40 @@ def get_service_client_token( if timeout is None: timeout = int(current_app.config.get("AUTH_SVC_TIMEOUT", 20)) - data = "grant_type=client_credentials" + cache_key = hashlib.sha256(f"{client_id}:{client_secret}:{token_url}".encode()).hexdigest() + if cached_token := cls._token_cache.get(cache_key): + return cached_token - # get service account token - res = requests.post( - url=token_url, - data=data, - headers={"content-type": "application/x-www-form-urlencoded"}, - auth=(client_id, client_secret), - timeout=timeout, - ) + with cls._token_lock: + if cached_token := cls._token_cache.get(cache_key): + return cached_token - try: - return res.json().get("access_token") - except Exception: - return None + res = requests.post( + url=token_url, + data="grant_type=client_credentials", + headers={"content-type": "application/x-www-form-urlencoded"}, + auth=(client_id, client_secret), + timeout=timeout, + ) + + try: + token_data = res.json() + access_token = token_data.get("access_token") + except Exception: + return None + + if not access_token: + return None + + if ttl := cls._compute_token_ttl(token_data.get("expires_in")): + cls._token_cache.set(cache_key, access_token, timeout=ttl) + + return access_token @classmethod def search_accounts(cls, account_name: str): """Searches for an existing account.""" token = AuthService.get_service_client_token() - print(token) endpoint = f"{current_app.config.get('AUTH_SVC_URL')}/orgs?name={account_name.strip()}" accounts = RestService.get(endpoint=endpoint, token=token).json() return accounts diff --git a/strr-api/tests/unit/services/test_auth_service.py b/strr-api/tests/unit/services/test_auth_service.py index 1d870f9db..3becdde55 100644 --- a/strr-api/tests/unit/services/test_auth_service.py +++ b/strr-api/tests/unit/services/test_auth_service.py @@ -4,6 +4,8 @@ # you may not use this file except in compliance with the License. """Tests for AuthService (HTTP/RestService mocked).""" +import threading +import time from http import HTTPStatus from unittest.mock import MagicMock, patch @@ -14,6 +16,14 @@ from strr_api.services.auth_service import AuthService +@pytest.fixture(autouse=True) +def clear_token_cache(): + """Ensure service client token cache is isolated per test.""" + AuthService._token_cache.clear() + yield + AuthService._token_cache.clear() + + @patch("strr_api.services.auth_service.requests.post") def test_get_service_client_token_success(mock_post, app_ctx): mock_post.return_value.json.return_value = {"access_token": "tok"} @@ -23,6 +33,80 @@ def test_get_service_client_token_success(mock_post, app_ctx): assert token == "tok" +@patch("strr_api.services.auth_service.requests.post") +def test_get_service_client_token_caches_within_ttl(mock_post, app_ctx): + mock_post.return_value.json.return_value = {"access_token": "cached-tok", "expires_in": 300} + + first = AuthService.get_service_client_token("id", "sec", "https://token") + second = AuthService.get_service_client_token("id", "sec", "https://token") + + assert first == "cached-tok" + assert second == "cached-tok" + mock_post.assert_called_once() + + +@patch("strr_api.services.auth_service.requests.post") +def test_get_service_client_token_refreshes_near_expiry(mock_post, app_ctx): + mock_post.side_effect = [ + MagicMock(json=MagicMock(return_value={"access_token": "tok-1", "expires_in": 300})), + MagicMock(json=MagicMock(return_value={"access_token": "tok-2", "expires_in": 300})), + ] + now = [1000.0] + + with patch("cachelib.simple.time", side_effect=lambda: now[0]): + first = AuthService.get_service_client_token("id", "sec", "https://token") + now[0] = 1275.0 # past 300 - 30 = 270s cached TTL + second = AuthService.get_service_client_token("id", "sec", "https://token") + + assert first == "tok-1" + assert second == "tok-2" + assert mock_post.call_count == 2 + + +@patch("strr_api.services.auth_service.requests.post") +def test_get_service_client_token_does_not_cache_zero_ttl(mock_post, app_ctx): + mock_post.return_value.json.return_value = {"access_token": "ephemeral", "expires_in": 0} + + AuthService.get_service_client_token("id", "sec", "https://token") + AuthService.get_service_client_token("id", "sec", "https://token") + + assert mock_post.call_count == 2 + + +@patch("strr_api.services.auth_service.requests.post") +def test_get_service_client_token_invalid_expires_in_still_returns_token(mock_post, app_ctx): + mock_post.return_value.json.return_value = {"access_token": "tok-raw", "expires_in": ""} + + first = AuthService.get_service_client_token("id", "sec", "https://token") + second = AuthService.get_service_client_token("id", "sec", "https://token") + + assert first == "tok-raw" + assert second == "tok-raw" + assert mock_post.call_count == 2 + + +@patch("strr_api.services.auth_service.requests.post") +def test_get_service_client_token_coalesces_concurrent_fetches(mock_post, app_ctx): + def slow_post(*_args, **_kwargs): + time.sleep(0.05) + return MagicMock(json=MagicMock(return_value={"access_token": "shared-tok", "expires_in": 300})) + + mock_post.side_effect = slow_post + results: list[str] = [] + + def worker(): + results.append(AuthService.get_service_client_token("id", "sec", "https://token", timeout=5)) + + threads = [threading.Thread(target=worker) for _ in range(5)] + for t in threads: + t.start() + for t in threads: + t.join() + + assert results == ["shared-tok"] * 5 + mock_post.assert_called_once() + + @patch("strr_api.services.auth_service.requests.post") def test_get_service_client_token_json_failure_returns_none(mock_post, app_ctx): mock_post.return_value.json.side_effect = ValueError("bad json") diff --git a/strr-host-pm-web/app/pages/auth/account/create-new.vue b/strr-host-pm-web/app/pages/auth/account/create-new.vue index abe2a2f7e..ff2f755f5 100644 --- a/strr-host-pm-web/app/pages/auth/account/create-new.vue +++ b/strr-host-pm-web/app/pages/auth/account/create-new.vue @@ -34,9 +34,72 @@ const state = reactive({ const createAccountFormRef = ref>() +const MIN_ACCOUNT_NAME_SEARCH_LENGTH = 3 +const ACCOUNT_NAME_DEBOUNCE_MS = 450 +let debounceTimer: ReturnType | null = null +let accountSearchAbortController: AbortController | null = null + +function cancelPendingAccountNameSearch () { + if (debounceTimer !== null) { + clearTimeout(debounceTimer) + debounceTimer = null + } + if (accountSearchAbortController) { + accountSearchAbortController.abort() + accountSearchAbortController = null + } +} + +function isAbortError (err: unknown): boolean { + if (!(err instanceof Error)) { + return false + } + return err.name === 'AbortError' || (err as { cause?: { name?: string } }).cause?.name === 'AbortError' +} + +async function checkAccountNameExists (trimmedName: string): Promise { + cancelPendingAccountNameSearch() + const controller = new AbortController() + accountSearchAbortController = controller + + try { + loadingCheckAccountName.value = true + // also returns limit: number, orgs: Array, page: number, but we only need the total here + const { total } = await $strrApi<{ total: number }>('/accounts/search', { // TODO: move function to store/composable? + params: { name: trimmedName }, + signal: controller.signal + }) + if (controller.signal.aborted) { + return false + } + accountExists.value = total > 0 + return true + } catch (e) { + if (controller.signal.aborted || isAbortError(e)) { + return false + } + logFetchError(e, 'Error checking if account name exists') + accountExists.value = true // assume account exists if api error + return true + } finally { + if (accountSearchAbortController === controller) { + accountSearchAbortController = null + loadingCheckAccountName.value = false + } + } +} + async function handleCreateAccount () { try { loadingSubmitForm.value = true + const trimmedName = state.accountName.trim() + if (trimmedName.length < MIN_ACCOUNT_NAME_SEARCH_LENGTH || loadingCheckAccountName.value) { + const completed = await checkAccountNameExists(trimmedName) + if (!completed || accountExists.value || state.accountName.trim() !== trimmedName) { + createAccountFormRef.value?.validate('accountName', { silent: true }) + return + } + } const response = await $strrApi<{sbc_account_id: number, user_id: number}>('/accounts', { // TODO: move function to store/composable? method: 'POST', body: { @@ -60,33 +123,33 @@ async function handleCreateAccount () { } } -// validate account name already exists -watchDebounced( - () => state.accountName, - async (newVal) => { - if (newVal.trim() !== '') { - try { - loadingCheckAccountName.value = true - // also returns limit: number, orgs: Array, page: number, but we only need the total here - const { total } = await $strrApi<{ total: number }>('/accounts/search', { // TODO: move function to store/composable? - params: { name: newVal } - }) - accountExists.value = total > 0 - } catch (e) { - logFetchError(e, 'Error checking if account name exists') - accountExists.value = true // assume account exists if api error - } finally { - loadingCheckAccountName.value = false - } - } else { - accountExists.value = false // set to false if accountName is empty +// Validate account name existence on trimmed changes, keeping Save disabled while a search is pending +watch( + () => state.accountName.trim(), + (trimmedName) => { + cancelPendingAccountNameSearch() + accountExists.value = false + + if (trimmedName.length < MIN_ACCOUNT_NAME_SEARCH_LENGTH) { + loadingCheckAccountName.value = false + createAccountFormRef.value?.validate('accountName', { silent: true }) + return } - // revalidate input after accountExists ref is updated - createAccountFormRef.value?.validate('accountName', { silent: true }) - }, - { debounce: 150 } // short debounce to get the 'on input' real time validation, this may need to be tweaked + + loadingCheckAccountName.value = true + debounceTimer = setTimeout(async () => { + debounceTimer = null + if (await checkAccountNameExists(trimmedName)) { + createAccountFormRef.value?.validate('accountName', { silent: true }) + } + }, ACCOUNT_NAME_DEBOUNCE_MS) + } ) +onScopeDispose(() => { + cancelPendingAccountNameSearch() +}) + useHead({ title: t('page.createAccount.title') }) diff --git a/strr-host-pm-web/package.json b/strr-host-pm-web/package.json index 0503a1272..037eec21e 100644 --- a/strr-host-pm-web/package.json +++ b/strr-host-pm-web/package.json @@ -2,7 +2,7 @@ "name": "strr-host-pm-web", "private": true, "type": "module", - "version": "1.3.38", + "version": "1.3.39", "engines": { "node": ">=24" }, diff --git a/strr-host-pm-web/tests/e2e/create-new-account.test.ts b/strr-host-pm-web/tests/e2e/create-new-account.test.ts new file mode 100644 index 000000000..8224c34d6 --- /dev/null +++ b/strr-host-pm-web/tests/e2e/create-new-account.test.ts @@ -0,0 +1,93 @@ +import { test, expect, type Locator, type Page } from '@playwright/test' +import { enI18n } from '~~/tests/mocks/i18n' + +const i18nText = enI18n.global.messages.value['en-CA'] +const DEBOUNCE_SETTLE_MS = 600 +const SEARCH_RESPONSE_TIMEOUT_MS = 15000 + +async function waitForDebounceWindow (page: Page) { + await page.evaluate(ms => new Promise(resolve => setTimeout(resolve, ms)), DEBOUNCE_SETTLE_MS) +} + +async function searchAccountAndGetTotal ( + page: Page, + input: Locator, + name: string, + { sequential = false } = {} +): Promise { + const responsePromise = page.waitForResponse( + res => res.url().includes('/accounts/search') && + res.request().method() === 'GET' && + new URL(res.url()).searchParams.get('name') === name, + { timeout: SEARCH_RESPONSE_TIMEOUT_MS } + ) + if (sequential) { + await input.fill('') + await input.pressSequentially(name, { delay: 30 }) + } else { + await input.fill(name) + } + const response = await responsePromise + expect(response.status()).toBe(200) + const body = await response.json() + return body.total +} + +test.describe('Create New Account - Account Name Search', () => { + test.use({ storageState: 'tests/e2e/.auth/bcsc-user.json' }) + + test('enforces min length, debounces typing, and validates account names', async ({ page }, testInfo) => { + const existingAccountName = process.env.PLAYWRIGHT_TEST_BCSC_PREMIUM_ACCOUNT_NAME + // Environment-specific fixture required to verify existing-account duplicate detection + testInfo.skip(!existingAccountName, 'PLAYWRIGHT_TEST_BCSC_PREMIUM_ACCOUNT_NAME is required') + + const searchRequests: string[] = [] + page.on('request', (req) => { + if (req.url().includes('/accounts/search')) { + searchRequests.push(req.url()) + } + }) + + await page.goto('/en-CA/auth/account/create-new', { waitUntil: 'domcontentloaded' }) + + const accountNameInput = page.getByPlaceholder(i18nText.label.accountName) + await expect(accountNameInput).toBeVisible({ timeout: SEARCH_RESPONSE_TIMEOUT_MS }) + const existsError = page.getByText(i18nText.validation.accountName.exists) + + // 1. Fewer than 3 characters should not trigger /accounts/search + await accountNameInput.fill('A') + await waitForDebounceWindow(page) + await accountNameInput.fill('AB') + await waitForDebounceWindow(page) + expect(searchRequests).toHaveLength(0) + + // 2. Rapid typing should debounce and avoid firing a request per keystroke + const existingTotal = await searchAccountAndGetTotal(page, accountNameInput, existingAccountName!, { + sequential: true + }) + expect(existingTotal).toBeGreaterThan(0) + expect(searchRequests.length).toBeLessThanOrEqual(2) + await expect(existsError).toBeVisible() + + // Appending trailing whitespace should not trigger an extra /accounts/search request + const countBeforeWhitespace = searchRequests.length + await accountNameInput.fill(`${existingAccountName} `) + await waitForDebounceWindow(page) + expect(searchRequests).toHaveLength(countBeforeWhitespace) + + // 3. Unique account name should clear the existing-account validation error + const uniqueTotal = await searchAccountAndGetTotal(page, accountNameInput, `E2EUniqueAcct${Date.now()}`) + expect(uniqueTotal).toBe(0) + await expect(existsError).not.toBeVisible() + + // 4. Re-entering existing name then dropping below 3 chars clears error immediately without searching + await searchAccountAndGetTotal(page, accountNameInput, existingAccountName!) + await expect(existsError).toBeVisible() + + const countBeforeShort = searchRequests.length + await accountNameInput.fill('XY') + await waitForDebounceWindow(page) + expect(searchRequests).toHaveLength(countBeforeShort) + await expect(existsError).not.toBeVisible() + }) +}) diff --git a/strr-host-pm-web/tests/e2e/test-utils/auth-setup.ts b/strr-host-pm-web/tests/e2e/test-utils/auth-setup.ts index 48eedf7ea..55c5172df 100644 --- a/strr-host-pm-web/tests/e2e/test-utils/auth-setup.ts +++ b/strr-host-pm-web/tests/e2e/test-utils/auth-setup.ts @@ -32,7 +32,7 @@ export async function authSetup ( // permanent TOS as of Summer 2025 const agreeToTerms = page.getByText('I agree to the BC Login') - if (agreeToTerms) { + if (await agreeToTerms.waitFor({ state: 'visible', timeout: 5000 }).then(() => true).catch(() => false)) { await agreeToTerms.click() await page.getByRole('button', { name: 'Continue' }).click() } diff --git a/strr-host-pm-web/tests/unit/create-new-account-page.spec.ts b/strr-host-pm-web/tests/unit/create-new-account-page.spec.ts new file mode 100644 index 000000000..306a959e7 --- /dev/null +++ b/strr-host-pm-web/tests/unit/create-new-account-page.spec.ts @@ -0,0 +1,219 @@ +import { mountSuspended, mockNuxtImport } from '@nuxt/test-utils/runtime' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { baseEnI18n } from '../mocks/i18n' +import CreateNewAccountPage from '~/pages/auth/account/create-new.vue' + +const { + mockStrrApi, + mockLogFetchError +} = vi.hoisted(() => ({ + mockStrrApi: vi.fn(), + mockLogFetchError: vi.fn() +})) + +mockNuxtImport('useStrrModals', () => () => ({ + openErrorModal: vi.fn() +})) + +mockNuxtImport('useHostPmModals', () => () => ({ + openHelpCreateAccountModal: vi.fn() +})) + +mockNuxtImport('useConnectAccountStore', () => () => ({ + setAccountInfo: vi.fn(), + switchCurrentAccount: vi.fn() +})) + +mockNuxtImport('useStrrContactStore', () => () => ({ + compPartySchema: z.object({ + firstName: z.string().optional(), + lastName: z.string().optional(), + emailAddress: z.string().optional(), + phone: z.object({ + countryCode: z.string().optional(), + number: z.string().optional(), + extension: z.string().optional() + }).optional() + }), + completingParty: ref({ + firstName: 'Jane', + lastName: 'Doe', + emailAddress: 'jane@example.com', + phone: { countryCode: '1', number: '2505550100', extension: '' } + }) +})) + +mockNuxtImport('logFetchError', () => mockLogFetchError) + +describe('Create New Account Page - Account Name Search', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + const nuxtApp = useNuxtApp() + nuxtApp.$strrApi = mockStrrApi as any + }) + + afterEach(() => { + vi.useRealTimers() + }) + + async function mountPage () { + return await mountSuspended(CreateNewAccountPage, { + global: { + plugins: [baseEnI18n], + mocks: { + $keycloak: { tokenParsed: { loginSource: 'BCSC' } } + }, + stubs: { + ConnectTypographyH1: true, + ConnectPageSection: { template: '
' }, + ConnectFormSection: { template: '
' }, + ConnectFormFieldGroup: { + props: ['modelValue'], + emits: ['update:modelValue'], + template: [ + '' + ].join(' ') + }, + FormCommonContact: true, + UForm: { + methods: { + getErrors: () => [], + validate: () => Promise.resolve() + }, + emits: ['submit'], + template: '
' + }, + UButton: { + props: ['disabled', 'loading', 'label'], + template: '' + } + } + } + }) + } + + it('does not call /accounts/search when input has fewer than 3 characters', async () => { + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('A') + await vi.advanceTimersByTimeAsync(500) + await input.setValue('AB') + await vi.advanceTimersByTimeAsync(500) + await input.setValue(' A ') + await vi.advanceTimersByTimeAsync(500) + + expect(mockStrrApi).not.toHaveBeenCalled() + }) + + it('waits at least 400ms after typing stops before calling /accounts/search', async () => { + mockStrrApi.mockResolvedValue({ total: 0 }) + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('Acme') + await vi.advanceTimersByTimeAsync(399) + expect(mockStrrApi).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(100) + expect(mockStrrApi).toHaveBeenCalledTimes(1) + expect(mockStrrApi).toHaveBeenCalledWith('/accounts/search', expect.objectContaining({ + params: { name: 'Acme' }, + signal: expect.any(AbortSignal) + })) + }) + + it('cancels in-flight /accounts/search request when subsequent characters are typed', async () => { + let capturedSignal: AbortSignal | undefined + mockStrrApi.mockImplementation((_url: string, opts: { signal?: AbortSignal }) => { + capturedSignal = opts.signal + return new Promise((_resolve, reject) => { + opts.signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')) + }) + }) + }) + + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('Acm') + await vi.advanceTimersByTimeAsync(450) + expect(mockStrrApi).toHaveBeenCalledTimes(1) + expect(capturedSignal?.aborted).toBe(false) + + // Typing another character immediately aborts the in-flight request + await input.setValue('Acme') + expect(capturedSignal?.aborted).toBe(true) + expect(mockLogFetchError).not.toHaveBeenCalled() + + // New request fires after debounce + mockStrrApi.mockResolvedValueOnce({ total: 0 }) + await vi.advanceTimersByTimeAsync(450) + expect(mockStrrApi).toHaveBeenCalledTimes(2) + }) + + it('keeps Save disabled while debounced search is pending for >= 3 characters', async () => { + mockStrrApi.mockResolvedValue({ total: 0 }) + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('Acme') + const submitBtn = wrapper.findAll('button').find(b => b.text().includes('Save')) + expect(submitBtn?.attributes('disabled')).toBeDefined() + + await vi.advanceTimersByTimeAsync(450) + expect(submitBtn?.attributes('disabled')).toBeUndefined() + }) + + it('checks short (< 3 char) account names on submit and blocks duplicate POST', async () => { + mockStrrApi.mockResolvedValueOnce({ total: 1 }) + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('AB') + await vi.advanceTimersByTimeAsync(500) + expect(mockStrrApi).not.toHaveBeenCalled() + + await wrapper.find('form').trigger('submit') + await vi.waitFor(() => expect(mockStrrApi).toHaveBeenCalledTimes(1)) + expect(mockStrrApi).toHaveBeenCalledWith('/accounts/search', expect.objectContaining({ + params: { name: 'AB' } + })) + expect(mockStrrApi).not.toHaveBeenCalledWith('/accounts', expect.anything()) + }) + + it('does not re-query /accounts/search when only trailing whitespace changes', async () => { + mockStrrApi.mockResolvedValue({ total: 0 }) + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('Acme') + await vi.advanceTimersByTimeAsync(450) + expect(mockStrrApi).toHaveBeenCalledTimes(1) + + await input.setValue('Acme ') + await vi.advanceTimersByTimeAsync(450) + expect(mockStrrApi).toHaveBeenCalledTimes(1) + }) + + it('checks account name immediately when submitted during pending debounce and blocks duplicate POST', async () => { + mockStrrApi.mockResolvedValueOnce({ total: 1 }) + const wrapper = await mountPage() + const input = wrapper.find('[data-testid="account-name-input"]') + + await input.setValue('Existing') + // Submit before the 450ms debounce fires (e.g. pressing Enter) + await wrapper.find('form').trigger('submit') + await vi.waitFor(() => expect(mockStrrApi).toHaveBeenCalledTimes(1)) + + expect(mockStrrApi).toHaveBeenCalledWith('/accounts/search', expect.objectContaining({ + params: { name: 'Existing' } + })) + expect(mockStrrApi).not.toHaveBeenCalledWith('/accounts', expect.anything()) + }) +})