diff --git a/.changeset/admin-analytics.md b/.changeset/admin-analytics.md new file mode 100644 index 0000000..35f999a --- /dev/null +++ b/.changeset/admin-analytics.md @@ -0,0 +1,9 @@ +--- +'@goto/web': minor +'@goto/cli': minor +'@goto/worker': minor +--- + +Add a dedicated Analytics page with one searchable scope picker for all traffic, domains, Root and named redirects, or tags. Tag reports use current YAML membership across domains. Hide its navigation link when analytics is disabled and send direct visits to Health. Display the 90-day timeframe in days without changing the reporting window. Use a chart icon beside Health and compact icon controls in the mobile navbar. Keep Overview, Domain, Root, named Link, and Tag pages focused on configuration and all-time visit summaries, with their charts, breakdowns, and timeframes in Analytics. + +When Analytics is enabled, add report links to Domain, Root, Link, and Tag details. The Root page opens its domain-wide report. Show the tag name in the Tag details card instead of the page heading. diff --git a/apps/web/e2e/auth.e2e.ts b/apps/web/e2e/auth.e2e.ts index bc2f8a3..56a461c 100644 --- a/apps/web/e2e/auth.e2e.ts +++ b/apps/web/e2e/auth.e2e.ts @@ -13,20 +13,16 @@ test('shared credentials protect admin pages and sign-out removes access', async appServer }) => { await page.setViewportSize({ width: 1280, height: 720 }); - const navigationWarnings: string[] = []; - page.on('console', (message) => { - const text = message.text(); - if (text.includes('push_state_deprecated')) navigationWarnings.push(text); - }); const root = await request.get('/', { maxRedirects: 0 }); expect(root.status()).toBe(404); expect(root.headers().location).toBeUndefined(); - const adminRedirect = await request.get('/admin', { + const adminRedirect = await request.get('/admin/analytics', { headers: { accept: 'text/html' }, maxRedirects: 0 }); expect(adminRedirect.status()).toBe(303); + expect(adminRedirect.headers().location).toBe('/signin?callbackUrl=%2Fadmin%2Fanalytics'); expect(adminRedirect.headers()['cache-control']).toBe('private, no-store'); const signInPage = await page.goto(`${appServer.origin}/admin`); @@ -44,109 +40,30 @@ test('shared credentials protect admin pages and sign-out removes access', async await page.getByLabel('Password', { exact: true }).fill('e2e-only-password'); await page.getByRole('button', { name: 'Sign in', exact: true }).click(); await expect(page.getByRole('heading', { name: 'Overview', exact: true })).toBeVisible(); - const visitsValue = page - .getByRole('region', { name: 'Visits', exact: true }) - .locator('.admin-stat-value'); await expect(page.getByRole('region', { name: 'Domains', exact: true })).toContainText('2'); - await expect(visitsValue).toHaveText('3'); - const acceptedLanguages = page.getByRole('region', { name: 'Accepted languages', exact: true }); - await expect(acceptedLanguages.getByRole('columnheader')).toHaveText([ - 'Language', - 'Visits', - 'Share' - ]); - await expect( - acceptedLanguages.getByRole('rowheader', { name: 'Other', exact: true }) - ).toBeVisible(); - const browsers = page.getByRole('region', { name: 'Browsers', exact: true }); - const operatingSystems = page.getByRole('region', { name: 'Operating systems', exact: true }); - await expect(browsers).toBeVisible(); - await expect(operatingSystems).toBeVisible(); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ + const summary = page.getByRole('region', { name: 'Summary', exact: true }); + await expect(summary.locator('.admin-stat-label')).toHaveText([ 'Domains', 'Links', - 'Visits', - 'Retention' + 'Total Visits' ]); + const totalVisits = summary.getByRole('region', { name: 'Total Visits', exact: true }); + await expect(totalVisits.getByText('5', { exact: true })).toBeVisible(); + await expect(summary.getByRole('link')).toHaveCount(0); + await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount(0); + await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( + 0 + ); const heading = page.locator('.admin-heading'); await expect(heading.locator('.admin-title > h1 + time')).toBeVisible(); const timeframe = heading.getByRole('group', { name: 'Timeframe', exact: true }); - await expect(timeframe.getByRole('button')).toHaveText(['7 days', '30 days', '3 months']); - await expect(timeframe.getByRole('button', { name: '30 days', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - const trend = page.getByRole('region', { name: 'Visits over time', exact: true }); - const graph = trend.getByRole('img'); - await expect(graph).toHaveAttribute('aria-busy', 'false'); - const chartTable = trend.getByRole('table'); - await expect(chartTable).toBeVisible(); - await expect(chartTable).toHaveAccessibleName('Visits'); - await expect(chartTable.getByRole('columnheader')).toHaveText(['Period (UTC)', 'Visits']); - await expect(chartTable.getByRole('row', { name: 'Total 3', exact: true })).toBeVisible(); - await expect(chartTable).not.toContainText('(partial)'); - await expect(trend.getByRole('region', { name: 'Visit data', exact: true })).toHaveAttribute( - 'tabindex', - '0' - ); - await expect(graph).toBeVisible(); - await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 3\./); + await expect(timeframe).toHaveCount(0); const domainLink = page.getByRole('link', { name: 'go.example.org', exact: true }); const domainRow = page.getByRole('listitem').filter({ has: domainLink }); - const domainCounts = domainRow.locator('.admin-inventory-number'); - await expect(domainCounts).toHaveText(['6', '2']); - const selectionRequests: string[] = []; - const recordSelectionRequest = (request: Request) => { - const type = request.resourceType(); - if (type === 'document' || type === 'fetch' || type === 'xhr') { - selectionRequests.push(request.url()); - } - }; - page.on('request', recordSelectionRequest); - await timeframe.getByRole('button', { name: '7 days', exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}/admin?period=7d`); - await expect(timeframe.getByRole('button', { name: '7 days', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('2'); - await expect(domainCounts).toHaveText(['6', '1']); - await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 2\./); - await timeframe.getByRole('button', { name: '3 months', exact: true }).click(); - await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('4'); - await expect(domainCounts).toHaveText(['6', '3']); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 4\./); - await page.goBack(); - await expect(timeframe.getByRole('button', { name: '7 days', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('2'); - await expect(domainCounts).toHaveText(['6', '1']); - await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 2\./); - await page.goForward(); - await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('4'); - await expect(domainCounts).toHaveText(['6', '3']); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 4\./); - page.off('request', recordSelectionRequest); - expect(selectionRequests).toEqual([]); - const overviewResponse = await page.reload(); + await expect(domainRow.locator('.admin-inventory-number')).toHaveText(['6', '3']); + const overviewResponse = await page.goto(`${appServer.origin}/admin?period=7d`); expect(overviewResponse?.headers()['cache-control']).toBe('private, no-store'); - await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('4'); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 4\./); - expect(navigationWarnings).toEqual([]); + await expect(totalVisits.getByText('5', { exact: true })).toBeVisible(); const adminNav = page.getByRole('navigation', { name: 'Administration', exact: true }); const overviewLink = adminNav.getByRole('link', { name: 'GoTo', exact: true }); await expect(adminNav.getByText('GoTo', { exact: true })).toBeVisible(); @@ -156,33 +73,22 @@ test('shared credentials protect admin pages and sign-out removes access', async const context = page.locator('.admin-context'); await expect(context).toHaveCount(0); await expect(page).toHaveTitle('Domain — go.example.org — GoTo'); - await expect(acceptedLanguages).toBeVisible(); - await expect(browsers.getByRole('columnheader')).toHaveText(['Browser', 'Visits', 'Share']); - await expect(operatingSystems.getByRole('columnheader')).toHaveText([ - 'Operating system', - 'Visits', - 'Share' - ]); - await expect(browsers.getByRole('rowheader', { name: 'Other', exact: true })).toBeVisible(); - await expect(overviewLink).toHaveAttribute('href', '/admin?period=all'); + await expect(timeframe).toHaveCount(0); + const trend = page.getByRole('region', { name: 'Visits over time', exact: true }); + await expect(trend).toHaveCount(0); + await expect(overviewLink).toHaveAttribute('href', '/admin'); const appIcon = overviewLink.locator('img[src="/@static/favicon.svg"]'); await expect(appIcon).toBeVisible(); await expect .poll(() => appIcon.evaluate((image: HTMLImageElement) => image.naturalWidth)) .toBeGreaterThan(0); await expect(page.getByRole('link', { name: 'Overview', exact: true })).toHaveCount(0); - await expect(graph).toHaveAttribute('aria-busy', 'false'); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 3\./); - await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('3'); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ + await expect(summary.locator('.admin-stat-label')).toHaveText([ 'Links', - 'Visits', + 'Total Visits', 'Invalid clicks' ]); + await expect(totalVisits.getByText('3', { exact: true })).toBeVisible(); await expect( page.getByRole('region', { name: 'Invalid clicks', exact: true }).locator('.admin-stat-value') ).toHaveText('1'); @@ -194,70 +100,66 @@ test('shared credentials protect admin pages and sign-out removes access', async const rootLink = rootRow.getByRole('link', { name: '(root)', exact: true }); await expect(rootRow.locator('.admin-inventory-secondary')).toHaveText('[not found]'); await expect(rootRow.locator('.admin-inventory-state')).toHaveText('Active'); - const columns = ['Path', 'Destination', 'State', 'Visits']; + const columns = ['Path', 'Destination', 'State', 'Total Visits']; await expect(linksInventory.locator('.admin-inventory-heading > span')).toHaveText(columns); - const retainedLink = linksInventory + const percentLinkRow = linksInventory .getByRole('listitem') .filter({ has: page.getByRole('link', { name: '/a%2Fb', exact: true }) }); - await expect(retainedLink.getByRole('link')).toHaveCount(1); - const retainedVisits = retainedLink.locator('.admin-inventory-number'); - await expect(retainedVisits).toHaveText('1'); - await page.setViewportSize({ width: 390, height: 844 }); - const mobileTimeframe = page.getByRole('button', { name: /^Timeframe: / }); - await expect(mobileTimeframe).toContainText('3 months'); - await mobileTimeframe.click(); - await page - .getByRole('listbox', { name: 'Timeframe', exact: true }) - .getByRole('option', { name: '30 days', exact: true }) - .click(); - await expect(visitsValue).toHaveText('2'); - await expect(retainedVisits).toHaveText('0'); - await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 2\./); - expect( - await linksInventory.evaluate((element) => element.scrollWidth <= element.clientWidth) - ).toBe(true); - await page.setViewportSize({ width: 1280, height: 720 }); - await timeframe.getByRole('button', { name: '3 months', exact: true }).click(); - await expect(visitsValue).toHaveText('3'); - await expect(retainedVisits).toHaveText('1'); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 3\./); + await expect(percentLinkRow.getByRole('link')).toHaveCount(1); + await expect(percentLinkRow.locator('.admin-inventory-number')).toHaveText('1'); const historicalInvalid = linksInventory .getByRole('listitem') .filter({ has: page.getByRole('link', { name: '/a/b', exact: true }) }); await expect(historicalInvalid.locator('.admin-inventory-number')).toHaveText('0'); await expect(domainDetails.getByRole('heading', { name: 'Details', exact: true })).toBeVisible(); - await expect(domainDetails.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback']); + const domainReportPath = '/admin/analytics?domain=go.example.org'; + await expect(domainDetails.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback', 'Analytics']); await expect(domainDetails.locator('dd')).toHaveText([ 'go.example.org', 'Uses fallback', - '404 Not found' + '404 Not found', + domainReportPath ]); await expect(rootRow.locator('.admin-inventory-number')).toHaveText('1'); await expect(domainDetails.getByRole('link', { name: 'Root', exact: true })).toHaveCount(0); await expect(domainDetails.getByRole('link', { name: 'Fallback', exact: true })).toHaveCount(0); + const domainAnalyticsLink = domainDetails.getByRole('link', { + name: domainReportPath, + exact: true + }); + await expect(domainAnalyticsLink).toHaveAttribute('href', domainReportPath); await expect( linksInventory.getByText('https://example.org/first-domain', { exact: true }) ).toBeVisible(); await expect( linksInventory.getByRole('link', { name: 'https://example.org/first-domain', exact: true }) ).toHaveCount(0); - await expect(rootLink).toHaveAttribute('href', '/admin/domains/go.example.org/links?period=all'); + await expect(rootLink).toHaveAttribute('href', '/admin/domains/go.example.org/links'); const redirectCard = page.getByRole('region', { name: 'Redirect', exact: true }); const settingsCard = page.getByRole('region', { name: 'Settings', exact: true }); const docsPath = '/admin/domains/go.example.org/links/docs'; await page.getByRole('link', { name: '/docs', exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}${docsPath}?period=all`); + await expect(page).toHaveURL(`${appServer.origin}${docsPath}`); await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible(); + const summaryVisitCount = page + .getByRole('region', { name: 'Summary', exact: true }) + .getByRole('region', { name: 'Total Visits', exact: true }) + .locator('.admin-stat-value'); + const acceptedLanguages = page.getByRole('region', { name: 'Accepted languages', exact: true }); await expect(context).toHaveCount(0); - await expect(redirectCard.getByRole('heading', { name: 'Redirect', exact: true })).toBeVisible(); + await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([ + 'Summary', + 'Redirect', + 'Settings' + ]); await expect(redirectCard.locator('dt')).toHaveText([ 'Domain', 'Path', 'Title', 'Destination', 'Rules', - 'Visits' + 'Analytics' ]); await expect(redirectCard.getByText(docsTitle, { exact: true })).toBeVisible(); await expect(settingsCard.locator('dt')).toHaveText([ @@ -284,7 +186,7 @@ test('shared credentials protect admin pages and sign-out removes access', async ).toHaveText(['work', 'docs', sharedTag]); await expect(settingsCard.getByRole('link', { name: sharedTag, exact: true })).toHaveAttribute( 'href', - `${tagPath}?period=all` + tagPath ); const destinations = redirectCard.getByRole('list', { name: 'Destinations', exact: true }); await expect(destinations.getByRole('link')).toHaveText([ @@ -300,82 +202,72 @@ test('shared credentials protect admin pages and sign-out removes access', async await expect(domainField).toHaveText('go.example.org'); await expect(domainField.getByRole('link')).toHaveAttribute( 'href', - '/admin/domains/go.example.org?period=all' + '/admin/domains/go.example.org' ); await expect(redirectCard.locator('dd').nth(1)).toHaveText('/docs'); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Visits', 'Status']); + await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ + 'Total Visits', + 'Status' + ]); await expect(page.getByRole('region', { name: 'Status', exact: true })).toContainText('Active'); await expect(page).toHaveTitle('Link — go.example.org/docs — GoTo'); - await expect(graph).toHaveAttribute('aria-busy', 'false'); - await expect(chartTable).toHaveAccessibleName('Visits'); - await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 1\./); - await expect(browsers.getByRole('row', { name: 'Firefox 1 100%', exact: true })).toBeVisible(); - await expect( - acceptedLanguages.getByRole('row', { name: 'en 1 100%', exact: true }) - ).toBeVisible(); - await expect( - acceptedLanguages.getByRole('row', { name: 'fr 1 100%', exact: true }) - ).toBeVisible(); - const languageData = acceptedLanguages.getByRole('region', { - name: 'Accepted languages data', - exact: true - }); - const sixthLanguage = acceptedLanguages.getByRole('row', { name: 'pt 1 100%', exact: true }); - await languageData.scrollIntoViewIfNeeded(); - await expect( - acceptedLanguages.getByRole('row', { name: 'de 1 100%', exact: true }) - ).toBeInViewport(); - await expect(sixthLanguage).not.toBeInViewport(); - await sixthLanguage.scrollIntoViewIfNeeded(); - await expect(sixthLanguage).toBeInViewport(); - await expect( - operatingSystems.getByRole('row', { name: 'Linux 1 100%', exact: true }) - ).toBeVisible(); - await expect(visitsValue).toHaveText('1'); - await timeframe.getByRole('button', { name: '7 days', exact: true }).click(); - await expect(visitsValue).toHaveText('0'); - await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 0\./); - await expect(browsers).toContainText('No visits in this period.'); - await expect(operatingSystems).toContainText('No visits in this period.'); - await expect(acceptedLanguages).toContainText('No visits in this period.'); - await expect(chartTable.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); - await timeframe.getByRole('button', { name: '3 months', exact: true }).click(); - await expect(visitsValue).toHaveText('1'); - await expect(overviewLink).toHaveAttribute('href', '/admin?period=all'); + await expect(summaryVisitCount).toHaveText('1'); + await expect(timeframe).toHaveCount(0); + await expect(trend).toHaveCount(0); + await expect(acceptedLanguages).toHaveCount(0); + await expect(overviewLink).toHaveAttribute('href', '/admin'); await expect( page.getByRole('region', { name: 'Links on go.example.org', exact: true }) ).toHaveCount(0); await settingsCard.getByRole('link', { name: sharedTag, exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}${tagPath}?period=all`); - const tagHeading = page.getByRole('heading', { name: `Tag: ${sharedTag}`, exact: true }); - await expect(tagHeading).toBeVisible(); - await expect(tagHeading).toHaveAttribute('title', `Tag: ${sharedTag}`); + await expect(page).toHaveURL(`${appServer.origin}${tagPath}`); + await expect(page.getByRole('heading', { level: 1, name: 'Tag', exact: true })).toBeVisible(); await expect(page).toHaveTitle(`Tag: ${sharedTag} — GoTo`); - await expect(page.getByRole('region', { name: 'Tag details', exact: true })).toHaveCount(0); + await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([ + 'Summary', + 'Details', + 'Links' + ]); + const tagDetails = page.getByRole('region', { name: 'Details', exact: true }); + const tagQuery = new URLSearchParams({ tag: sharedTag }); + const tagReportPath = `/admin/analytics?${tagQuery}`; + await expect(tagDetails.locator('dt')).toHaveText(['Tag Name', 'Analytics']); + await expect(tagDetails.locator('dd')).toHaveText([sharedTag, tagReportPath]); + const tagAnalyticsLink = tagDetails.getByRole('link', { name: tagReportPath, exact: true }); + await tagAnalyticsLink.click(); + await expect(page).toHaveURL(`${appServer.origin}${tagReportPath}`); + const tagScopePicker = page.getByRole('combobox', { name: 'Report scope', exact: true }); + await expect(tagScopePicker).toHaveAttribute('placeholder', `Tag: ${sharedTag}`); + await page.goBack(); + const tagSummary = page.getByRole('region', { name: 'Summary', exact: true }); + await expect(tagSummary.locator('.admin-stat-label')).toHaveText([ + 'Domains', + 'Links', + 'Total Visits' + ]); + await expect(tagSummary.locator('.admin-stat-value')).toHaveText(['2', '2', '2']); + await expect(timeframe).toHaveCount(0); + await expect(trend).toHaveCount(0); const taggedLinks = page.getByRole('region', { name: `Links tagged ${sharedTag}`, exact: true }); await expect(taggedLinks.getByRole('link')).toHaveCount(2); await expect(taggedLinks.locator('.admin-inventory-heading > span')).toHaveText([ 'Domain', 'Path', 'State', - 'Visits' + 'Total Visits' ]); + await expect(taggedLinks.locator('.admin-inventory-number')).toHaveText(['1', '1']); const taggedDocs = taggedLinks.getByRole('link', { name: 'go.example.org/docs', exact: true }); await expect(taggedDocs.locator('.admin-inventory-primary')).toHaveText('go.example.org'); await expect(taggedDocs.locator('.admin-inventory-secondary')).toHaveText('/docs'); - await expect(taggedDocs).toHaveAttribute('href', `${docsPath}?period=all`); + await expect(taggedDocs).toHaveAttribute('href', docsPath); await expect( taggedLinks.getByRole('link', { name: 'tiny.example.org/docs', exact: true }) ).toBeVisible(); - await expect(visitsValue).toHaveText('2'); - await expect(acceptedLanguages).toBeVisible(); - await timeframe.getByRole('button', { name: '7 days', exact: true }).click(); - await expect(page).toHaveURL(`${appServer.origin}${tagPath}?period=7d`); - await expect(visitsValue).toHaveText('1'); await taggedDocs.click(); - await expect(page).toHaveURL(`${appServer.origin}${docsPath}?period=7d`); - await timeframe.getByRole('button', { name: '3 months', exact: true }).click(); + await expect(page).toHaveURL(`${appServer.origin}${docsPath}`); + await expect(summaryVisitCount).toHaveText('1'); await overviewLink.click(); await domainLink.click(); @@ -383,43 +275,67 @@ test('shared credentials protect admin pages and sign-out removes access', async await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible(); await expect(page).toHaveTitle('Link — go.example.org/a%2Fb — GoTo'); await expect(redirectCard.getByText('Title', { exact: true })).toHaveCount(0); - await expect(page).toHaveURL( - `${appServer.origin}/admin/domains/go.example.org/links/a%252Fb?period=all` + await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links/a%252Fb`); + await expect(summaryVisitCount).toHaveText('1'); + const literalPercentReportPath = `${domainReportPath}&path=%2Fa%252Fb`; + const literalPercentReport = redirectCard.getByRole('link', { + name: literalPercentReportPath, + exact: true + }); + await expect(literalPercentReport).toHaveAttribute('href', literalPercentReportPath); + const linkSummary = page.getByRole('region', { name: 'Summary', exact: true }); + await expect(linkSummary.getByRole('region', { name: 'Status', exact: true })).toContainText( + 'Limit Exceeded' ); - await expect(visitsValue).toHaveText('1'); + await expect( + linkSummary + .getByRole('region', { name: 'Max visits', exact: true }) + .getByText('1', { exact: true }) + ).toBeVisible(); await page.goBack(); await page.getByRole('link', { name: '/a/b', exact: true }).click(); - await expect(page).toHaveURL( - `${appServer.origin}/admin/domains/go.example.org/links/a/b?period=all` - ); + await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links/a/b`); await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible(); await expect(page).toHaveTitle('Link — go.example.org/a/b — GoTo'); - await expect(visitsValue).toHaveText('0'); + await expect(summaryVisitCount).toHaveText('0'); + const nestedReportPath = `${domainReportPath}&path=%2Fa%2Fb`; + const nestedReport = redirectCard.getByRole('link', { name: nestedReportPath, exact: true }); + await expect(nestedReport).toHaveAttribute('href', nestedReportPath); await page.goBack(); await rootLink.click(); - await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links?period=all`); + await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links`); await expect(page.getByRole('heading', { name: 'Root', exact: true })).toBeVisible(); await expect(page).toHaveTitle('Root — go.example.org — GoTo'); - await expect(acceptedLanguages).toBeVisible(); - await expect(visitsValue).toHaveText('1'); + await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([ + 'Summary', + 'Root details', + 'Fallback' + ]); + await expect(timeframe).toHaveCount(0); + await expect(trend).toHaveCount(0); + await expect(summaryVisitCount).toHaveText('1'); await expect(page.getByRole('region', { name: 'Status', exact: true })).toHaveCount(0); const rootDetails = page.getByRole('region', { name: 'Root details', exact: true }); + await expect(rootDetails.locator('dt')).toHaveText([ + 'Domain', + 'Address', + 'Destination', + 'Analytics' + ]); await expect(rootDetails.locator('dd')).toHaveText([ 'go.example.org', 'go.example.org/', - '1', - 'Uses fallback' + 'Uses fallback', + domainReportPath ]); await expect(page.getByRole('region', { name: 'Fallback', exact: true })).toContainText( '404 Not found' ); + const rootAnalyticsLink = rootDetails.getByRole('link', { name: domainReportPath, exact: true }); + await expect(rootAnalyticsLink).toHaveAttribute('href', domainReportPath); await rootDetails.getByRole('link', { name: 'go.example.org', exact: true }).click(); - await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ); - await expect(visitsValue).toHaveText('3'); + await expect(totalVisits.getByText('3', { exact: true })).toBeVisible(); await page .getByRole('navigation', { name: 'Administration', exact: true }) @@ -444,9 +360,203 @@ test('shared credentials protect admin pages and sign-out removes access', async await expect(workerHealth.getByRole('alert')).toContainText('Worker is reachable.'); await expect(workerHealth.locator('time')).toBeVisible(); + await page + .getByRole('navigation', { name: 'Administration', exact: true }) + .getByRole('link', { name: 'Analytics', exact: true }) + .click(); + await expect(page.getByRole('heading', { name: 'Analytics', exact: true })).toBeVisible(); + const analyticsVisits = page.getByRole('region', { name: 'Visits', exact: true }); + const analyticsChart = page.getByRole('region', { name: 'Visits over time', exact: true }); + await expect(analyticsVisits).toContainText('3'); + await expect(analyticsChart.getByRole('row', { name: 'Total 3', exact: true })).toBeVisible(); + const reportFilters = page.getByRole('group', { name: 'Report filters', exact: true }); + const scopeInput = reportFilters.getByRole('combobox', { name: 'Report scope', exact: true }); + const scopeOptions = page.getByRole('listbox', { name: 'Report scopes', exact: true }); + async function chooseReportScope(option: string) { + await scopeInput.click(); + await scopeOptions.getByRole('option', { name: option, exact: true }).click(); + } + await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic'); + const analyticsUrl = `${appServer.origin}/admin/analytics`; + const goReportUrl = `${analyticsUrl}?period=7d&domain=go.example.org`; + await timeframe.getByRole('button', { name: '7 days', exact: true }).click(); + await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); + await chooseReportScope('go.example.org'); + await expect(page).toHaveURL(goReportUrl); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + + const isHeldRedirectRequest = (url: URL) => + url.pathname === '/admin/analytics/__data.json' && + url.searchParams.get('domain') === 'go.example.org' && + url.searchParams.get('path') === '/a/b'; + const releaseRedirectReport = Promise.withResolvers(); + await page.route( + isHeldRedirectRequest, + async (route) => { + await releaseRedirectReport.promise; + await route.continue(); + }, + { times: 1 } + ); + try { + const [heldRequest] = await Promise.all([ + page.waitForRequest((request) => isHeldRedirectRequest(new URL(request.url()))), + chooseReportScope('go.example.org/a/b') + ]); + await expect(reportFilters).toHaveAttribute('aria-busy', 'true'); + await expect(scopeInput).toHaveAttribute('placeholder', 'Domain: go.example.org'); + await timeframe.getByRole('button', { name: '30 days', exact: true }).click(); + await expect(page).toHaveURL(`${analyticsUrl}?domain=go.example.org`); + + releaseRedirectReport.resolve(); + const lateResponse = await heldRequest.response(); + expect(lateResponse?.ok()).toBe(true); + await expect(reportFilters).toHaveAttribute('aria-busy', 'false'); + await expect(page).toHaveURL(`${analyticsUrl}?domain=go.example.org`); + await expect(scopeInput).toHaveAttribute('placeholder', 'Domain: go.example.org'); + await expect(analyticsVisits).toContainText('2'); + await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); + } finally { + releaseRedirectReport.resolve(); + } + await page.goBack(); + await page.goBack(); + await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); + await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic'); + await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); + + const searchRequests: string[] = []; + function recordSearchRequest(request: Request) { + const url = new URL(request.url()); + if (url.origin === appServer.origin && url.pathname.startsWith('/admin/analytics')) { + searchRequests.push(url.href); + } + } + page.on('request', recordSearchRequest); + try { + await scopeInput.fill('/DOCS'); + await expect(scopeOptions.getByRole('option')).toHaveText([ + 'go.example.org/docs', + 'tiny.example.org/docs' + ]); + await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); + await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); + expect(searchRequests).toEqual([]); + } finally { + page.off('request', recordSearchRequest); + } + await scopeOptions.getByRole('option', { name: 'go.example.org/docs', exact: true }).click(); + await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`); + await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); + await chooseReportScope('go.example.org/ (Root)'); + await expect(page).toHaveURL(`${goReportUrl}&path=%2F`); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + await page.goBack(); + await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/docs'); + await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); + + await chooseReportScope('tiny.example.org/docs'); + const tinyReportUrl = `${analyticsUrl}?period=7d&domain=tiny.example.org`; + await expect(page).toHaveURL(`${tinyReportUrl}&path=%2Fdocs`); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + + await scopeInput.click(); + await expect(scopeOptions).toBeVisible(); + const popupId = await scopeOptions.getAttribute('id'); + expect(popupId).toBeTruthy(); + await expect(scopeInput).toHaveAttribute('aria-controls', popupId ?? ''); + await scopeInput.press('Home'); + const allTraffic = scopeOptions.getByRole('option', { name: 'All traffic', exact: true }); + await expect(scopeInput).toHaveAttribute( + 'aria-activedescendant', + (await allTraffic.getAttribute('id')) ?? '' + ); + await scopeInput.fill('work/100%'); + await expect(scopeOptions.getByRole('option')).toHaveText([sharedTag]); + await scopeInput.press('ArrowDown'); + await scopeInput.press('Enter'); + const tagReportUrl = `${analyticsUrl}?period=7d&${new URLSearchParams({ tag: sharedTag })}`; + await expect(page).toHaveURL(tagReportUrl); + await expect(scopeInput).toHaveAttribute('placeholder', `Tag: ${sharedTag}`); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + await timeframe.getByRole('button', { name: '30 days', exact: true }).click(); + await expect(page).toHaveURL(`${analyticsUrl}?${new URLSearchParams({ tag: sharedTag })}`); + await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); + await expect(acceptedLanguages.getByRole('row', { name: 'fr 1 50%', exact: true })).toBeVisible(); + await page.goBack(); + await expect(page).toHaveURL(tagReportUrl); + await page.reload(); + await expect(scopeInput).toHaveAttribute('placeholder', `Tag: ${sharedTag}`); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + + await scopeInput.click(); + await expect(scopeOptions).toBeVisible(); + await scopeInput.fill('long-picker-tag-'); + const longTag = `long-picker-tag-${'w'.repeat(1400)}`; + await expect(scopeOptions.getByRole('option')).toHaveText([longTag]); + await scopeInput.press('ArrowDown'); + await scopeInput.press('Enter'); + await expect(page).toHaveURL( + `${analyticsUrl}?period=7d&${new URLSearchParams({ tag: longTag })}` + ); + await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); + + await page.goto(`${analyticsUrl}?period=7d&tag=Removed`); + await expect(page.getByRole('status')).toContainText( + 'This report scope is no longer configured.' + ); + await expect(analyticsChart).toHaveCount(0); + await chooseReportScope('All traffic'); + await expect(page).toHaveURL(`${analyticsUrl}?period=7d`); + await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible(); + + await chooseReportScope('go.example.org/docs'); + await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`); + await page.setViewportSize({ width: 390, height: 844 }); + const graph = analyticsChart.getByRole('img'); + const browsers = page.getByRole('region', { name: 'Browsers', exact: true }); + const operatingSystems = page.getByRole('region', { name: 'Operating systems', exact: true }); + await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 0\./); + await expect(browsers).toContainText('No visits in this period.'); + await expect(operatingSystems).toContainText('No visits in this period.'); + await expect(acceptedLanguages).toContainText('No visits in this period.'); + + await page.getByRole('button', { name: 'Timeframe: 7 days', exact: true }).click(); + await page + .getByRole('listbox', { name: 'Timeframe', exact: true }) + .getByRole('option', { name: '90 days', exact: true }) + .click(); + const fullDomainUrl = `${analyticsUrl}?period=all&domain=go.example.org`; + await expect(page).toHaveURL(`${fullDomainUrl}&path=%2Fdocs`); + await expect(graph).toHaveAttribute('aria-busy', 'false'); + await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 1\./); + await expect(browsers.getByRole('row', { name: 'Firefox 1 100%', exact: true })).toBeVisible(); + await expect( + operatingSystems.getByRole('row', { name: 'Linux 1 100%', exact: true }) + ).toBeVisible(); + await expect( + acceptedLanguages.getByRole('row', { name: 'fr 1 100%', exact: true }) + ).toBeVisible(); + await page.setViewportSize({ width: 1280, height: 720 }); + await chooseReportScope('go.example.org/a%2Fb'); + const literalPathUrl = `${fullDomainUrl}&path=%2Fa%252Fb`; + await expect(page).toHaveURL(literalPathUrl); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + await chooseReportScope('go.example.org/a/b'); + await expect(page).toHaveURL(`${fullDomainUrl}&path=%2Fa%2Fb`); + await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible(); + await page.goBack(); + await expect(page).toHaveURL(literalPathUrl); + await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/a%2Fb'); + await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible(); + const html = await page.content(); await expect(html).not.toContain('e2e-only-password'); - await page.getByRole('button', { name: 'Sign out', exact: true }).click(); + await page.setViewportSize({ width: 390, height: 844 }); + await page + .getByRole('navigation', { name: 'Administration', exact: true }) + .getByRole('button', { name: 'Sign out', exact: true }) + .click(); await expect(page).toHaveURL(/\/signin\?/); await page.goto(`${appServer.origin}${docsPath}`); await expect(page).toHaveURL(/\/signin\?/); @@ -465,7 +575,18 @@ test.describe('analytics disabled', () => { await page.getByLabel('Password', { exact: true }).fill('e2e-only-password'); await page.getByRole('button', { name: 'Sign in', exact: true }).click(); await expect(page.getByRole('heading', { name: 'Overview', exact: true })).toBeVisible(); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Domains', 'Links']); + const adminNav = page.getByRole('navigation', { name: 'Administration', exact: true }); + await expect(adminNav.getByRole('link', { name: 'Analytics', exact: true })).toHaveCount(0); + await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ + 'Domains', + 'Links', + 'Total Visits' + ]); + await expect( + page + .getByRole('region', { name: 'Total Visits', exact: true }) + .getByText('0', { exact: true }) + ).toBeVisible(); await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); await expect(page.getByRole('region', { name: 'Browsers', exact: true })).toHaveCount(0); await expect(page.getByRole('region', { name: 'Operating systems', exact: true })).toHaveCount( @@ -481,10 +602,13 @@ test.describe('analytics disabled', () => { page .getByRole('region', { name: 'Domain inventory', exact: true }) .locator('.admin-inventory-heading > span') - ).toHaveText(['Host', 'Links']); - await expect(page.getByRole('status')).toHaveText('Analytics disabled.'); + ).toHaveText(['Host', 'Links', 'Total Visits']); await page.getByRole('link', { name: 'go.example.org', exact: true }).click(); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Links']); + await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ + 'Links', + 'Total Visits', + 'Invalid clicks' + ]); await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( 0 @@ -496,22 +620,36 @@ test.describe('analytics disabled', () => { page .getByRole('region', { name: 'Links on go.example.org', exact: true }) .locator('.admin-inventory-heading > span') - ).toHaveText(['Path', 'Destination', 'State']); - await expect( - page.getByRole('region', { name: 'Details', exact: true }).locator('dt') - ).toHaveText(['Domain', 'Root', 'Fallback']); - await expect( - page - .getByRole('region', { name: 'Links on go.example.org', exact: true }) - .getByRole('link', { name: '(root)', exact: true }) - ).toBeVisible(); + ).toHaveText(['Path', 'Destination', 'State', 'Total Visits']); + const details = page.getByRole('region', { name: 'Details', exact: true }); + const reportLinks = 'a[href^="/admin/analytics"]'; + await expect(details.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback']); + await expect(details.locator(reportLinks)).toHaveCount(0); + const rootLink = page + .getByRole('region', { name: 'Links on go.example.org', exact: true }) + .getByRole('link', { name: '(root)', exact: true }); + await rootLink.click(); + const rootDetails = page.getByRole('region', { name: 'Root details', exact: true }); + await expect(rootDetails).toBeVisible(); + await expect(rootDetails.locator(reportLinks)).toHaveCount(0); + await page.goBack(); await page.getByRole('link', { name: '/docs', exact: true }).click(); - await expect(page.getByRole('region', { name: 'Redirect', exact: true })).toBeVisible(); + const redirectCard = page.getByRole('region', { name: 'Redirect', exact: true }); + await expect(redirectCard).toBeVisible(); + await expect(redirectCard.locator(reportLinks)).toHaveCount(0); await expect(page.getByRole('region', { name: 'Browsers', exact: true })).toHaveCount(0); await expect(page.getByRole('region', { name: 'Operating systems', exact: true })).toHaveCount( 0 ); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Status']); + await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([ + 'Total Visits', + 'Status' + ]); + await expect( + page + .getByRole('region', { name: 'Total Visits', exact: true }) + .getByText('0', { exact: true }) + ).toBeVisible(); await expect(page.getByRole('region', { name: 'Status', exact: true })).toContainText('Active'); await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( @@ -520,10 +658,8 @@ test.describe('analytics disabled', () => { await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount( 0 ); - await page - .getByRole('navigation', { name: 'Administration', exact: true }) - .getByRole('link', { name: 'Health', exact: true }) - .click(); + await page.goto('/admin/analytics?period=7d'); + await expect(page).toHaveURL(`${appServer.origin}/admin/health`); await expect( page.getByRole('region', { name: 'Analytics', exact: true }).locator('dd') ).toHaveText(['Disabled', 'Disabled', 'Disabled']); @@ -538,10 +674,12 @@ test.describe('analytics disabled', () => { .getByRole('link', { name: sharedTag, exact: true }) .click(); await expect(page).toHaveURL(`${appServer.origin}${tagPath}`); - await expect( - page.getByRole('heading', { name: `Tag: ${sharedTag}`, exact: true }) - ).toBeVisible(); - await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Links']); + await expect(page.getByRole('heading', { level: 1, name: 'Tag', exact: true })).toBeVisible(); + await expect(details.locator('dt')).toHaveText('Tag Name'); + await expect(details.locator('dd')).toHaveText(sharedTag); + await expect(details.locator(reportLinks)).toHaveCount(0); + const tagSummary = page.getByRole('region', { name: 'Summary', exact: true }); + await expect(tagSummary.locator('.admin-stat-value')).toHaveText(['2', '2', '0']); await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0); await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount( 0 @@ -557,7 +695,8 @@ test.describe('analytics disabled', () => { await expect(taggedLinks.locator('.admin-inventory-heading > span')).toHaveText([ 'Domain', 'Path', - 'State' + 'State', + 'Total Visits' ]); }); }); diff --git a/apps/web/e2e/server.js b/apps/web/e2e/server.js index 37189e6..9a85050 100644 --- a/apps/web/e2e/server.js +++ b/apps/web/e2e/server.js @@ -34,7 +34,7 @@ const configuration = { '/schema.json': { url: 'https://example.org/public-schema' }, '/_app/version.json': { url: 'https://example.org/public-asset' }, '/a/b': { url: 'https://example.org/decoded' }, - '/a%2Fb': { url: 'https://example.org/literal-percent' }, + '/a%2Fb': { url: 'https://example.org/literal-percent', max_visits: 1 }, '/docs': { title: 'New hire handbook', url: 'https://example.org/first-domain', @@ -49,7 +49,10 @@ const configuration = { valid_until: '2100-01-01T00:00:00Z', tags: ['work', 'docs', 'Work/100%é'] }, - '/healthz': { url: 'https://example.org/public-health' } + '/healthz': { + url: 'https://example.org/public-health', + tags: [`long-picker-tag-${'w'.repeat(1400)}`] + } } }, 'tiny.example.org': { @@ -101,7 +104,13 @@ async function seedVisits() { outcome: 'valid', visited_at: Date.now() - 45 * 86_400_000 }, - { domain: 'tiny.example.org', path: '/docs', outcome: 'valid', accept_language: 'en' } + { domain: 'tiny.example.org', path: '/docs', outcome: 'valid', accept_language: 'en' }, + { + domain: 'retired.example.org', + path: '/docs', + outcome: 'valid', + visited_at: Date.now() - 120 * 86_400_000 + } ]; for (const visit of visits) await insertVisit(db, { ...common, ...visit }); } finally { diff --git a/apps/web/src/lib/components/admin/AdminNav.svelte b/apps/web/src/lib/components/admin/AdminNav.svelte index 765766a..4ee951f 100644 --- a/apps/web/src/lib/components/admin/AdminNav.svelte +++ b/apps/web/src/lib/components/admin/AdminNav.svelte @@ -1,15 +1,19 @@ {documentTitle ?? heading} — GoTo - +
diff --git a/apps/web/src/lib/components/admin/AdminSelect.svelte b/apps/web/src/lib/components/admin/AdminSelect.svelte new file mode 100644 index 0000000..1aac794 --- /dev/null +++ b/apps/web/src/lib/components/admin/AdminSelect.svelte @@ -0,0 +1,137 @@ + + + committedValue, onSelectionRequest} items={options}> + + {#snippet child({ props })} + + {/snippet} + + + + {#snippet child({ props, wrapperProps })} +
+
+ + {#each options as option (option.value)} + + {#snippet child({ props: itemProps, selected })} +
+ {option.label} + {#if selected}
+ {/snippet} +
+ {/each} +
+
+
+ {/snippet} +
+
+
+ + diff --git a/apps/web/src/lib/components/admin/AnalyticsField.svelte b/apps/web/src/lib/components/admin/AnalyticsField.svelte new file mode 100644 index 0000000..9f61229 --- /dev/null +++ b/apps/web/src/lib/components/admin/AnalyticsField.svelte @@ -0,0 +1,24 @@ + + +
Analytics
+
{href}
+ + diff --git a/apps/web/src/lib/components/admin/AnalyticsSection.svelte b/apps/web/src/lib/components/admin/AnalyticsSection.svelte deleted file mode 100644 index 8b0ac7b..0000000 --- a/apps/web/src/lib/components/admin/AnalyticsSection.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - -
-

Analytics

-
- {@render children()} -
-
- - diff --git a/apps/web/src/lib/components/admin/LinkInventory.svelte b/apps/web/src/lib/components/admin/LinkInventory.svelte index 5c4c279..d71c9bf 100644 --- a/apps/web/src/lib/components/admin/LinkInventory.svelte +++ b/apps/web/src/lib/components/admin/LinkInventory.svelte @@ -1,13 +1,11 @@
    {#each links as link (link.href)} {@const pathLabel = link.path === '/' ? '(root)' : link.path} {@const linkLabel = showDomain ? `${link.domain}${link.path}` : pathLabel}
  • - + {#if showDomain} {link.domain} {pathLabel} @@ -65,12 +58,10 @@ {:else if link.state === 'expired'}Expired {:else if link.state === 'exhausted'}Limit Exceeded{/if} - {#if collectionEnabled} + {#if visitLabel} - Visits - {formatCount(link.countsByTimeframe[timeframe]?.validVisits ?? null)} + {visitLabel} + {formatCount(link.visits)} {/if} diff --git a/apps/web/src/lib/components/admin/TagPills.svelte b/apps/web/src/lib/components/admin/TagPills.svelte index 8248ea1..f01bf77 100644 --- a/apps/web/src/lib/components/admin/TagPills.svelte +++ b/apps/web/src/lib/components/admin/TagPills.svelte @@ -1,14 +1,13 @@
      {#each uniqueTags as tag (tag)} -
    • {tag}
    • +
    • {tag}
    • {/each}
    diff --git a/apps/web/src/lib/components/admin/VisitTimeframes.svelte b/apps/web/src/lib/components/admin/VisitTimeframes.svelte index 15074de..ca4bbfd 100644 --- a/apps/web/src/lib/components/admin/VisitTimeframes.svelte +++ b/apps/web/src/lib/components/admin/VisitTimeframes.svelte @@ -1,10 +1,8 @@ - - {#snippet actions()} - {#if data.available && data.timeframes.length > 0} - - {/if} - {/snippet} + +
    +

    Summary

    +
    + {#if data.totalVisits === null} +

    Visit totals unavailable.

    + {/if} +
    + + + +
    +
    +

    Domains

    {#if data.domains.length === 0}

    No domains configured.

    {:else} {/if}
    - - -
    - - - {#if data.collectionEnabled} - - - {/if} -
    - {#if data.chart && window} - - {/if} - {#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null} - - {/if} -
    + + diff --git a/apps/web/src/routes/(admin)/(auth)/admin/analytics/+page.server.ts b/apps/web/src/routes/(admin)/(auth)/admin/analytics/+page.server.ts new file mode 100644 index 0000000..ef5a29b --- /dev/null +++ b/apps/web/src/routes/(admin)/(auth)/admin/analytics/+page.server.ts @@ -0,0 +1,109 @@ +import { countBreakdownVisitsByTimeframe } from '@goto/analytics'; +import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily'; +import { isCanonicalPath, normalizeHost } from '@goto/config'; +import { error, redirect } from '@sveltejs/kit'; +import { scopeValue, type AnalyticsScope, type ScopeGroup } from '#lib/report-scopes.js'; +import type { ConfigurationSnapshot } from '#lib/server/snapshot.js'; +import { currentTags, tagMembers } from '#lib/server/tags/inventory.js'; +import { combineTagVisits } from '#lib/server/tags/visits.js'; +import { readLinkDetails, readVisitDetails } from '#lib/server/visits/reports.js'; +import type { PageServerLoad } from './$types'; + +export const load = (async ({ locals, url }) => { + const snapshot = locals.snapshot; + const retentionMonths = snapshot.configuration.analytics.retention_months; + if (retentionMonths === 0) redirect(307, '/admin/health'); + + const scope = selectedScope(url.searchParams); + const groups = scopeGroups(snapshot.domains); + const scopeUnavailable = !isConfiguredScope(scope, groups); + const timeframes = availableVisitTimeframes(retentionMonths); + const selection = { scope, groups, scopeUnavailable, retentionMonths, timeframes }; + if (scopeUnavailable) return { ...selection, report: null }; + + const details = await readScopeDetails(snapshot, scope); + if (!details) return { ...selection, report: null }; + + const windows = timeframes.map((timeframe) => ({ + timeframe, + window: visitWindow(details.period, timeframe) + })); + return { + ...selection, + report: { + period: details.period, + daily: details.daily, + lastActivityAt: details.lastActivityAt ? Date.parse(details.lastActivityAt) : null, + countsByTimeframe: countVisitWindows(details.daily, windows), + browserVisitsByTimeframe: countBreakdownVisitsByTimeframe(details.browsers, windows), + operatingSystemVisitsByTimeframe: countBreakdownVisitsByTimeframe( + details.operatingSystems, + windows + ), + acceptedLanguageVisitsByTimeframe: countBreakdownVisitsByTimeframe( + details.acceptedLanguages, + windows + ) + } + }; +}) satisfies PageServerLoad; + +function selectedScope(query: URLSearchParams): AnalyticsScope { + const domains = query.getAll('domain'); + const paths = query.getAll('path'); + const tags = query.getAll('tag'); + if (domains.length > 1 || paths.length > 1 || tags.length > 1) { + error(400, 'Select only one report scope'); + } + + const [domain] = domains; + const [path] = paths; + const [tag] = tags; + if (tag !== undefined) { + const conflictsWithTag = domain !== undefined || path !== undefined; + const tagIsBlank = tag.trim() === ''; + if (conflictsWithTag || tagIsBlank) error(400, 'Invalid tag selection'); + return { kind: 'tag', tag }; + } + if (domain !== undefined && normalizeHost(domain) !== domain) { + error(400, 'Invalid domain selection'); + } + if (path !== undefined) { + if (domain === undefined || !isCanonicalPath(path)) error(400, 'Invalid redirect selection'); + return { kind: 'link', domain, path }; + } + return domain === undefined ? { kind: 'overview' } : { kind: 'domain', domain }; +} + +function scopeGroups(domains: ConfigurationSnapshot['domains']): ScopeGroup[] { + const hosts = Object.keys(domains).sort(); + return [ + { label: 'Overview', scopes: [{ kind: 'overview' }] }, + { label: 'Domains', scopes: hosts.map((domain) => ({ kind: 'domain', domain })) }, + { + label: 'Redirects', + scopes: hosts.flatMap((domain) => + ['/', ...Object.keys(domains[domain]!.links).sort()].map((path) => ({ + kind: 'link', + domain, + path + })) + ) + }, + { label: 'Tags', scopes: currentTags(domains).map((tag) => ({ kind: 'tag', tag })) } + ]; +} + +function isConfiguredScope(scope: AnalyticsScope, groups: ScopeGroup[]): boolean { + const selectedValue = scopeValue(scope); + return groups.some(({ scopes }) => scopes.some((option) => scopeValue(option) === selectedValue)); +} + +async function readScopeDetails(snapshot: ConfigurationSnapshot, scope: AnalyticsScope) { + if (scope.kind !== 'tag') return readVisitDetails(snapshot.configuration, scope); + + const members = tagMembers(snapshot.domains, scope.tag); + const identities = members.map(({ domain, path }) => ({ domain, path })); + const report = await readLinkDetails(snapshot.configuration, identities); + return report ? combineTagVisits(report) : null; +} diff --git a/apps/web/src/routes/(admin)/(auth)/admin/analytics/+page.svelte b/apps/web/src/routes/(admin)/(auth)/admin/analytics/+page.svelte new file mode 100644 index 0000000..f579324 --- /dev/null +++ b/apps/web/src/routes/(admin)/(auth)/admin/analytics/+page.svelte @@ -0,0 +1,136 @@ + + + + {#snippet actions()} + {#if report} + + {/if} + {/snippet} +
    +
    0} + > + +
    + {#if counts} +
    + + +
    + {/if} +
    + {#if selectionNavigationFailed} + + {/if} + {#if data.scopeUnavailable} +

    + This report scope is no longer configured. Choose another scope or select All traffic. +

    + {:else} + + {/if} + {#if report && counts} + + + {/if} +
    + + diff --git a/apps/web/src/routes/(admin)/(auth)/admin/analytics/ReportScopePicker.svelte b/apps/web/src/routes/(admin)/(auth)/admin/analytics/ReportScopePicker.svelte new file mode 100644 index 0000000..8804198 --- /dev/null +++ b/apps/web/src/routes/(admin)/(auth)/admin/analytics/ReportScopePicker.svelte @@ -0,0 +1,268 @@ + + + committedValue, requestSelection} + bind:open + onOpenChange={handleOpenChange} + allowDeselect={false} +> +
    + + { + open = true; + }} + oninput={(event) => updateSearch(event.currentTarget.value)} + onkeydown={moveFromMissingHighlight} + > + {#snippet child({ props })} + + + {/snippet} + + + {#snippet child({ props })} + + {/snippet} + +
    + + + {#snippet child({ props, wrapperProps })} +
    +
    + + {#each matchingGroups as group (group.label)} + + + {group.label} + + {#each group.options as option (option.value)} + + {#snippet child({ props: optionProps, selected })} +
    + {option.label} + {#if selected}
    + {/snippet} +
    + {/each} +
    + {:else} +

    No matching report scopes.

    + {/each} +
    +
    +
    + {/snippet} +
    +
    +
    + + diff --git a/apps/web/src/routes/(admin)/(auth)/admin/analytics/page.server.test.ts b/apps/web/src/routes/(admin)/(auth)/admin/analytics/page.server.test.ts new file mode 100644 index 0000000..10a2c35 --- /dev/null +++ b/apps/web/src/routes/(admin)/(auth)/admin/analytics/page.server.test.ts @@ -0,0 +1,242 @@ +import { createVisitPeriod } from '@goto/analytics'; +import { loadConfig } from '@goto/config'; +import { beforeEach, expect, test, vi } from 'vitest'; +import { prepareSnapshot } from '#lib/server/snapshot.js'; +import { readLinkDetails, readVisitDetails } from '#lib/server/visits/reports.js'; +import { load } from './+page.server.js'; + +vi.mock('#lib/server/visits/reports.js', () => ({ + readVisitDetails: vi.fn(), + readLinkDetails: vi.fn() +})); +beforeEach(() => vi.resetAllMocks()); + +const configuredDomain = 'go.example.test'; +const tag = 'Work/100%é'; + +function request(retentionMonths: 0 | 3, query = '') { + const prepared = loadConfig( + { + auth: { credentials: { username: 'test', password: 'analytics-test-password' } }, + analytics: { retention_months: retentionMonths }, + domains: { + [configuredDomain]: { + links: { + '/a%2Fb': { url: 'https://example.test/literal' }, + '/a/b': { title: 'Nested docs', url: 'https://example.test/nested', tags: [tag] } + } + }, + 'other.example.test': { + links: { + '/a/b': { url: 'https://example.test/other', tags: [tag] }, + '/other': { url: 'https://example.test/untagged' } + } + } + } + }, + { env: {} } + ); + return { + locals: { snapshot: prepareSnapshot(prepared) }, + url: new URL(`https://admin.example.test/admin/analytics${query}`) + } as Parameters[0]; +} + +test('redirects to Health without reading a report when analytics is disabled', async () => { + await expect(load(request(0, `?${new URLSearchParams({ tag })}`))).rejects.toMatchObject({ + status: 307, + location: '/admin/health' + }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); +}); + +test('does not redirect when the global report is unavailable', async () => { + vi.mocked(readVisitDetails).mockResolvedValueOnce(null); + const unavailable = await load(request(3)); + expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), { + kind: 'overview' + }); + expect(unavailable).toMatchObject({ retentionMonths: 3, report: null }); +}); + +test('reads one report for the selected configured domain', async () => { + vi.mocked(readVisitDetails).mockResolvedValueOnce(null); + const data = await load(request(3, `?domain=${configuredDomain}`)); + expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), { + kind: 'domain', + domain: configuredDomain + }); + expect(data).toMatchObject({ + scope: { kind: 'domain', domain: configuredDomain }, + scopeUnavailable: false + }); + expect(data.groups).toEqual([ + { label: 'Overview', scopes: [{ kind: 'overview' }] }, + { + label: 'Domains', + scopes: [ + { kind: 'domain', domain: configuredDomain }, + { kind: 'domain', domain: 'other.example.test' } + ] + }, + { + label: 'Redirects', + scopes: [ + { kind: 'link', domain: configuredDomain, path: '/' }, + { kind: 'link', domain: configuredDomain, path: '/a%2Fb' }, + { kind: 'link', domain: configuredDomain, path: '/a/b' }, + { kind: 'link', domain: 'other.example.test', path: '/' }, + { kind: 'link', domain: 'other.example.test', path: '/a/b' }, + { kind: 'link', domain: 'other.example.test', path: '/other' } + ] + }, + { label: 'Tags', scopes: [{ kind: 'tag', tag }] } + ]); +}); + +test.each(['/', '/a%2Fb', '/a/b'])('reads one report for the exact redirect %s', async (path) => { + vi.mocked(readVisitDetails).mockResolvedValueOnce(null); + const query = new URLSearchParams({ domain: configuredDomain, path }); + const data = await load(request(3, `?${query}`)); + + expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), { + kind: 'link', + domain: configuredDomain, + path + }); + expect(data).toMatchObject({ + scope: { kind: 'link', domain: configuredDomain, path }, + scopeUnavailable: false + }); +}); + +test.each([ + '?path=%2F', + `?domain=${configuredDomain}&path=`, + `?domain=${configuredDomain}&path=%2Fa%2F..%2Fb`, + `?domain=${configuredDomain}&path=%2F&path=%2Fa%2Fb` +])('rejects an invalid redirect query without reading a report: %s', async (query) => { + await expect(load(request(3, query))).rejects.toMatchObject({ status: 400 }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); +}); + +test('does not read a broader report for a redirect missing from the selected domain', async () => { + const data = await load(request(3, `?domain=${configuredDomain}&path=%2Fother`)); + expect(data).toMatchObject({ + scope: { kind: 'link', domain: configuredDomain, path: '/other' }, + scopeUnavailable: true, + report: null + }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); +}); + +test.each([`?domain=${configuredDomain}&domain=tiny.example.test`, '?domain=GO.EXAMPLE.TEST'])( + 'rejects an invalid domain query without reading a report: %s', + async (query) => { + await expect(load(request(3, query))).rejects.toMatchObject({ status: 400 }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); + } +); + +test('keeps a removed domain selection without falling back to the global report', async () => { + const data = await load(request(3, '?domain=removed.example.test')); + expect(data).toMatchObject({ + scope: { kind: 'domain', domain: 'removed.example.test' }, + scopeUnavailable: true, + report: null + }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); +}); + +test('reads one batch for the exact tag across domains, excluding other paths', async () => { + vi.mocked(readLinkDetails).mockResolvedValueOnce(null); + const data = await load(request(3, `?${new URLSearchParams({ tag })}`)); + expect(readLinkDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [ + { domain: configuredDomain, path: '/a/b' }, + { domain: 'other.example.test', path: '/a/b' } + ]); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(data).toMatchObject({ + scope: { kind: 'tag', tag }, + scopeUnavailable: false, + report: null + }); +}); + +test.each([ + '?tag=', + '?tag=Work&tag=Docs', + `?tag=Work&domain=${configuredDomain}`, + '?tag=Work&path=%2F' +])('rejects malformed or mixed tag selections: %s', async (query) => { + await expect(load(request(3, query))).rejects.toMatchObject({ status: 400 }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); +}); + +test('does not fall back to all traffic for a stale tag', async () => { + const data = await load(request(3, '?tag=Removed')); + expect(data).toMatchObject({ + scope: { kind: 'tag', tag: 'Removed' }, + scopeUnavailable: true, + report: null + }); + expect(readVisitDetails).not.toHaveBeenCalled(); + expect(readLinkDetails).not.toHaveBeenCalled(); +}); + +test('projects global totals and keeps each breakdown tied to the selected window', async () => { + const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z')); + const recent = { day: '2026-06-01', validVisits: 3, invalidVisits: 1 }; + const older = { day: '2026-05-01', validVisits: 2, invalidVisits: 4 }; + vi.mocked(readVisitDetails).mockResolvedValueOnce({ + version: 5, + scope: { kind: 'overview' }, + period, + lastActivityAt: '2026-06-01T12:00:00.000Z', + daily: [ + { + start: '2026-05-01T00:00:00.000Z', + end: '2026-05-02T00:00:00.000Z', + partial: false, + validVisits: older.validVisits, + invalidVisits: older.invalidVisits + }, + { + start: '2026-06-01T00:00:00.000Z', + end: '2026-06-02T00:00:00.000Z', + partial: false, + validVisits: recent.validVisits, + invalidVisits: recent.invalidVisits + } + ], + browsers: [ + { ...older, name: 'Chrome' }, + { ...recent, name: 'Firefox' } + ], + operatingSystems: [ + { ...older, name: 'Windows' }, + { ...recent, name: 'Linux' } + ], + acceptedLanguages: [ + { ...older, name: 'fr' }, + { ...recent, name: 'en' } + ] + }); + + const { report } = await load(request(3)); + + expect(report?.countsByTimeframe).toEqual({ + '7d': { validVisits: 0, invalidVisits: 0 }, + '30d': { validVisits: 3, invalidVisits: 1 }, + all: { validVisits: 5, invalidVisits: 5 } + }); + expect(report?.browserVisitsByTimeframe['30d']).toEqual([{ name: 'Firefox', visits: 3 }]); + expect(report?.operatingSystemVisitsByTimeframe['30d']).toEqual([{ name: 'Linux', visits: 3 }]); + expect(report?.acceptedLanguageVisitsByTimeframe['30d']).toEqual([{ name: 'en', visits: 3 }]); +}); diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.server.ts b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.server.ts index 61a4540..f199de9 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.server.ts +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.server.ts @@ -1,89 +1,51 @@ import { error } from '@sveltejs/kit'; -import { countBreakdownVisitsByTimeframe } from '@goto/analytics'; -import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily'; import { linkHref } from '#lib/components/admin/urls.js'; import { currentLinkState } from '#lib/server/link-state.js'; -import { readDomainDetails } from '#lib/server/visits/reports.js'; +import { readLastActivity } from '#lib/server/visits/reports.js'; +import { readDomainLifetimeVisitTotals } from '#lib/server/visits/totals.js'; import type { PageServerLoad } from './$types'; export const load = (async ({ locals, params }) => { - const snapshot = locals.snapshot; + const { configuration, domains } = locals.snapshot; const domain = params.domain; - if (!Object.hasOwn(snapshot.domains, domain)) throw error(404, 'Domain not configured'); - const prepared = snapshot.domains[domain]!; - const configuration = snapshot.configuration; - const retentionMonths = configuration.analytics.retention_months; - const collectionEnabled = retentionMonths !== 0; - const currentPaths = Object.keys(prepared.links); - let report: Awaited> = null; - if (collectionEnabled) { - report = await readDomainDetails(configuration, domain, currentPaths); - } - const domainDetails = report?.domain ?? null; - const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths); - const windows = domainDetails - ? timeframes.map((timeframe) => ({ - timeframe, - window: visitWindow(domainDetails.period, timeframe) - })) - : []; - const detailsByPath = new Map(report?.links.map(({ path, details }) => [path, details])); - const countsByTimeframe = countVisitWindows(domainDetails?.daily, windows); - const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe( - domainDetails?.browsers, - windows + if (!Object.hasOwn(domains, domain)) error(404, 'Domain not configured'); + + const prepared = domains[domain]!; + const namedLinks = Object.entries(prepared.links); + const analyticsEnabled = configuration.analytics.retention_months !== 0; + const totals = await readDomainLifetimeVisitTotals( + configuration, + domain, + Object.keys(prepared.links) ); - const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe( - domainDetails?.operatingSystems, - windows - ); - const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe( - domainDetails?.acceptedLanguages, - windows - ); - let rootUrl: string | null = null; - if (prepared.root !== null) rootUrl = prepared.root.url; - else if (prepared.fallback !== null) rootUrl = prepared.fallback.url; - const rootCountsByTimeframe = countVisitWindows(detailsByPath.get('/')?.daily, windows); - const rootHref = linkHref(domain, '/'); + const activity = analyticsEnabled + ? await readLastActivity(configuration, { kind: 'domain', domain }) + : null; const now = Date.now(); const links = [ { path: '/', - url: rootUrl, + url: prepared.root?.url ?? prepared.fallback?.url ?? null, state: 'active' as const, - countsByTimeframe: rootCountsByTimeframe, - href: rootHref + visits: totals?.byPath.get('/')?.validVisits ?? null, + href: linkHref(domain, '/') }, - ...Object.entries(prepared.links).map(([path, link]) => { - const daily = detailsByPath.get(path)?.daily; - const countsByTimeframe = countVisitWindows(daily, windows); - return { - path, - url: link.url, - state: currentLinkState(link, now, locals.application.linkVisitCount(domain, path)), - countsByTimeframe, - href: linkHref(domain, path) - }; - }) + ...namedLinks.map(([path, link]) => ({ + path, + url: link.url, + state: currentLinkState(link, now, locals.application.linkVisitCount(domain, path)), + visits: totals?.byPath.get(path)?.validVisits ?? null, + href: linkHref(domain, path) + })) ]; - const lastActivityAt = domainDetails?.lastActivityAt - ? Date.parse(domainDetails.lastActivityAt) - : null; - const chart = domainDetails ? { daily: domainDetails.daily, period: domainDetails.period } : null; + return { domain, - retentionMonths, - collectionEnabled, - available: domainDetails !== null, - lastActivityAt, - linkCount: currentPaths.length, - timeframes, - countsByTimeframe, - browserVisitsByTimeframe, - operatingSystemVisitsByTimeframe, - acceptedLanguageVisitsByTimeframe, - chart, + analyticsEnabled, + lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null, + linkCount: namedLinks.length, + totalVisits: totals?.domain.validVisits ?? null, + invalidClicks: totals?.domain.invalidVisits ?? null, root: prepared.root, fallback: prepared.fallback, links diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.svelte b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.svelte index dd88e13..eba41ee 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.svelte +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/+page.svelte @@ -1,94 +1,65 @@ - {#snippet actions()} - {#if data.available && data.timeframes.length > 0} - - {/if} - {/snippet} -
    +
    +

    Summary

    +
    + {#if data.totalVisits === null} +

    Visit totals unavailable.

    + {/if} +
    + + + +
    +
    +
    +

    Details

    -
    -
    Domain
    -
    {data.domain}
    -
    Root
    -
    - {#if data.root} - {data.root.url} - {:else}Uses fallback{/if} -
    -
    Fallback
    -
    - {#if data.fallback} - {data.fallback.url} - {:else}404 Not found{/if} -
    -
    +
    +
    +
    Domain
    +
    {data.domain}
    +
    Root
    +
    + {#if data.root} + {data.root.url} + {:else}Uses fallback{/if} +
    +
    Fallback
    +
    + {#if data.fallback} + {data.fallback.url} + {:else}404 Not found{/if} +
    + {#if data.analyticsEnabled} + + {/if} +
    +

    Links

    - +
    - - -
    - - {#if data.collectionEnabled} - - - {/if} -
    - {#if data.chart && window} - - {/if} - {#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null} - - {/if} -
    + + diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.server.ts b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.server.ts index 018f6f4..f773bdc 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.server.ts +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.server.ts @@ -1,7 +1,5 @@ import { error } from '@sveltejs/kit'; -import { countBreakdownVisitsByTimeframe } from '@goto/analytics'; -import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily'; -import { readVisitDetails } from '#lib/server/visits/reports.js'; +import { readLastActivity } from '#lib/server/visits/reports.js'; import { readLifetimeVisitTotals } from '#lib/server/visits/totals.js'; import type { PageServerLoad } from './$types'; @@ -13,47 +11,19 @@ export const load = (async ({ locals, params }) => { const response = prepared.root; const fallback = prepared.fallback; const configuration = snapshot.configuration; - const retentionMonths = configuration.analytics.retention_months; - const collectionEnabled = retentionMonths !== 0; + const analyticsEnabled = configuration.analytics.retention_months !== 0; const scope = { kind: 'link' as const, domain, path: '/' }; - const lifetimeVisitTotals = await readLifetimeVisitTotals(configuration, scope); - let details: Awaited> = null; - if (collectionEnabled) { - details = await readVisitDetails(configuration, scope); - } - const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths); - const windows = details - ? timeframes.map((timeframe) => ({ timeframe, window: visitWindow(details.period, timeframe) })) - : []; - const countsByTimeframe = countVisitWindows(details?.daily, windows); - const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(details?.browsers, windows); - const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe( - details?.operatingSystems, - windows - ); - const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe( - details?.acceptedLanguages, - windows - ); - const lastActivityAt = details?.lastActivityAt ? Date.parse(details.lastActivityAt) : null; - const chart = details ? { daily: details.daily, period: details.period } : null; + const totals = await readLifetimeVisitTotals(configuration, scope); + const activity = analyticsEnabled ? await readLastActivity(configuration, scope) : null; return { domain, - lifetimeVisitTotals, + totalVisits: totals?.validVisits ?? null, domainHref: `/admin/domains/${encodeURIComponent(domain)}`, response, fallback, fallbackSource: prepared.provenance.fallback, - retentionMonths, - collectionEnabled, - available: details !== null, - lastActivityAt, - timeframes, - countsByTimeframe, - browserVisitsByTimeframe, - operatingSystemVisitsByTimeframe, - acceptedLanguageVisitsByTimeframe, - chart + analyticsEnabled, + lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null }; }) satisfies PageServerLoad; diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.svelte b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.svelte index 01cc27e..be3a61d 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.svelte +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/+page.svelte @@ -1,115 +1,91 @@ - {#snippet actions()} - {#if data.available && data.timeframes.length > 0} - - {/if} - {/snippet} -
    -

    Root details

    -
    -
    Domain
    -
    {data.domain}
    -
    Address
    -
    {data.domain}/
    -
    All-time visits
    -
    {formatCount(data.lifetimeVisitTotals?.validVisits ?? null)}
    -
    Destination
    -
    - {#if data.response} - - {data.response.url} - - {:else} - Uses fallback - {/if} -
    - {#if data.response} -
    HTTP status
    -
    {data.response.status_code}
    -
    Forward query
    -
    {data.response.forward_query ? 'Yes' : 'No'}
    - {/if} -
    -
    -
    -

    Fallback

    -
    -
    Source
    -
    - {#if data.fallbackSource === 'domain'}Domain - {:else if data.fallbackSource === 'global'}Global - {:else}Default{/if} -
    -
    Destination
    -
    - {#if data.fallback} - - {data.fallback.url} - - {:else}404 Not found{/if} -
    - {#if data.fallback} -
    HTTP status
    -
    {data.fallback.status_code}
    -
    Forward query
    -
    {data.fallback.forward_query ? 'Yes' : 'No'}
    - {/if} -
    -
    - - -
    - {#if data.collectionEnabled} - +
    +

    Summary

    +
    + {#if data.totalVisits === null} +

    Visit totals unavailable.

    {/if} +
    + +
    - {#if data.chart && window} - - {/if} - {#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null} - - {/if} - +
    +
    +

    Root details

    +
    +
    +
    Domain
    +
    {data.domain}
    +
    Address
    +
    {data.domain}/
    +
    Destination
    +
    + {#if data.response} + + {data.response.url} + + {:else} + Uses fallback + {/if} +
    + {#if data.response} +
    HTTP status
    +
    {data.response.status_code}
    +
    Forward query
    +
    {data.response.forward_query ? 'Yes' : 'No'}
    + {/if} + {#if data.analyticsEnabled} + + {/if} +
    +
    +
    +
    +

    Fallback

    +
    +
    +
    Source
    +
    + {#if data.fallbackSource === 'domain'}Domain + {:else if data.fallbackSource === 'global'}Global + {:else}Default{/if} +
    +
    Destination
    +
    + {#if data.fallback} + + {data.fallback.url} + + {:else}404 Not found{/if} +
    + {#if data.fallback} +
    HTTP status
    +
    {data.fallback.status_code}
    +
    Forward query
    +
    {data.fallback.forward_query ? 'Yes' : 'No'}
    + {/if} +
    +
    +
    + + diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.server.ts b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.server.ts index 9afab55..d98f60f 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.server.ts +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.server.ts @@ -1,8 +1,6 @@ import { error } from '@sveltejs/kit'; -import { countBreakdownVisitsByTimeframe } from '@goto/analytics'; -import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily'; import { currentLinkState } from '#lib/server/link-state.js'; -import { readVisitDetails } from '#lib/server/visits/reports.js'; +import { readLastActivity } from '#lib/server/visits/reports.js'; import type { PageServerLoad } from './$types'; export const load = (async ({ locals, params }) => { @@ -29,29 +27,10 @@ export const load = (async ({ locals, params }) => { const validFrom = link.valid_from ?? null; const validUntil = link.valid_until ?? null; const configuration = snapshot.configuration; - const retentionMonths = configuration.analytics.retention_months; - const collectionEnabled = retentionMonths !== 0; - const scope = { kind: 'link' as const, domain, path }; - let details: Awaited> = null; - if (collectionEnabled) { - details = await readVisitDetails(configuration, scope); - } - const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths); - const windows = details - ? timeframes.map((timeframe) => ({ timeframe, window: visitWindow(details.period, timeframe) })) - : []; - const countsByTimeframe = countVisitWindows(details?.daily, windows); - const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(details?.browsers, windows); - const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe( - details?.operatingSystems, - windows - ); - const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe( - details?.acceptedLanguages, - windows - ); - const lastActivityAt = details?.lastActivityAt ? Date.parse(details.lastActivityAt) : null; - const chart = details ? { daily: details.daily, period: details.period } : null; + const analyticsEnabled = configuration.analytics.retention_months !== 0; + const activity = analyticsEnabled + ? await readLastActivity(configuration, { kind: 'link', domain, path }) + : null; return { domain, @@ -68,15 +47,7 @@ export const load = (async ({ locals, params }) => { validFrom, validUntil, tags: link.tags, - retentionMonths, - collectionEnabled, - available: details !== null, - lastActivityAt, - timeframes, - countsByTimeframe, - browserVisitsByTimeframe, - operatingSystemVisitsByTimeframe, - acceptedLanguageVisitsByTimeframe, - chart + analyticsEnabled, + lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null }; }) satisfies PageServerLoad; diff --git a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.svelte b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.svelte index bcf2b55..eaaa7c4 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.svelte +++ b/apps/web/src/routes/(admin)/(auth)/admin/domains/[domain]/links/[...path]/+page.svelte @@ -1,177 +1,138 @@ - {#snippet actions()} - {#if data.available && data.timeframes.length > 0} - - {/if} - {/snippet} -
    -

    Redirect

    -
    -
    Domain
    -
    - - {data.domain} - -
    -
    Path
    -
    {data.path}
    - {#if data.linkTitle} -
    Title
    -
    {data.linkTitle}
    - {/if} -
    Destination
    -
    0}> - {#if data.redirectRules.length > 0} -
      - {#each data.redirectRules as rule, index (index)} -
    1. - - {rule.to} -
    2. - {/each} -
    3. - - {data.response.url} -
    4. -
    - {:else} - {data.response.url} - {/if} -
    - {#if data.redirectRules.length > 0} -
    Rules
    -
    -
      - {#each data.redirectRules as rule, index (index)} -
    1. - - - {#if rule.language !== null && rule.os !== null} - language {rule.language} AND OS {rule.os} - {:else if rule.language !== null} - language {rule.language} - {:else} - OS {rule.os} - {/if} - -
    2. - {/each} -
    3. - - default -
    4. -
    -
    - {/if} -
    Visits
    -
    {formatCount(data.lifetimeVisits)} (all time)
    -
    -
    -
    -

    Settings

    -
    -
    HTTP status
    -
    {data.response.status_code}
    -
    Case insensitive
    -
    {data.caseInsensitive ? 'Yes' : 'No'}
    -
    Trailing slash
    -
    {data.ignoreTrailingSlash ? 'Yes' : 'No'}
    -
    Path forwarding
    -
    {data.forwardPath ? 'Yes' : 'No'}
    -
    Query forwarding
    -
    {data.response.forward_query ? 'Yes' : 'No'}
    - {#if data.maxVisits !== null} -
    Max visits
    -
    {formatCount(data.maxVisits)}
    - {/if} - {#if data.validFrom} -
    Starts
    -
    - -
    - {/if} - {#if data.validUntil} -
    Expires
    -
    - -
    - {/if} - {#if data.tags.length > 0} -
    Tags
    -
    - {/if} -
    -
    - - +
    +

    Summary

    - {#if data.collectionEnabled} - - {/if} - {#if data.state === 'active'} - - {:else if data.state === 'disabled'} - - {:else if data.state === 'scheduled'} - - {:else if data.state === 'expired'} - - {:else if data.state === 'exhausted'} - + + + {#if data.maxVisits !== null} + {/if}
    - {#if data.chart && window} - - {/if} - {#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null} - - {/if} - +
    +
    +

    Redirect

    +
    +
    +
    Domain
    +
    + + {data.domain} + +
    +
    Path
    +
    {data.path}
    + {#if data.linkTitle} +
    Title
    +
    {data.linkTitle}
    + {/if} +
    Destination
    +
    0}> + {#if data.redirectRules.length > 0} +
      + {#each data.redirectRules as rule, index (index)} +
    1. + + {rule.to} +
    2. + {/each} +
    3. + + {data.response.url} +
    4. +
    + {:else} + {data.response.url} + {/if} +
    + {#if data.redirectRules.length > 0} +
    Rules
    +
    +
      + {#each data.redirectRules as rule, index (index)} +
    1. + + + {#if rule.language !== null && rule.os !== null} + language {rule.language} AND OS {rule.os} + {:else if rule.language !== null} + language {rule.language} + {:else} + OS {rule.os} + {/if} + +
    2. + {/each} +
    3. + + default +
    4. +
    +
    + {/if} + {#if data.analyticsEnabled} + + {/if} +
    +
    +
    +
    +

    Settings

    +
    +
    +
    HTTP status
    +
    {data.response.status_code}
    +
    Case insensitive
    +
    {data.caseInsensitive ? 'Yes' : 'No'}
    +
    Trailing slash
    +
    {data.ignoreTrailingSlash ? 'Yes' : 'No'}
    +
    Path forwarding
    +
    {data.forwardPath ? 'Yes' : 'No'}
    +
    Query forwarding
    +
    {data.response.forward_query ? 'Yes' : 'No'}
    + {#if data.validFrom} +
    Starts
    +
    + +
    + {/if} + {#if data.validUntil} +
    Expires
    +
    + +
    + {/if} + {#if data.tags.length > 0} +
    Tags
    +
    + {/if} +
    +
    +
    diff --git a/apps/web/src/routes/(admin)/(auth)/admin/tags/[tag]/page.server.test.ts b/apps/web/src/routes/(admin)/(auth)/admin/tags/[tag]/page.server.test.ts index 68075c7..35b6474 100644 --- a/apps/web/src/routes/(admin)/(auth)/admin/tags/[tag]/page.server.test.ts +++ b/apps/web/src/routes/(admin)/(auth)/admin/tags/[tag]/page.server.test.ts @@ -1,58 +1,54 @@ -import { createVisitPeriod, visitDays, type VisitDetails } from '@goto/analytics'; import { loadConfig } from '@goto/config'; -import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { beforeEach, expect, test, vi } from 'vitest'; import type { Application } from '#lib/server/application.js'; import { prepareSnapshot } from '#lib/server/snapshot.js'; -import { readLinkDetails } from '#lib/server/visits/reports.js'; +import { readLastActivity } from '#lib/server/visits/reports.js'; import { load } from './+page.server.js'; -vi.mock('#lib/server/visits/reports.js', () => ({ readLinkDetails: vi.fn() })); +vi.mock('#lib/server/visits/reports.js', () => ({ readLastActivity: vi.fn() })); beforeEach(() => { vi.resetAllMocks(); - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(new Date('2026-06-15T13:00:00.000Z')); + vi.mocked(readLastActivity).mockResolvedValue({ available: false, lastActivityAt: null }); }); -afterEach(() => vi.useRealTimers()); const tag = 'Work/100%é'; const firstDomain = 'go.example.test'; const secondDomain = 'tiny.example.test'; -const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z')); -const domains = { - [firstDomain]: { - root: { url: 'https://example.test/start' }, - links: { - '/docs': { url: 'https://example.test/docs', tags: [tag, tag, 'work'] }, - '/a%2Fb': { url: 'https://example.test/percent', tags: ['%2F'], enabled: false } - } - }, - [secondDomain]: { - links: { - '/docs': { url: 'https://example.test/other', tags: [tag], enabled: false }, - '/other': { url: 'https://example.test/unrelated', tags: [] } - } - } +const visitsByDomain: Record> = { + [firstDomain]: { '/docs': 100, '/guide': 3, '/a%2Fb': 4 }, + [secondDomain]: { '/docs': 6, '/other': 200 } }; -function request( +function request({ selectedTag = tag, - settings: { - retentionMonths?: number; - domains?: Record; - visits?: Record>; - } = {} -) { + retentionMonths = 3, + firstLinkTags = [tag, tag, 'work'] +}: { selectedTag?: string; retentionMonths?: 0 | 3; firstLinkTags?: string[] } = {}) { const prepared = loadConfig( { auth: { credentials: { username: 'test', password: 'tag-page-test-password' } }, - analytics: { retention_months: settings.retentionMonths ?? 3 }, - domains: settings.domains ?? domains + analytics: { retention_months: retentionMonths }, + domains: { + [firstDomain]: { + links: { + '/docs': { url: 'https://example.test/docs', tags: firstLinkTags, max_visits: 100 }, + '/guide': { url: 'https://example.test/guide', tags: [tag] }, + '/a%2Fb': { url: 'https://example.test/percent', tags: ['%2F'], enabled: false } + } + }, + [secondDomain]: { + links: { + '/docs': { url: 'https://example.test/other', tags: [tag], max_visits: 100 }, + '/other': { url: 'https://example.test/unrelated' } + } + } + } }, { env: {} } ); const snapshot = prepareSnapshot(prepared); const linkVisitCount = vi.fn( - (domain: string, path: string): number => settings.visits?.[domain]?.[path] ?? 0 + (domain: string, path: string) => visitsByDomain[domain]?.[path] ?? 0 ); const application: Application = { currentSnapshot: () => snapshot, linkVisitCount }; return { @@ -61,265 +57,88 @@ function request( } as Parameters[0]; } -function details( - domain: string, - path: string, - counts: Record, - browser: string -): VisitDetails { - const daily = visitDays(period).map((day) => { - const [validVisits, invalidVisits] = counts[day.start.slice(0, 10)] ?? [0, 0]; - return { ...day, validVisits, invalidVisits }; - }); - const browsers = daily - .filter(({ validVisits, invalidVisits }) => validVisits > 0 || invalidVisits > 0) - .map(({ start, validVisits, invalidVisits }) => ({ - day: start.slice(0, 10), - name: browser, - validVisits, - invalidVisits - })); - const lastDay = Object.keys(counts).sort().at(-1); - return { - version: 5, - lastActivityAt: lastDay ? `${lastDay}T10:00:00.000Z` : null, - scope: { kind: 'link', domain, path }, - period, - daily, - browsers, - operatingSystems: browsers.map((row) => ({ ...row, name: 'Other' })), - acceptedLanguages: browsers.flatMap((row) => [ - { ...row, name: 'en' }, - { ...row, name: 'fr' } - ]) - }; -} +test('uses each current link lifetime count once for the summary, inventory, and status', async () => { + const lastActivityAt = '2026-06-15T10:00:00.000Z'; + vi.mocked(readLastActivity).mockResolvedValue({ available: true, lastActivityAt }); + const event = request(); + const data = await load(event); -const firstDetails = details( - firstDomain, - '/docs', - { - '2026-05-20': [2, 1], - '2026-06-15': [3, 2] - }, - 'Firefox' -); -const secondDetails = details( - secondDomain, - '/docs', - { - '2026-03-17': [5, 3], - '2026-06-09': [4, 1] - }, - 'Chrome' -); -const report = { - period, - links: [ - { domain: firstDomain, path: '/docs', details: firstDetails }, - { domain: secondDomain, path: '/docs', details: secondDetails } - ] -}; - -test('projects complete tag traffic and globally distinct member rows without leaking member series', async () => { - vi.mocked(readLinkDetails).mockResolvedValue(report); - const data = await load(request()); - expect(readLinkDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [ - { domain: firstDomain, path: '/docs' }, - { domain: secondDomain, path: '/docs' } - ]); expect(data).toEqual({ tag, - retentionMonths: 3, - collectionEnabled: true, - available: true, - lastActivityAt: Date.parse(firstDetails.lastActivityAt!), - linkCount: 2, - timeframes: ['7d', '30d', 'all'], - countsByTimeframe: { - '7d': { validVisits: 7, invalidVisits: 3 }, - '30d': { validVisits: 9, invalidVisits: 4 }, - all: { validVisits: 14, invalidVisits: 7 } - }, - acceptedLanguageVisitsByTimeframe: { - '7d': [ - { name: 'en', visits: 7 }, - { name: 'fr', visits: 7 } - ], - '30d': [ - { name: 'en', visits: 9 }, - { name: 'fr', visits: 9 } - ], - all: [ - { name: 'en', visits: 14 }, - { name: 'fr', visits: 14 } - ] - }, - browserVisitsByTimeframe: { - '7d': [ - { name: 'Chrome', visits: 4 }, - { name: 'Firefox', visits: 3 } - ], - '30d': [ - { name: 'Firefox', visits: 5 }, - { name: 'Chrome', visits: 4 } - ], - all: [ - { name: 'Chrome', visits: 9 }, - { name: 'Firefox', visits: 5 } - ] - }, - operatingSystemVisitsByTimeframe: { - '7d': [{ name: 'Other', visits: 7 }], - '30d': [{ name: 'Other', visits: 9 }], - all: [{ name: 'Other', visits: 14 }] - }, - chart: { period, daily: expect.any(Array) }, + analyticsEnabled: true, + lastActivityAt: Date.parse(lastActivityAt), + domainCount: 2, + totalVisits: 109, links: [ { domain: firstDomain, path: '/docs', - state: 'active', - countsByTimeframe: { - '7d': { validVisits: 3, invalidVisits: 2 }, - '30d': { validVisits: 5, invalidVisits: 3 }, - all: { validVisits: 5, invalidVisits: 3 } - }, + state: 'exhausted', + visits: 100, href: '/admin/domains/go.example.test/links/docs' }, + { + domain: firstDomain, + path: '/guide', + state: 'active', + visits: 3, + href: '/admin/domains/go.example.test/links/guide' + }, { domain: secondDomain, path: '/docs', - state: 'disabled', - countsByTimeframe: { - '7d': { validVisits: 4, invalidVisits: 1 }, - '30d': { validVisits: 4, invalidVisits: 1 }, - all: { validVisits: 9, invalidVisits: 4 } - }, + state: 'active', + visits: 6, href: '/admin/domains/tiny.example.test/links/docs' } ] }); - expect(data.chart?.daily).toHaveLength(visitDays(period).length); - expect(data.chart?.daily.at(-1)).toMatchObject({ - validVisits: 3, - invalidVisits: 2, - partial: true - }); + expect(vi.mocked(event.locals.application.linkVisitCount).mock.calls).toEqual([ + [firstDomain, '/docs'], + [firstDomain, '/guide'], + [secondDomain, '/docs'] + ]); + expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [ + { kind: 'link', domain: firstDomain, path: '/docs' }, + { kind: 'link', domain: firstDomain, path: '/guide' }, + { kind: 'link', domain: secondDomain, path: '/docs' } + ]); }); -test('current membership reassigns unchanged prepared history without tag-specific reports', async () => { - vi.mocked(readLinkDetails).mockResolvedValue({ period, links: [report.links[1]!] }); - const data = await load( - request(tag, { - domains: { - [firstDomain]: { - links: { '/docs': { url: 'https://example.test/docs', tags: ['Different'] } } - }, - [secondDomain]: domains[secondDomain] +test('keeps current-member totals when retained activity is unavailable', async () => { + const data = await load(request({ firstLinkTags: ['Different'] })); + expect(data.totalVisits).toBe(9); + expect(data.lastActivityAt).toBeNull(); + expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [ + { kind: 'link', domain: firstDomain, path: '/guide' }, + { kind: 'link', domain: secondDomain, path: '/docs' } + ]); +}); + +test('keeps literal percent identities and shows lifetime visits at zero retention', async () => { + const data = await load(request({ selectedTag: '%2F', retentionMonths: 0 })); + expect(readLastActivity).not.toHaveBeenCalled(); + expect(data).toEqual({ + tag: '%2F', + analyticsEnabled: false, + lastActivityAt: null, + domainCount: 1, + totalVisits: 4, + links: [ + { + domain: firstDomain, + path: '/a%2Fb', + state: 'disabled', + visits: 4, + href: '/admin/domains/go.example.test/links/a%252Fb' } - }) - ); - expect(readLinkDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [ - { domain: secondDomain, path: '/docs' } - ]); - expect(data.linkCount).toBe(1); - expect(data.lastActivityAt).toBe(Date.parse(secondDetails.lastActivityAt!)); - expect(data.countsByTimeframe.all).toEqual({ validVisits: 9, invalidVisits: 4 }); - expect(data.links.map(({ domain, path }) => ({ domain, path }))).toEqual([ - { domain: secondDomain, path: '/docs' } - ]); -}); - -test('uses the already decoded literal parameter without decoding percent escapes again', async () => { - const percentDetails = details(firstDomain, '/a%2Fb', {}, 'Other'); - vi.mocked(readLinkDetails).mockResolvedValue({ - period, - links: [{ domain: firstDomain, path: '/a%2Fb', details: percentDetails }] + ] }); - const event = request('%2F'); - const data = await load(event); - expect(event.locals.application.linkVisitCount).toHaveBeenCalledExactlyOnceWith( - firstDomain, - '/a%2Fb' - ); - expect(data.tag).toBe('%2F'); - expect(data.lastActivityAt).toBeNull(); - expect(data.countsByTimeframe.all).toEqual({ validVisits: 0, invalidVisits: 0 }); - expect(data.acceptedLanguageVisitsByTimeframe).toEqual({ '7d': [], '30d': [], all: [] }); - expect(data.links[0]?.href).toBe('/admin/domains/go.example.test/links/a%252Fb'); }); -test('unknown literal labels return 404 before reading reports', async () => { - await expect(load(request('work/100%é'))).rejects.toMatchObject({ status: 404 }); - expect(readLinkDetails).not.toHaveBeenCalled(); -}); - -test('unavailable reports preserve all current members but expose no partial traffic', async () => { - vi.mocked(readLinkDetails).mockResolvedValue(null); - const data = await load(request()); - expect(data.available).toBe(false); - expect(data.lastActivityAt).toBeNull(); - expect(data.countsByTimeframe).toEqual({}); - expect(data.acceptedLanguageVisitsByTimeframe).toEqual({}); - expect(data.browserVisitsByTimeframe).toEqual({}); - expect(data.operatingSystemVisitsByTimeframe).toEqual({}); - expect(data.chart).toBeNull(); - expect(data.linkCount).toBe(2); - expect(data.links.map(({ countsByTimeframe }) => countsByTimeframe)).toEqual([{}, {}]); - expect(data.links.map(({ href }) => href)).toEqual([ - '/admin/domains/go.example.test/links/docs', - '/admin/domains/tiny.example.test/links/docs' - ]); -}); - -test.each([0, 3])( - 'tag rows use domain-specific live counts with %i-month analytics', - async (retentionMonths) => { - vi.mocked(readLinkDetails).mockResolvedValue(report); - const event = request(tag, { - retentionMonths, - domains: { - [firstDomain]: { - links: { '/docs': { url: 'https://example.test/docs', tags: [tag], max_visits: 100 } } - }, - [secondDomain]: { - links: { '/docs': { url: 'https://example.test/other', tags: [tag], max_visits: 100 } } - } - }, - visits: { [firstDomain]: { '/docs': 100 }, [secondDomain]: { '/docs': 3 } } - }); - const data = await load(event); - expect(data.links.map(({ domain, path, state }) => ({ domain, path, state }))).toEqual([ - { domain: firstDomain, path: '/docs', state: 'exhausted' }, - { domain: secondDomain, path: '/docs', state: 'active' } - ]); - expect(event.locals.application.linkVisitCount).toHaveBeenCalledTimes(2); - expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith( - 1, - firstDomain, - '/docs' - ); - expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith( - 2, - secondDomain, - '/docs' - ); - } -); - -test('zero retention skips the report reader and keeps tag inventory without traffic controls', async () => { - const data = await load(request(tag, { retentionMonths: 0 })); - expect(readLinkDetails).not.toHaveBeenCalled(); - expect(data.collectionEnabled).toBe(false); - expect(data.available).toBe(false); - expect(data.lastActivityAt).toBeNull(); - expect(data.timeframes).toEqual([]); - expect(data.countsByTimeframe).toEqual({}); - expect(data.acceptedLanguageVisitsByTimeframe).toEqual({}); - expect(data.browserVisitsByTimeframe).toEqual({}); - expect(data.operatingSystemVisitsByTimeframe).toEqual({}); - expect(data.chart).toBeNull(); - expect(data.linkCount).toBe(2); - expect(data.links.map(({ countsByTimeframe }) => countsByTimeframe)).toEqual([{}, {}]); +test('rejects unknown literal labels before reading visits or activity', async () => { + const event = request({ selectedTag: 'work/100%é' }); + await expect(load(event)).rejects.toMatchObject({ status: 404 }); + expect(readLastActivity).not.toHaveBeenCalled(); + expect(event.locals.application.linkVisitCount).not.toHaveBeenCalled(); }); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 51c9a58..6f622ed 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -7,7 +7,13 @@ import type { Database } from './types.js'; export { runMigrations } from './migrate.js'; export { insertVisit, purgeVisits } from './visits.js'; -export { addVisitTotals, readVisitTotals, readLinkVisitCounts } from './visit-totals.js'; +export { + addVisitTotals, + readVisitTotals, + readOverviewVisitTotals, + readDomainVisitTotals, + readLinkVisitCounts +} from './visit-totals.js'; export { captureVisitBoundary, processVisitBatch, diff --git a/packages/db/src/visit-reports/index.ts b/packages/db/src/visit-reports/index.ts index c0dd4fe..618d662 100644 --- a/packages/db/src/visit-reports/index.ts +++ b/packages/db/src/visit-reports/index.ts @@ -3,15 +3,8 @@ export { subtractDailyVisitStatistics, deleteExpiredDailyStatistics, clearDailyVisitStatistics, - readOverviewVisitDetails, - readDomainVisitDetails, readLinkVisitDetails, readVisitDetails, readLastVisitActivity } from './storage.js'; -export type { - DailyStatisticsMismatch, - OverviewVisitDetails, - DomainVisitDetails, - LinkVisitDetails -} from './storage.js'; +export type { DailyStatisticsMismatch, LinkVisitDetails } from './storage.js'; diff --git a/packages/db/src/visit-reports/storage.test.ts b/packages/db/src/visit-reports/storage.test.ts index 3fe3814..5f30dd9 100644 --- a/packages/db/src/visit-reports/storage.test.ts +++ b/packages/db/src/visit-reports/storage.test.ts @@ -16,8 +16,6 @@ import { clearDailyVisitStatistics, deleteExpiredDailyStatistics, readVisitDetails, - readOverviewVisitDetails, - readDomainVisitDetails, readLinkVisitDetails, readLastVisitActivity } from './storage.js'; @@ -242,58 +240,17 @@ test('daily writes and raw processing share caller rollback, with no independent expect(await db.selectFrom('visits').select('processed').execute()).toEqual([{ processed: 0 }]); }); -test('overview selects only current domains in one SQL read and derives zeros for new scopes', async () => { - const overview = daily(overviewScope, 8, 2); - const current = daily(domainScope, 3, 1); - await add( - overview, - current, - daily(rootScope), - daily({ kind: 'domain', domain: 'removed.example.test' }) - ); - await db - .updateTable('visit_daily_statistics') - .set({ browsers_json: '["private malformed cache"]' }) - .where(({ or, eb }) => - or([eb('scope_kind', '=', 'link'), eb('domain', '=', 'removed.example.test')]) - ) - .execute(); - const before = await db.selectFrom('visit_daily_statistics').selectAll().execute(); - const statements = vi.spyOn(DatabaseSync.prototype, 'prepare'); - try { - expect( - await readOverviewVisitDetails(db, [domain, domain, 'new.example.test'], period) - ).toEqual({ - overview: projectVisitDetails(overviewScope, period, [overview]), - domains: [ - { domain, details: projectVisitDetails(domainScope, period, [current]) }, - { - domain: 'new.example.test', - details: projectVisitDetails({ kind: 'domain', domain: 'new.example.test' }, period, []) - } - ] - }); - expect(statements).toHaveBeenCalledTimes(1); - const query = statements.mock.calls[0]![0]; - expect(query).toContain('domain IN'); - expect(query).not.toMatch(/\bvisits\b|\bjoin\b|\bsum\s*\(/i); - } finally { - statements.mockRestore(); - } - expect(await db.selectFrom('visit_daily_statistics').selectAll().execute()).toEqual(before); -}); - -test('domain and selected-link readers bind exact path/domain pairs, include Root, and ignore distractors', async () => { +test('selected-link readers bind exact path/domain pairs and ignore distractors', async () => { const path = "/' OR 1=1 --"; const link = { kind: 'link', domain, path } as const; const other = { kind: 'link', domain: 'other.example.test', path: '/faq' } as const; await add( daily(domainScope, 6, 2), daily(rootScope, 1), - daily(link, 5), - daily(other, 7), - daily({ kind: 'link', domain, path: '/faq' }, 99), - daily({ kind: 'link', domain: 'other.example.test', path }, 99) + daily(link, 5, 0, 11), + daily(other, 7, 0, 12), + daily({ kind: 'link', domain, path: '/faq' }, 99, 0, 13), + daily({ kind: 'link', domain: 'other.example.test', path }, 99, 0, 14) ); await db .updateTable('visit_daily_statistics') @@ -302,10 +259,6 @@ test('domain and selected-link readers bind exact path/domain pairs, include Roo .where('domain', '=', domain) .where('path', '=', '/faq') .execute(); - const domainDetails = await readDomainVisitDetails(db, domain, [path, path, '/new'], period); - expect(domainDetails.links.map(({ path }) => path)).toEqual(['/', path, '/new']); - expect(domainDetails.links[0]!.details.daily[0]!.validVisits).toBe(1); - expect(domainDetails.links[2]!.details.lastActivityAt).toBeNull(); const selected = await readLinkVisitDetails(db, [link, other, link], period); expect( selected.links.map(({ domain, path, details }) => ({ @@ -318,12 +271,17 @@ test('domain and selected-link readers bind exact path/domain pairs, include Roo { domain: other.domain, path: other.path, visits: 7 } ]); expect(await readLinkVisitDetails(db, [], period)).toEqual({ period, links: [] }); + expect(await readLastVisitActivity(db, period, [link, other])).toBe('2026-04-01T12:00:00.000Z'); + expect(await readLastVisitActivity(db, period, [])).toBeNull(); }); test('successful empty reads give zeros/activity null; view time advances without writes and zero clears derived rows', async () => { - const empty = await readOverviewVisitDetails(db, [domain], period); - expect(empty.overview).toEqual(projectVisitDetails(overviewScope, period, [])); - expect(empty.domains[0]!.details).toEqual(projectVisitDetails(domainScope, period, [])); + expect(await readVisitDetails(db, overviewScope, period)).toEqual( + projectVisitDetails(overviewScope, period, []) + ); + expect(await readVisitDetails(db, domainScope, period)).toEqual( + projectVisitDetails(domainScope, period, []) + ); expect(await readLastVisitActivity(db, period)).toBeNull(); await add(daily(overviewScope), daily(domainScope, 1, 0, 11)); const before = await db.selectFrom('visit_daily_statistics').selectAll().execute(); @@ -332,6 +290,7 @@ test('successful empty reads give zeros/activity null; view time advances withou expect(await readLastVisitActivity(db, nextPeriod)).toBeNull(); expect(await db.selectFrom('visit_daily_statistics').selectAll().execute()).toEqual(before); expect(await readLastVisitActivity(db, period)).toBe('2026-04-01T10:00:00.000Z'); + expect(await readLastVisitActivity(db, period, domainScope)).toBe('2026-04-01T11:00:00.000Z'); await clearDailyVisitStatistics(db); expect((await readVisitDetails(db, overviewScope, period)).lastActivityAt).toBeNull(); }); diff --git a/packages/db/src/visit-reports/storage.ts b/packages/db/src/visit-reports/storage.ts index 3158d2f..822031c 100644 --- a/packages/db/src/visit-reports/storage.ts +++ b/packages/db/src/visit-reports/storage.ts @@ -84,51 +84,6 @@ export async function clearDailyVisitStatistics(db: Kysely): Promise; -} - -export async function readOverviewVisitDetails( - db: Kysely, - currentDomains: string[], - period: ReportPeriod -): Promise { - const domains = [...new Set(currentDomains)]; - const [overview, ...details] = await readCurrentDetails( - db, - [{ kind: 'overview' }, ...domains.map((domain) => ({ kind: 'domain' as const, domain }))], - period - ); - return { - overview: overview!, - domains: domains.map((domain, index) => ({ domain, details: details[index]! })) - }; -} - -export interface DomainVisitDetails { - domain: VisitDetails; - links: Array<{ path: string; details: VisitDetails }>; -} - -export async function readDomainVisitDetails( - db: Kysely, - domain: string, - currentPaths: string[], - period: ReportPeriod -): Promise { - const paths = [...new Set(['/', ...currentPaths])]; - const [details, ...links] = await readCurrentDetails( - db, - [{ kind: 'domain', domain }, ...paths.map((path) => ({ kind: 'link' as const, domain, path }))], - period - ); - return { - domain: details!, - links: paths.map((path, index) => ({ path, details: links[index]! })) - }; -} - export interface LinkVisitDetails { period: ReportPeriod; links: Array<{ domain: string; path: string; details: VisitDetails }>; @@ -162,13 +117,15 @@ export async function readVisitDetails( export async function readLastVisitActivity( db: Kysely, - period: ReportPeriod + period: ReportPeriod, + scopeOrScopes: ReportScope | ReportScope[] = { kind: 'overview' } ): Promise { + const scopes = Array.isArray(scopeOrScopes) ? scopeOrScopes : [scopeOrScopes]; + for (const selected of scopes) checkReportScope(selected); const days = reportDays(period); - const row = await db - .selectFrom('visit_daily_statistics') + if (scopes.length === 0) return null; + const row = await selectedDays(db, scopes) .select(({ fn }) => fn.max('last_visit_at').as('lastVisitAt')) - .where('scope_kind', '=', 'overview') .where('day', '>=', days.first) .where('day', '<=', days.last) .executeTakeFirstOrThrow(); diff --git a/packages/db/src/visit-totals.test.ts b/packages/db/src/visit-totals.test.ts index f233255..0619944 100644 --- a/packages/db/src/visit-totals.test.ts +++ b/packages/db/src/visit-totals.test.ts @@ -3,6 +3,8 @@ import { afterEach, beforeEach, expect, test } from 'vitest'; import { addVisitTotals, openDb, + readDomainVisitTotals, + readOverviewVisitTotals, readVisitTotals, readLinkVisitCounts, runMigrations, @@ -42,6 +44,50 @@ test('adds numeric totals per scope inside a caller transaction and reads missin }); }); +test('reads the lifetime overview and only requested domain rows, filling absent domains with zero', async () => { + const formerDomain = { kind: 'domain' as const, domain: 'old.example.test' }; + await db.transaction().execute((transaction) => + addVisitTotals(transaction, [ + { scope: overview, totals: { validVisits: 6, invalidVisits: 2 } }, + { scope: domain, totals: { validVisits: 4, invalidVisits: 1 } }, + { scope: formerDomain, totals: { validVisits: 2, invalidVisits: 1 } }, + { scope: link, totals: { validVisits: 1, invalidVisits: 0 } } + ]) + ); + + expect(await readOverviewVisitTotals(db, [domain.domain, 'empty.example.test'])).toEqual({ + overview: { validVisits: 6, invalidVisits: 2 }, + byDomain: new Map([ + [domain.domain, { validVisits: 4, invalidVisits: 1 }], + ['empty.example.test', { validVisits: 0, invalidVisits: 0 }] + ]) + }); +}); + +test('reads stored domain, Root, and current path totals without including other domains or paths', async () => { + await db.transaction().execute((transaction) => + addVisitTotals(transaction, [ + { scope: domain, totals: { validVisits: 9, invalidVisits: 2 } }, + { scope: { ...link, path: '/' }, totals: { validVisits: 2, invalidVisits: 0 } }, + { scope: link, totals: { validVisits: 3, invalidVisits: 0 } }, + { scope: { ...link, path: '/retired' }, totals: { validVisits: 4, invalidVisits: 0 } }, + { + scope: { ...link, domain: 'other.example.test' }, + totals: { validVisits: 5, invalidVisits: 0 } + } + ]) + ); + + expect(await readDomainVisitTotals(db, domain.domain, ['/docs', '/new'])).toEqual({ + domain: { validVisits: 9, invalidVisits: 2 }, + byPath: new Map([ + ['/', { validVisits: 2, invalidVisits: 0 }], + ['/docs', { validVisits: 3, invalidVisits: 0 }], + ['/new', { validVisits: 0, invalidVisits: 0 }] + ]) + }); +}); + test('unsafe accumulated totals roll back the whole addition transaction', async () => { await db .transaction() diff --git a/packages/db/src/visit-totals.ts b/packages/db/src/visit-totals.ts index d036598..8814b65 100644 --- a/packages/db/src/visit-totals.ts +++ b/packages/db/src/visit-totals.ts @@ -1,4 +1,9 @@ -import { checkReportScope, type ReportScope, type VisitTotals } from '@goto/analytics'; +import { + checkReportScope, + zeroVisitTotals, + type ReportScope, + type VisitTotals +} from '@goto/analytics'; import { sql, type Kysely } from 'kysely'; import type { Database } from './types.js'; @@ -42,6 +47,68 @@ export async function readVisitTotals( return checkTotals({ validVisits: row.valid_visits, invalidVisits: row.invalid_visits }); } +export async function readOverviewVisitTotals( + db: Kysely, + domains: readonly string[] +): Promise<{ overview: VisitTotals; byDomain: Map }> { + for (const domain of domains) checkReportScope({ kind: 'domain', domain }); + const rows = await db + .selectFrom('visit_totals') + .select(['scope_kind', 'domain', 'valid_visits', 'invalid_visits']) + .where( + sql`scope_kind = 'overview' OR ( + scope_kind = 'domain' AND domain IN (SELECT value FROM json_each(${JSON.stringify(domains)})) + )` + ) + .execute(); + + let overview = zeroVisitTotals(); + const byDomain = new Map(domains.map((domain) => [domain, zeroVisitTotals()])); + for (const row of rows) { + const totals = checkTotals({ + validVisits: row.valid_visits, + invalidVisits: row.invalid_visits + }); + if (row.scope_kind === 'overview') overview = totals; + else if (row.domain !== null) byDomain.set(row.domain, totals); + } + return { overview, byDomain }; +} + +export async function readDomainVisitTotals( + db: Kysely, + domain: string, + currentPaths: readonly string[] +): Promise<{ domain: VisitTotals; byPath: Map }> { + checkReportScope({ kind: 'domain', domain }); + const paths = ['/', ...currentPaths]; + for (const path of paths) checkReportScope({ kind: 'link', domain, path }); + const rows = await db + .selectFrom('visit_totals') + .select(['scope_kind', 'path', 'valid_visits', 'invalid_visits']) + .where('domain', '=', domain) + .where( + sql`( + scope_kind = 'domain' OR ( + scope_kind = 'link' AND path IN (SELECT value FROM json_each(${JSON.stringify(paths)})) + ) + )` + ) + .execute(); + + let domainTotals = zeroVisitTotals(); + const byPath = new Map(paths.map((path) => [path, zeroVisitTotals()])); + for (const row of rows) { + const totals = checkTotals({ + validVisits: row.valid_visits, + invalidVisits: row.invalid_visits + }); + if (row.scope_kind === 'domain') domainTotals = totals; + else if (row.path !== null) byPath.set(row.path, totals); + } + return { domain: domainTotals, byPath }; +} + export async function readLinkVisitCounts( db: Kysely, links: readonly { domain: string; path: string }[]