Report root visits separately in admin #50
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@goto/web': patch
|
||||
---
|
||||
|
||||
Report root visits separately from valid links and invalid clicks in admin summaries and Analytics, including historical traffic. Show root traffic over time in the Root report.
|
||||
+43
-27
@@ -45,10 +45,16 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
await expect(summary.locator('.admin-stat-label')).toHaveText([
|
||||
'Domains',
|
||||
'Links',
|
||||
'Total Visits'
|
||||
'Total Visits',
|
||||
'Invalid clicks',
|
||||
'Root visits'
|
||||
]);
|
||||
const totalVisits = summary.getByRole('region', { name: 'Total Visits', exact: true });
|
||||
await expect(totalVisits.getByText('5', { exact: true })).toBeVisible();
|
||||
const invalidClicks = page.getByRole('region', { name: 'Invalid clicks', exact: true });
|
||||
const rootVisits = page.getByRole('region', { name: 'Root visits', exact: true });
|
||||
await expect(totalVisits.getByText('4', { exact: true })).toBeVisible();
|
||||
await expect(invalidClicks.locator('.admin-stat-value')).toHaveText('1');
|
||||
await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1');
|
||||
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(
|
||||
@@ -60,10 +66,10 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
await expect(timeframe).toHaveCount(0);
|
||||
const domainLink = page.getByRole('link', { name: 'go.example.org', exact: true });
|
||||
const domainRow = page.getByRole('listitem').filter({ has: domainLink });
|
||||
await expect(domainRow.locator('.admin-inventory-number')).toHaveText(['6', '3']);
|
||||
await expect(domainRow.locator('.admin-inventory-number')).toHaveText(['6', '2']);
|
||||
const overviewResponse = await page.goto(`${appServer.origin}/admin?period=7d`);
|
||||
expect(overviewResponse?.headers()['cache-control']).toBe('private, no-store');
|
||||
await expect(totalVisits.getByText('5', { exact: true })).toBeVisible();
|
||||
await expect(totalVisits.getByText('4', { 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();
|
||||
@@ -86,12 +92,12 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
await expect(summary.locator('.admin-stat-label')).toHaveText([
|
||||
'Links',
|
||||
'Total Visits',
|
||||
'Invalid clicks'
|
||||
'Invalid clicks',
|
||||
'Root visits'
|
||||
]);
|
||||
await expect(totalVisits.getByText('3', { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole('region', { name: 'Invalid clicks', exact: true }).locator('.admin-stat-value')
|
||||
).toHaveText('1');
|
||||
await expect(totalVisits.getByText('2', { exact: true })).toBeVisible();
|
||||
await expect(invalidClicks.locator('.admin-stat-value')).toHaveText('1');
|
||||
await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1');
|
||||
const linksInventory = page.getByRole('region', { name: 'Links on go.example.org', exact: true });
|
||||
const domainDetails = page.getByRole('region', { name: 'Details', exact: true });
|
||||
const rootRow = linksInventory.getByRole('listitem').filter({
|
||||
@@ -100,7 +106,7 @@ 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', 'Total Visits'];
|
||||
const columns = ['Path', 'Destination', 'State', 'Visits'];
|
||||
await expect(linksInventory.locator('.admin-inventory-heading > span')).toHaveText(columns);
|
||||
const percentLinkRow = linksInventory
|
||||
.getByRole('listitem')
|
||||
@@ -120,6 +126,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
'404 Not found',
|
||||
domainReportPath
|
||||
]);
|
||||
await expect(rootRow.getByText('Root visits', { exact: true })).toBeVisible();
|
||||
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);
|
||||
@@ -314,7 +321,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
]);
|
||||
await expect(timeframe).toHaveCount(0);
|
||||
await expect(trend).toHaveCount(0);
|
||||
await expect(summaryVisitCount).toHaveText('1');
|
||||
await expect(rootVisits.locator('.admin-stat-value')).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([
|
||||
@@ -323,19 +330,20 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
'Destination',
|
||||
'Analytics'
|
||||
]);
|
||||
const rootReportPath = `${domainReportPath}&path=%2F`;
|
||||
await expect(rootDetails.locator('dd')).toHaveText([
|
||||
'go.example.org',
|
||||
'go.example.org/',
|
||||
'Uses fallback',
|
||||
domainReportPath
|
||||
rootReportPath
|
||||
]);
|
||||
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);
|
||||
const rootAnalyticsLink = rootDetails.getByRole('link', { name: rootReportPath, exact: true });
|
||||
await expect(rootAnalyticsLink).toHaveAttribute('href', rootReportPath);
|
||||
await rootDetails.getByRole('link', { name: 'go.example.org', exact: true }).click();
|
||||
await expect(totalVisits.getByText('3', { exact: true })).toBeVisible();
|
||||
await expect(totalVisits.getByText('2', { exact: true })).toBeVisible();
|
||||
|
||||
await page
|
||||
.getByRole('navigation', { name: 'Administration', exact: true })
|
||||
@@ -367,8 +375,10 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
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();
|
||||
await expect(analyticsVisits).toContainText('2');
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
|
||||
await expect(invalidClicks.locator('.admin-stat-value')).toHaveText('1');
|
||||
await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1');
|
||||
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 });
|
||||
@@ -383,7 +393,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
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();
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
|
||||
|
||||
const isHeldRedirectRequest = (url: URL) =>
|
||||
url.pathname === '/admin/analytics/__data.json' &&
|
||||
@@ -414,8 +424,8 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
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();
|
||||
await expect(analyticsVisits).toContainText('1');
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
|
||||
} finally {
|
||||
releaseRedirectReport.resolve();
|
||||
}
|
||||
@@ -423,7 +433,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
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();
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
|
||||
|
||||
const searchRequests: string[] = [];
|
||||
function recordSearchRequest(request: Request) {
|
||||
@@ -440,7 +450,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
'tiny.example.org/docs'
|
||||
]);
|
||||
await expect(page).toHaveURL(`${analyticsUrl}?period=7d`);
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
|
||||
expect(searchRequests).toEqual([]);
|
||||
} finally {
|
||||
page.off('request', recordSearchRequest);
|
||||
@@ -450,7 +460,10 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
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();
|
||||
const rootChart = page.getByRole('region', { name: 'Root visits over time', exact: true });
|
||||
await expect(rootChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
|
||||
await expect(rootVisits.locator('.admin-stat-value')).toHaveText('1');
|
||||
await expect(invalidClicks).toHaveCount(0);
|
||||
await page.goBack();
|
||||
await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/docs');
|
||||
await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
|
||||
@@ -508,7 +521,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
|
||||
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 expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
|
||||
|
||||
await chooseReportScope('go.example.org/docs');
|
||||
await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`);
|
||||
@@ -580,7 +593,9 @@ test.describe('analytics disabled', () => {
|
||||
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
|
||||
'Domains',
|
||||
'Links',
|
||||
'Total Visits'
|
||||
'Total Visits',
|
||||
'Invalid clicks',
|
||||
'Root visits'
|
||||
]);
|
||||
await expect(
|
||||
page
|
||||
@@ -607,7 +622,8 @@ test.describe('analytics disabled', () => {
|
||||
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
|
||||
'Links',
|
||||
'Total Visits',
|
||||
'Invalid clicks'
|
||||
'Invalid clicks',
|
||||
'Root visits'
|
||||
]);
|
||||
await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount(
|
||||
@@ -620,7 +636,7 @@ test.describe('analytics disabled', () => {
|
||||
page
|
||||
.getByRole('region', { name: 'Links on go.example.org', exact: true })
|
||||
.locator('.admin-inventory-heading > span')
|
||||
).toHaveText(['Path', 'Destination', 'State', 'Total Visits']);
|
||||
).toHaveText(['Path', 'Destination', 'State', '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']);
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
</div>
|
||||
<ul class="admin-inventory-list">
|
||||
{#each links as link (link.href)}
|
||||
{@const pathLabel = link.path === '/' ? '(root)' : link.path}
|
||||
{@const isRoot = link.path === '/'}
|
||||
{@const pathLabel = isRoot ? '(root)' : link.path}
|
||||
{@const linkLabel = showDomain ? `${link.domain}${link.path}` : pathLabel}
|
||||
<li>
|
||||
<a class="admin-inventory-row admin-inventory-link" href={link.href} aria-label={linkLabel}>
|
||||
@@ -60,7 +61,11 @@
|
||||
</span>
|
||||
{#if visitLabel}
|
||||
<span class="admin-inventory-count">
|
||||
<span class="admin-inventory-label">{visitLabel}</span>
|
||||
{#if isRoot}
|
||||
<span class="root-visit-label">Root visits</span>
|
||||
{:else}
|
||||
<span class="admin-inventory-label">{visitLabel}</span>
|
||||
{/if}
|
||||
<span class="admin-inventory-number">{formatCount(link.visits)}</span>
|
||||
</span>
|
||||
{/if}
|
||||
@@ -69,3 +74,9 @@
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.root-visit-label {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
</style>
|
||||
@@ -8,11 +8,13 @@
|
||||
let {
|
||||
daily,
|
||||
window: viewWindow,
|
||||
granularity
|
||||
granularity,
|
||||
visitLabel = 'Visits'
|
||||
}: {
|
||||
daily: VisitDetails['daily'];
|
||||
window: VisitWindow;
|
||||
granularity: VisitGranularity;
|
||||
visitLabel?: string;
|
||||
} = $props();
|
||||
let ready = $state(false);
|
||||
let unavailable = $state(false);
|
||||
@@ -39,7 +41,7 @@
|
||||
let buckets = $derived(groupVisitDays(daily, viewWindow, granularity));
|
||||
let total = $derived(buckets.reduce((sum, bucket) => sum + bucket.validVisits, 0));
|
||||
let summary = $derived(
|
||||
`Visits by ${granularity}. Total: ${formatCount(total)}. ${windowLabel(viewWindow)}.`
|
||||
`${visitLabel} by ${granularity}. Total: ${formatCount(total)}. ${windowLabel(viewWindow)}.`
|
||||
);
|
||||
|
||||
function windowLabel(window: VisitWindow): string {
|
||||
@@ -100,7 +102,7 @@
|
||||
const bucket = points[items[0]?.dataIndex ?? -1];
|
||||
return bucket ? `${bucketPeriod(bucket)} UTC` : '';
|
||||
},
|
||||
label: (item) => `Visits: ${formatCount(item.parsed.y)}`,
|
||||
label: (item) => `${visitLabel}: ${formatCount(item.parsed.y)}`,
|
||||
footer: (items) => (points[items[0]?.dataIndex ?? -1]?.partial ? 'Partial period' : '')
|
||||
}
|
||||
}
|
||||
@@ -114,7 +116,7 @@
|
||||
chart.data.labels = points.map((point) => bucketLabel(point.start, grouping));
|
||||
chart.data.datasets = [
|
||||
{
|
||||
label: 'Visits',
|
||||
label: visitLabel,
|
||||
data: points.map((point) => point.validVisits),
|
||||
borderColor: color,
|
||||
borderWidth: 2,
|
||||
@@ -192,9 +194,9 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="visits-chart" aria-label="Visits over time">
|
||||
<section class="visits-chart" aria-label={`${visitLabel} over time`}>
|
||||
<header>
|
||||
<h2>Visits</h2>
|
||||
<h2>{visitLabel}</h2>
|
||||
<span class="grouping">{groupingLabels[granularity]}</span>
|
||||
</header>
|
||||
<span class="chart-palette" bind:this={palette} hidden aria-hidden="true"></span>
|
||||
@@ -207,9 +209,9 @@
|
||||
{/if}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex (Keyboard scrolling needs a focusable region.) -->
|
||||
<div class="table-scroll" role="region" aria-label="Visit data" tabindex="0">
|
||||
<table aria-label="Visits">
|
||||
<table aria-label={visitLabel}>
|
||||
<thead>
|
||||
<tr><th scope="col">Period (UTC)</th><th scope="col">Visits</th></tr>
|
||||
<tr><th scope="col">Period (UTC)</th><th scope="col">{visitLabel}</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each buckets as bucket (bucket.start)}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type VisitDetails
|
||||
} from '@goto/analytics';
|
||||
import type { GotoConfiguration } from '@goto/config';
|
||||
import { openDb, runMigrations } from '@goto/db';
|
||||
import { addVisitTotals, openDb, runMigrations } from '@goto/db';
|
||||
import { addDailyVisitStatistics } from '@goto/db/visit-reports';
|
||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
|
||||
import { readLinkDetails, readVisitDetails, readLastActivity } from './reports.js';
|
||||
@@ -61,6 +61,9 @@ test('reads daily output and derives zero scopes in a window from current time a
|
||||
const linkScope = { kind: 'link', domain, path: '/docs' } as const;
|
||||
const linkDetails: VisitDetails = { ...details, scope: linkScope };
|
||||
const otherLink = { kind: 'link', domain: 'other.example.test', path: '/docs' } as const;
|
||||
const formerDomain = { kind: 'domain', domain: 'old.example.test' } as const;
|
||||
const formerRoot = { kind: 'link', domain: formerDomain.domain, path: '/' } as const;
|
||||
const rootCounts = { validVisits: 1, invalidVisits: 0 };
|
||||
const otherLinkActivityAt = '2026-06-15T11:00:00.000Z';
|
||||
const emptyDetails: VisitDetails = {
|
||||
...details,
|
||||
@@ -82,22 +85,35 @@ test('reads daily output and derives zero scopes in a window from current time a
|
||||
available: true,
|
||||
lastActivityAt: null
|
||||
});
|
||||
await db
|
||||
.transaction()
|
||||
.execute((transaction) =>
|
||||
addDailyVisitStatistics(transaction, [
|
||||
daily,
|
||||
{ ...daily, scope: domainScope },
|
||||
{ ...daily, scope: linkScope },
|
||||
{ ...daily, scope: otherLink, lastVisitAt: Date.parse(otherLinkActivityAt) }
|
||||
])
|
||||
);
|
||||
await db.transaction().execute(async (transaction) => {
|
||||
await addVisitTotals(transaction, [{ scope: formerDomain, totals: rootCounts }]);
|
||||
await addDailyVisitStatistics(transaction, [
|
||||
daily,
|
||||
{ ...daily, scope: domainScope },
|
||||
{ ...daily, scope: linkScope },
|
||||
{ ...daily, scope: otherLink, lastVisitAt: Date.parse(otherLinkActivityAt) },
|
||||
{
|
||||
...daily,
|
||||
scope: formerRoot,
|
||||
...rootCounts,
|
||||
browsers: [{ name: 'Other', ...rootCounts }],
|
||||
operatingSystems: [{ name: 'Other', ...rootCounts }],
|
||||
acceptedLanguages: [{ name: 'Other', ...rootCounts }]
|
||||
}
|
||||
]);
|
||||
});
|
||||
} finally {
|
||||
await db.destroy();
|
||||
}
|
||||
const close = vi.spyOn(DatabaseSync.prototype, 'close');
|
||||
try {
|
||||
expect(await readVisitDetails(configuration, details.scope)).toEqual(details);
|
||||
const overview = await readVisitDetails(configuration, details.scope);
|
||||
expect(overview?.daily.at(-1)).toMatchObject({
|
||||
validVisits: 1,
|
||||
invalidVisits: 1,
|
||||
rootVisits: 1
|
||||
});
|
||||
expect(overview?.lastActivityAt).toBe(lastActivityAt);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(await readVisitDetails(configuration, domainScope)).toEqual(domainDetails);
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { createVisitPeriod, type ReportScope, type VisitDetails } from '@goto/analytics';
|
||||
import { createVisitPeriod, type ReportScope } from '@goto/analytics';
|
||||
import type { GotoConfiguration } from '@goto/config';
|
||||
import { openDb } from '@goto/db';
|
||||
import {
|
||||
readLinkVisitDetails,
|
||||
readVisitDetails as readStoredDetails,
|
||||
readAnalyticsVisitDetails,
|
||||
readLastVisitActivity,
|
||||
type AnalyticsVisitDetails,
|
||||
type LinkVisitDetails
|
||||
} from '@goto/db/visit-reports';
|
||||
import type { Immutable } from '../snapshot.js';
|
||||
@@ -33,14 +34,14 @@ export async function readLinkDetails(
|
||||
export async function readVisitDetails(
|
||||
configuration: ReportConfiguration,
|
||||
scope: ReportScope
|
||||
): Promise<VisitDetails | null> {
|
||||
): Promise<AnalyticsVisitDetails | null> {
|
||||
const months = configuration.analytics.retention_months;
|
||||
if (months === 0) return null;
|
||||
let db: Awaited<ReturnType<typeof openDb>> | undefined;
|
||||
try {
|
||||
db = await openDb(configuration.database.path, { readOnly: true });
|
||||
const period = createVisitPeriod(months, Date.now());
|
||||
return await readStoredDetails(db, scope, period);
|
||||
return await readAnalyticsVisitDetails(db, scope, period);
|
||||
} catch {
|
||||
warnUnavailable();
|
||||
return null;
|
||||
|
||||
@@ -23,6 +23,8 @@ export const load = (async ({ locals }) => {
|
||||
domainCount: domains.length,
|
||||
linkCount: domains.reduce((sum, row) => sum + row.linkCount, 0),
|
||||
totalVisits: totals?.overview.validVisits ?? null,
|
||||
invalidClicks: totals?.overview.invalidVisits ?? null,
|
||||
rootVisits: totals?.overview.rootVisits ?? null,
|
||||
domains
|
||||
};
|
||||
}) satisfies PageServerLoad;
|
||||
@@ -17,10 +17,12 @@
|
||||
{#if data.totalVisits === null}
|
||||
<p class="admin-notice" role="status">Visit totals unavailable.</p>
|
||||
{/if}
|
||||
<div class="admin-cards">
|
||||
<div class="admin-cards overview-cards">
|
||||
<StatCard label="Domains" value={data.domainCount} />
|
||||
<StatCard label="Links" value={data.linkCount} />
|
||||
<StatCard label="Total Visits" value={data.totalVisits} />
|
||||
<StatCard label="Invalid clicks" value={data.invalidClicks} />
|
||||
<StatCard label="Root visits" value={data.rootVisits} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -64,6 +66,12 @@
|
||||
</AdminPage>
|
||||
|
||||
<style>
|
||||
@media (width > 960px) {
|
||||
.overview-cards {
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.summary-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { countBreakdownVisitsByTimeframe } from '@goto/analytics';
|
||||
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
|
||||
import {
|
||||
availableVisitTimeframes,
|
||||
countVisitWindows,
|
||||
visitWindow,
|
||||
type VisitWindow
|
||||
} from '@goto/analytics/daily';
|
||||
import { isCanonicalPath, normalizeHost } from '@goto/config';
|
||||
import type { AnalyticsVisitDetails } from '@goto/db/visit-reports';
|
||||
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';
|
||||
@@ -28,6 +34,18 @@ export const load = (async ({ locals, url }) => {
|
||||
timeframe,
|
||||
window: visitWindow(details.period, timeframe)
|
||||
}));
|
||||
const rootVisitsByTimeframe =
|
||||
scope.kind === 'overview' || scope.kind === 'domain'
|
||||
? Object.fromEntries(
|
||||
windows.map(({ timeframe, window }) => [
|
||||
timeframe,
|
||||
details.daily.reduce(
|
||||
(total, day) => total + (dayOverlapsWindow(day, window) ? (day.rootVisits ?? 0) : 0),
|
||||
0
|
||||
)
|
||||
])
|
||||
)
|
||||
: null;
|
||||
return {
|
||||
...selection,
|
||||
report: {
|
||||
@@ -35,6 +53,7 @@ export const load = (async ({ locals, url }) => {
|
||||
daily: details.daily,
|
||||
lastActivityAt: details.lastActivityAt ? Date.parse(details.lastActivityAt) : null,
|
||||
countsByTimeframe: countVisitWindows(details.daily, windows),
|
||||
rootVisitsByTimeframe,
|
||||
browserVisitsByTimeframe: countBreakdownVisitsByTimeframe(details.browsers, windows),
|
||||
operatingSystemVisitsByTimeframe: countBreakdownVisitsByTimeframe(
|
||||
details.operatingSystems,
|
||||
@@ -48,6 +67,10 @@ export const load = (async ({ locals, url }) => {
|
||||
};
|
||||
}) satisfies PageServerLoad;
|
||||
|
||||
function dayOverlapsWindow(day: { start: string; end: string }, window: VisitWindow): boolean {
|
||||
return day.start < window.asOf && day.end > window.from;
|
||||
}
|
||||
|
||||
function selectedScope(query: URLSearchParams): AnalyticsScope {
|
||||
const domains = query.getAll('domain');
|
||||
const paths = query.getAll('path');
|
||||
@@ -99,7 +122,10 @@ function isConfiguredScope(scope: AnalyticsScope, groups: ScopeGroup[]): boolean
|
||||
return groups.some(({ scopes }) => scopes.some((option) => scopeValue(option) === selectedValue));
|
||||
}
|
||||
|
||||
async function readScopeDetails(snapshot: ConfigurationSnapshot, scope: AnalyticsScope) {
|
||||
async function readScopeDetails(
|
||||
snapshot: ConfigurationSnapshot,
|
||||
scope: AnalyticsScope
|
||||
): Promise<AnalyticsVisitDetails | null> {
|
||||
if (scope.kind !== 'tag') return readVisitDetails(snapshot.configuration, scope);
|
||||
|
||||
const members = tagMembers(snapshot.domains, scope.tag);
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
|
||||
);
|
||||
let counts = $derived(report?.countsByTimeframe[timeframe]);
|
||||
let isRootReport = $derived(data.scope.kind === 'link' && data.scope.path === '/');
|
||||
|
||||
let selectionNavigationFailed = $state(false);
|
||||
let pendingReportNavigations = $state(0);
|
||||
@@ -50,7 +51,7 @@
|
||||
/>
|
||||
{/if}
|
||||
{/snippet}
|
||||
<div class="analytics-summary">
|
||||
<div class="analytics-summary" class:has-root-count={report?.rootVisitsByTimeframe != null}>
|
||||
<div
|
||||
class="report-filters"
|
||||
role="group"
|
||||
@@ -65,8 +66,15 @@
|
||||
</div>
|
||||
{#if counts}
|
||||
<div class="admin-cards report-totals">
|
||||
<StatCard label="Visits" value={counts.validVisits} />
|
||||
<StatCard label="Invalid clicks" value={counts.invalidVisits} />
|
||||
{#if isRootReport}
|
||||
<StatCard label="Root visits" value={counts.validVisits} />
|
||||
{:else}
|
||||
<StatCard label="Visits" value={counts.validVisits} />
|
||||
<StatCard label="Invalid clicks" value={counts.invalidVisits} />
|
||||
{#if report?.rootVisitsByTimeframe}
|
||||
<StatCard label="Root visits" value={report.rootVisitsByTimeframe[timeframe] ?? 0} />
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -85,6 +93,7 @@
|
||||
daily={report.daily}
|
||||
window={visitWindow(report.period, timeframe)}
|
||||
granularity={visitGranularity(timeframe, report.period.retentionMonths)}
|
||||
visitLabel={isRootReport ? 'Root visits' : 'Visits'}
|
||||
/>
|
||||
<VisitBreakdowns
|
||||
browserVisits={report.browserVisitsByTimeframe[timeframe] ?? []}
|
||||
@@ -123,6 +132,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
@media (width > 900px) {
|
||||
.analytics-summary.has-root-count {
|
||||
--summary-trio-width: calc(3 * var(--summary-card-width) + 2 * var(--space-5));
|
||||
grid-template-columns: minmax(0, var(--summary-pair-width)) minmax(
|
||||
0,
|
||||
var(--summary-trio-width)
|
||||
);
|
||||
}
|
||||
|
||||
.has-root-count .report-totals {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (width > 640px) {
|
||||
.analytics-summary {
|
||||
grid-template-columns: repeat(2, minmax(0, var(--summary-pair-width)));
|
||||
|
||||
@@ -190,13 +190,11 @@ test('does not fall back to all traffic for a stale tag', async () => {
|
||||
expect(readLinkDetails).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('projects global totals and keeps each breakdown tied to the selected window', async () => {
|
||||
test('keeps link counts, Root counts and breakdowns 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: [
|
||||
@@ -205,14 +203,16 @@ test('projects global totals and keeps each breakdown tied to the selected windo
|
||||
end: '2026-05-02T00:00:00.000Z',
|
||||
partial: false,
|
||||
validVisits: older.validVisits,
|
||||
invalidVisits: older.invalidVisits
|
||||
invalidVisits: older.invalidVisits,
|
||||
rootVisits: 2
|
||||
},
|
||||
{
|
||||
start: '2026-06-01T00:00:00.000Z',
|
||||
end: '2026-06-02T00:00:00.000Z',
|
||||
partial: false,
|
||||
validVisits: recent.validVisits,
|
||||
invalidVisits: recent.invalidVisits
|
||||
invalidVisits: recent.invalidVisits,
|
||||
rootVisits: 1
|
||||
}
|
||||
],
|
||||
browsers: [
|
||||
@@ -231,6 +231,11 @@ test('projects global totals and keeps each breakdown tied to the selected windo
|
||||
|
||||
const { report } = await load(request(3));
|
||||
|
||||
expect(report?.rootVisitsByTimeframe).toEqual({ '7d': 0, '30d': 1, all: 3 });
|
||||
expect(report?.daily.map(({ start }) => start)).toEqual([
|
||||
'2026-05-01T00:00:00.000Z',
|
||||
'2026-06-01T00:00:00.000Z'
|
||||
]);
|
||||
expect(report?.countsByTimeframe).toEqual({
|
||||
'7d': { validVisits: 0, invalidVisits: 0 },
|
||||
'30d': { validVisits: 3, invalidVisits: 1 },
|
||||
|
||||
@@ -46,6 +46,7 @@ export const load = (async ({ locals, params }) => {
|
||||
linkCount: namedLinks.length,
|
||||
totalVisits: totals?.domain.validVisits ?? null,
|
||||
invalidClicks: totals?.domain.invalidVisits ?? null,
|
||||
rootVisits: totals?.domain.rootVisits ?? null,
|
||||
root: prepared.root,
|
||||
fallback: prepared.fallback,
|
||||
links
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
<StatCard label="Links" value={data.linkCount} />
|
||||
<StatCard label="Total Visits" value={data.totalVisits} />
|
||||
<StatCard label="Invalid clicks" value={data.invalidClicks} />
|
||||
<StatCard label="Root visits" value={data.rootVisits} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -52,7 +53,7 @@
|
||||
</section>
|
||||
<section>
|
||||
<h2>Links</h2>
|
||||
<LinkInventory label={`Links on ${data.domain}`} links={data.links} visitLabel="Total Visits" />
|
||||
<LinkInventory label={`Links on ${data.domain}`} links={data.links} visitLabel="Visits" />
|
||||
</section>
|
||||
</AdminPage>
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ export const load = (async ({ locals, params }) => {
|
||||
|
||||
return {
|
||||
domain,
|
||||
totalVisits: totals?.validVisits ?? null,
|
||||
rootVisits: totals?.validVisits ?? null,
|
||||
domainHref: `/admin/domains/${encodeURIComponent(domain)}`,
|
||||
response,
|
||||
fallback,
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
<section aria-labelledby="summary-heading">
|
||||
<h2 id="summary-heading">Summary</h2>
|
||||
<div class="summary-content">
|
||||
{#if data.totalVisits === null}
|
||||
{#if data.rootVisits === null}
|
||||
<p class="admin-notice" role="status">Visit totals unavailable.</p>
|
||||
{/if}
|
||||
<div class="admin-cards">
|
||||
<StatCard label="Total Visits" value={data.totalVisits} />
|
||||
<StatCard label="Root visits" value={data.rootVisits} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -48,7 +48,7 @@
|
||||
<dd>{data.response.forward_query ? 'Yes' : 'No'}</dd>
|
||||
{/if}
|
||||
{#if data.analyticsEnabled}
|
||||
<AnalyticsField scope={{ kind: 'domain', domain: data.domain }} />
|
||||
<AnalyticsField scope={{ kind: 'link', domain: data.domain, path: '/' }} />
|
||||
{/if}
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
@@ -62,7 +62,7 @@ test('reads lifetime Root totals and scoped activity even when Root uses fallbac
|
||||
|
||||
expect(await load(request())).toEqual({
|
||||
domain,
|
||||
totalVisits: 40,
|
||||
rootVisits: 40,
|
||||
domainHref: '/admin/domains/go.example.test',
|
||||
response: null,
|
||||
fallback,
|
||||
@@ -84,7 +84,7 @@ test('keeps configured Root settings and activity when lifetime totals are unava
|
||||
vi.mocked(readLastActivity).mockResolvedValue({ available: true, lastActivityAt });
|
||||
|
||||
expect(await load(request({ root }))).toMatchObject({
|
||||
totalVisits: null,
|
||||
rootVisits: null,
|
||||
lastActivityAt: Date.parse(lastActivityAt),
|
||||
response: root,
|
||||
fallback,
|
||||
@@ -97,7 +97,7 @@ test.each(['global', 'builtin'] as const)(
|
||||
async (fallbackSource) => {
|
||||
vi.mocked(readLifetimeVisitTotals).mockResolvedValue({ validVisits: 40, invalidVisits: 0 });
|
||||
expect(await load(request({ retentionMonths: 0, fallbackSource }))).toMatchObject({
|
||||
totalVisits: 40,
|
||||
rootVisits: 40,
|
||||
analyticsEnabled: false,
|
||||
lastActivityAt: null,
|
||||
response: null,
|
||||
|
||||
@@ -56,7 +56,7 @@ function request({
|
||||
|
||||
test('shows stored domain and link totals at zero retention but uses live counts for link limits', async () => {
|
||||
vi.mocked(readDomainLifetimeVisitTotals).mockResolvedValueOnce({
|
||||
domain: { validVisits: 15, invalidVisits: 4 },
|
||||
domain: { validVisits: 15, invalidVisits: 4, rootVisits: 3 },
|
||||
byPath: new Map([
|
||||
['/', { validVisits: 3, invalidVisits: 0 }],
|
||||
['/docs', { validVisits: 1, invalidVisits: 0 }],
|
||||
@@ -78,6 +78,7 @@ test('shows stored domain and link totals at zero retention but uses live counts
|
||||
linkCount: 2,
|
||||
totalVisits: 15,
|
||||
invalidClicks: 4,
|
||||
rootVisits: 3,
|
||||
root,
|
||||
fallback
|
||||
});
|
||||
@@ -129,7 +130,8 @@ test('keeps fallback, inventory and scoped activity available when totals cannot
|
||||
root: null,
|
||||
fallback,
|
||||
totalVisits: null,
|
||||
invalidClicks: null
|
||||
invalidClicks: null,
|
||||
rootVisits: null
|
||||
});
|
||||
expect(data.links[0]).toMatchObject({ path: '/', url: fallback.url, visits: null });
|
||||
});
|
||||
@@ -36,7 +36,7 @@ function request(retentionMonths: 0 | 3) {
|
||||
|
||||
test('shows all-time totals and current inventory even when detailed analytics is disabled', async () => {
|
||||
vi.mocked(readOverviewLifetimeVisitTotals).mockResolvedValueOnce({
|
||||
overview: { validVisits: 40, invalidVisits: 7 },
|
||||
overview: { validVisits: 40, invalidVisits: 7, rootVisits: 9 },
|
||||
byDomain: new Map([
|
||||
[domain, { validVisits: 12, invalidVisits: 2 }],
|
||||
[emptyDomain, { validVisits: 0, invalidVisits: 0 }]
|
||||
@@ -56,6 +56,8 @@ test('shows all-time totals and current inventory even when detailed analytics i
|
||||
domainCount: 2,
|
||||
linkCount: 2,
|
||||
totalVisits: 40,
|
||||
invalidClicks: 7,
|
||||
rootVisits: 9,
|
||||
domains: [
|
||||
{ domain, linkCount: 2, totalVisits: 12, href: '/admin/domains/go.example.test' },
|
||||
{
|
||||
@@ -78,6 +80,8 @@ test('keeps the inventory and last activity when stored totals are unavailable',
|
||||
expect(data).toMatchObject({
|
||||
analyticsEnabled: true,
|
||||
totalVisits: null,
|
||||
invalidClicks: null,
|
||||
rootVisits: null,
|
||||
lastActivityAt: Date.parse(lastActivityAt)
|
||||
});
|
||||
expect(data.domains).toMatchObject([
|
||||
|
||||
@@ -5,6 +5,11 @@ export {
|
||||
clearDailyVisitStatistics,
|
||||
readLinkVisitDetails,
|
||||
readVisitDetails,
|
||||
readAnalyticsVisitDetails,
|
||||
readLastVisitActivity
|
||||
} from './storage.js';
|
||||
export type { DailyStatisticsMismatch, LinkVisitDetails } from './storage.js';
|
||||
export type {
|
||||
AnalyticsVisitDetails,
|
||||
DailyStatisticsMismatch,
|
||||
LinkVisitDetails
|
||||
} from './storage.js';
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { sql, type Kysely } from 'kysely';
|
||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
|
||||
import { openDb, runMigrations } from '../index.js';
|
||||
import { addVisitTotals, openDb, runMigrations } from '../index.js';
|
||||
import type { Database } from '../types.js';
|
||||
import {
|
||||
addDailyVisitStatistics,
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
clearDailyVisitStatistics,
|
||||
deleteExpiredDailyStatistics,
|
||||
readVisitDetails,
|
||||
readAnalyticsVisitDetails,
|
||||
readLinkVisitDetails,
|
||||
readLastVisitActivity
|
||||
} from './storage.js';
|
||||
@@ -275,6 +276,87 @@ test('selected-link readers bind exact path/domain pairs and ignore distractors'
|
||||
expect(await readLastVisitActivity(db, period, [])).toBeNull();
|
||||
});
|
||||
|
||||
test('Analytics separates Root visits without changing invalid clicks or counting roots in link breakdowns', async () => {
|
||||
const otherDomain = { kind: 'domain', domain: 'old.example.test' } as const;
|
||||
const otherRoot = { ...rootScope, domain: otherDomain.domain };
|
||||
const docs = { ...rootScope, path: '/docs' };
|
||||
const root = daily(rootScope, 2, 0, 12);
|
||||
const day = '2026-04-01';
|
||||
const nextDay = '2026-04-02';
|
||||
const rootOnlyDay = '2026-04-03';
|
||||
const rootOnlyVisitAt = Date.parse(`${rootOnlyDay}T10:00:00Z`);
|
||||
const nextDayTotals = { validVisits: 3, invalidVisits: 1 };
|
||||
await writer(async (transaction) => {
|
||||
await addVisitTotals(transaction, [
|
||||
{ scope: domainScope, totals: { validVisits: 7, invalidVisits: 2 } },
|
||||
{ scope: otherDomain, totals: { validVisits: 3, invalidVisits: 1 } }
|
||||
]);
|
||||
await addDailyVisitStatistics(transaction, [
|
||||
daily(overviewScope, 6, 2, 12),
|
||||
daily(domainScope, 4, 1, 12),
|
||||
root,
|
||||
daily(otherRoot, 2),
|
||||
daily(docs, 2),
|
||||
{
|
||||
...daily(overviewScope, nextDayTotals.validVisits, nextDayTotals.invalidVisits),
|
||||
day: nextDay,
|
||||
lastVisitAt: Date.parse(`${nextDay}T10:00:00Z`)
|
||||
},
|
||||
{ ...daily(overviewScope), day: rootOnlyDay, lastVisitAt: rootOnlyVisitAt },
|
||||
{ ...daily(otherRoot), day: rootOnlyDay, lastVisitAt: rootOnlyVisitAt }
|
||||
]);
|
||||
});
|
||||
|
||||
const overview = await readAnalyticsVisitDetails(db, overviewScope, period);
|
||||
expect(overview.daily.find(({ start }) => start.startsWith(day))).toMatchObject({
|
||||
validVisits: 2,
|
||||
invalidVisits: 2,
|
||||
rootVisits: 4
|
||||
});
|
||||
expect(overview.daily.find(({ start }) => start.startsWith(nextDay))).toMatchObject(
|
||||
nextDayTotals
|
||||
);
|
||||
expect(overview.daily.find(({ start }) => start.startsWith(rootOnlyDay))).toMatchObject({
|
||||
validVisits: 0,
|
||||
invalidVisits: 0,
|
||||
rootVisits: 1
|
||||
});
|
||||
expect(overview.lastActivityAt).toBe(new Date(rootOnlyVisitAt).toISOString());
|
||||
expect(overview.browsers).toEqual([
|
||||
{ day, name: 'Firefox', validVisits: 2, invalidVisits: 2 },
|
||||
{ day: nextDay, name: 'Firefox', ...nextDayTotals }
|
||||
]);
|
||||
expect(overview.operatingSystems).toContainEqual({
|
||||
day,
|
||||
name: 'Linux',
|
||||
validVisits: 2,
|
||||
invalidVisits: 2
|
||||
});
|
||||
expect(overview.acceptedLanguages.filter((row) => row.day === day)).toEqual([
|
||||
{ day, name: 'en', validVisits: 2, invalidVisits: 2 },
|
||||
{ day, name: 'fr', validVisits: 2, invalidVisits: 2 }
|
||||
]);
|
||||
const scoped = await readAnalyticsVisitDetails(db, domainScope, period);
|
||||
expect(scoped.daily[0]).toMatchObject({ validVisits: 2, invalidVisits: 1, rootVisits: 2 });
|
||||
expect(scoped.lastActivityAt).toBe('2026-04-01T12:00:00.000Z');
|
||||
expect((await readAnalyticsVisitDetails(db, rootScope, period)).daily[0]).toMatchObject({
|
||||
validVisits: 2,
|
||||
invalidVisits: 0
|
||||
});
|
||||
expect((await readAnalyticsVisitDetails(db, docs, period)).daily[0]).toMatchObject({
|
||||
validVisits: 2,
|
||||
invalidVisits: 0
|
||||
});
|
||||
});
|
||||
|
||||
test('reports stored Root and aggregate counts without reconciling them', async () => {
|
||||
await add(daily(domainScope, 1, 1), daily(rootScope, 2));
|
||||
|
||||
const report = await readAnalyticsVisitDetails(db, domainScope, period);
|
||||
expect(report.daily[0]).toMatchObject({ validVisits: -1, invalidVisits: 1, rootVisits: 2 });
|
||||
expect(report.lastActivityAt).toBe('2026-04-01T10:00:00.000Z');
|
||||
});
|
||||
|
||||
test('successful empty reads give zeros/activity null; view time advances without writes and zero clears derived rows', async () => {
|
||||
expect(await readVisitDetails(db, overviewScope, period)).toEqual(
|
||||
projectVisitDetails(overviewScope, period, [])
|
||||
@@ -301,7 +383,7 @@ test('selected corrupt day JSON fails with a static error, while a failed table
|
||||
.updateTable('visit_daily_statistics')
|
||||
.set({ browsers_json: '[{"name":"private IP","validVisits":99,"invalidVisits":0}]' })
|
||||
.execute();
|
||||
await expect(readVisitDetails(db, overviewScope, period)).rejects.toThrow(
|
||||
await expect(readAnalyticsVisitDetails(db, overviewScope, period)).rejects.toThrow(
|
||||
/^Invalid analytics report$/
|
||||
);
|
||||
await expect(
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
projectVisitDetails,
|
||||
visitDays,
|
||||
type DailyVisitStatistics,
|
||||
type DailyVisitCountByName,
|
||||
type ReportPeriod,
|
||||
type ReportScope,
|
||||
type VisitDetails,
|
||||
@@ -115,6 +116,24 @@ export async function readVisitDetails(
|
||||
return details!;
|
||||
}
|
||||
|
||||
type AnalyticsDay = VisitDetails['daily'][number] & { rootVisits?: number };
|
||||
|
||||
export type AnalyticsVisitDetails = Omit<VisitDetails, 'scope' | 'version' | 'daily'> & {
|
||||
daily: AnalyticsDay[];
|
||||
};
|
||||
|
||||
type AggregateScope = Exclude<ReportScope, { kind: 'link' }>;
|
||||
|
||||
export async function readAnalyticsVisitDetails(
|
||||
db: Kysely<Database>,
|
||||
scope: ReportScope,
|
||||
period: ReportPeriod
|
||||
): Promise<AnalyticsVisitDetails> {
|
||||
return scope.kind === 'link'
|
||||
? readVisitDetails(db, scope, period)
|
||||
: readAggregateAnalytics(db, scope, period);
|
||||
}
|
||||
|
||||
export async function readLastVisitActivity(
|
||||
db: Kysely<Database>,
|
||||
period: ReportPeriod,
|
||||
@@ -227,15 +246,7 @@ async function readCurrentDetails(
|
||||
scopes: ReportScope[],
|
||||
period: ReportPeriod
|
||||
): Promise<VisitDetails[]> {
|
||||
const days = reportDays(period);
|
||||
for (const scope of scopes) checkReportScope(scope);
|
||||
if (scopes.length === 0) return [];
|
||||
const rows = await selectedDays(db, scopes)
|
||||
.where('day', '>=', days.first)
|
||||
.where('day', '<=', days.last)
|
||||
.selectAll()
|
||||
.orderBy('day')
|
||||
.execute();
|
||||
const rows = await readReportRows(db, scopes, period);
|
||||
const grouped = new Map<string, DailyVisitStatistics[]>();
|
||||
for (const row of rows) {
|
||||
const statistics = decodeDailyStatistics(row);
|
||||
@@ -249,6 +260,84 @@ async function readCurrentDetails(
|
||||
);
|
||||
}
|
||||
|
||||
async function readAggregateAnalytics(
|
||||
db: Kysely<Database>,
|
||||
scope: AggregateScope,
|
||||
period: ReportPeriod
|
||||
): Promise<AnalyticsVisitDetails> {
|
||||
const rows = await readReportRows(db, [scope], period, scope);
|
||||
const totals: DailyVisitStatistics[] = [];
|
||||
const rootRows: DailyStatisticsRow[] = [];
|
||||
const rootVisitsByDate = new Map<string, number>();
|
||||
for (const row of rows) {
|
||||
if (row.scope_kind === 'link') {
|
||||
rootRows.push(row);
|
||||
const visits = (rootVisitsByDate.get(row.day) ?? 0) + row.valid_visits;
|
||||
rootVisitsByDate.set(row.day, visits);
|
||||
} else {
|
||||
totals.push(decodeDailyStatistics(row));
|
||||
}
|
||||
}
|
||||
|
||||
const details = projectVisitDetails(scope, period, totals);
|
||||
return {
|
||||
...details,
|
||||
daily: details.daily.map((day) => {
|
||||
const rootVisits = rootVisitsByDate.get(day.start.slice(0, 10));
|
||||
return rootVisits === undefined
|
||||
? day
|
||||
: { ...day, validVisits: day.validVisits - rootVisits, rootVisits };
|
||||
}),
|
||||
browsers: subtractRootBreakdown(details.browsers, rootRows, 'browsers_json'),
|
||||
operatingSystems: subtractRootBreakdown(
|
||||
details.operatingSystems,
|
||||
rootRows,
|
||||
'operating_systems_json'
|
||||
),
|
||||
acceptedLanguages: subtractRootBreakdown(
|
||||
details.acceptedLanguages,
|
||||
rootRows,
|
||||
'accepted_languages_json'
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
async function readReportRows(
|
||||
db: Kysely<Database>,
|
||||
scopes: ReportScope[],
|
||||
period: ReportPeriod,
|
||||
rootTrafficFor?: AggregateScope
|
||||
): Promise<DailyStatisticsRow[]> {
|
||||
const days = reportDays(period);
|
||||
for (const scope of scopes) checkReportScope(scope);
|
||||
if (scopes.length === 0) return [];
|
||||
return selectedDays(db, scopes, rootTrafficFor)
|
||||
.where('day', '>=', days.first)
|
||||
.where('day', '<=', days.last)
|
||||
.selectAll()
|
||||
.orderBy('day')
|
||||
.execute();
|
||||
}
|
||||
|
||||
function subtractRootBreakdown(
|
||||
totals: DailyVisitCountByName[],
|
||||
roots: DailyStatisticsRow[],
|
||||
column: 'browsers_json' | 'operating_systems_json' | 'accepted_languages_json'
|
||||
): DailyVisitCountByName[] {
|
||||
const rootCounts = new Map<string, number>();
|
||||
for (const root of roots) {
|
||||
const breakdown: DailyVisitStatistics['browsers'] = JSON.parse(root[column]);
|
||||
for (const { name, validVisits } of breakdown) {
|
||||
const key = `${root.day}/${name}`;
|
||||
rootCounts.set(key, (rootCounts.get(key) ?? 0) + validVisits);
|
||||
}
|
||||
}
|
||||
return totals.flatMap((total) => {
|
||||
const validVisits = total.validVisits - (rootCounts.get(`${total.day}/${total.name}`) ?? 0);
|
||||
return validVisits === 0 && total.invalidVisits === 0 ? [] : [{ ...total, validVisits }];
|
||||
});
|
||||
}
|
||||
|
||||
function reportDays(period: ReportPeriod): { first: string; last: string } {
|
||||
checkReportPeriod(period);
|
||||
const days = visitDays(period);
|
||||
@@ -290,12 +379,24 @@ function decodeStoredBreakdowns(row: DailyStatisticsRow) {
|
||||
}
|
||||
}
|
||||
|
||||
function selectedDays(db: Kysely<Database>, scopes: ReportScope[]) {
|
||||
function selectedDays(
|
||||
db: Kysely<Database>,
|
||||
scopes: ReportScope[],
|
||||
rootTrafficFor?: AggregateScope
|
||||
) {
|
||||
const overview = scopes.some((scope) => scope.kind === 'overview');
|
||||
const domains = scopes.flatMap((scope) => (scope.kind === 'domain' ? [scope.domain] : []));
|
||||
const links = scopes.flatMap((scope) => (scope.kind === 'link' ? [scope] : []));
|
||||
const predicates: RawBuilder<boolean>[] = [];
|
||||
if (overview) predicates.push(sql<boolean>`scope_kind = 'overview'`);
|
||||
if (rootTrafficFor?.kind === 'overview') {
|
||||
predicates.push(sql<boolean>`scope_kind = 'link' AND path = '/'
|
||||
AND domain IN (SELECT domain FROM visit_totals WHERE scope_kind = 'domain')`);
|
||||
} else if (rootTrafficFor?.kind === 'domain') {
|
||||
predicates.push(
|
||||
sql<boolean>`scope_kind = 'link' AND domain = ${rootTrafficFor.domain} AND path = '/'`
|
||||
);
|
||||
}
|
||||
if (domains.length > 0) {
|
||||
predicates.push(sql<boolean>`scope_kind = 'domain' AND domain IN (${sql.join(domains)})`);
|
||||
}
|
||||
|
||||
@@ -44,21 +44,26 @@ 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 () => {
|
||||
test('separates lifetime Root visits, including former domains in the overview', 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, path: '/' }, totals: { validVisits: 1, invalidVisits: 0 } },
|
||||
{
|
||||
scope: { ...link, domain: formerDomain.domain, path: '/' },
|
||||
totals: { validVisits: 2, invalidVisits: 0 }
|
||||
},
|
||||
{ scope: link, totals: { validVisits: 1, invalidVisits: 0 } }
|
||||
])
|
||||
);
|
||||
|
||||
expect(await readOverviewVisitTotals(db, [domain.domain, 'empty.example.test'])).toEqual({
|
||||
overview: { validVisits: 6, invalidVisits: 2 },
|
||||
overview: { validVisits: 3, invalidVisits: 2, rootVisits: 3 },
|
||||
byDomain: new Map([
|
||||
[domain.domain, { validVisits: 4, invalidVisits: 1 }],
|
||||
[domain.domain, { validVisits: 3, invalidVisits: 1 }],
|
||||
['empty.example.test', { validVisits: 0, invalidVisits: 0 }]
|
||||
])
|
||||
});
|
||||
@@ -79,7 +84,7 @@ test('reads stored domain, Root, and current path totals without including other
|
||||
);
|
||||
|
||||
expect(await readDomainVisitTotals(db, domain.domain, ['/docs', '/new'])).toEqual({
|
||||
domain: { validVisits: 9, invalidVisits: 2 },
|
||||
domain: { validVisits: 7, invalidVisits: 2, rootVisits: 2 },
|
||||
byPath: new Map([
|
||||
['/', { validVisits: 2, invalidVisits: 0 }],
|
||||
['/docs', { validVisits: 3, invalidVisits: 0 }],
|
||||
|
||||
@@ -47,39 +47,59 @@ export async function readVisitTotals(
|
||||
return checkTotals({ validVisits: row.valid_visits, invalidVisits: row.invalid_visits });
|
||||
}
|
||||
|
||||
type AdminVisitTotals = VisitTotals & { rootVisits: number };
|
||||
|
||||
export async function readOverviewVisitTotals(
|
||||
db: Kysely<Database>,
|
||||
domains: readonly string[]
|
||||
): Promise<{ overview: VisitTotals; byDomain: Map<string, VisitTotals> }> {
|
||||
): Promise<{ overview: AdminVisitTotals; byDomain: Map<string, VisitTotals> }> {
|
||||
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<boolean>`scope_kind = 'overview' OR (
|
||||
scope_kind = 'domain' AND domain IN (SELECT value FROM json_each(${JSON.stringify(domains)}))
|
||||
)`
|
||||
sql<boolean>`scope_kind = 'overview'
|
||||
OR (scope_kind = 'link' AND path = '/' AND domain IN (
|
||||
SELECT domain FROM visit_totals WHERE scope_kind = 'domain'
|
||||
))
|
||||
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()]));
|
||||
let rootVisits = 0;
|
||||
const domainTotals = new Map(domains.map((domain) => [domain, zeroVisitTotals()]));
|
||||
const rootVisitsByDomain = new Map<string, number>();
|
||||
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);
|
||||
else if (row.scope_kind === 'domain' && row.domain !== null) {
|
||||
domainTotals.set(row.domain, totals);
|
||||
} else if (row.scope_kind === 'link' && row.domain !== null) {
|
||||
rootVisitsByDomain.set(row.domain, totals.validVisits);
|
||||
rootVisits += totals.validVisits;
|
||||
}
|
||||
}
|
||||
return { overview, byDomain };
|
||||
const byDomain = new Map<string, VisitTotals>();
|
||||
for (const [domain, totals] of domainTotals) {
|
||||
byDomain.set(domain, {
|
||||
...totals,
|
||||
validVisits: totals.validVisits - (rootVisitsByDomain.get(domain) ?? 0)
|
||||
});
|
||||
}
|
||||
return { overview: separateRootVisits(overview, rootVisits), byDomain };
|
||||
}
|
||||
|
||||
export async function readDomainVisitTotals(
|
||||
db: Kysely<Database>,
|
||||
domain: string,
|
||||
currentPaths: readonly string[]
|
||||
): Promise<{ domain: VisitTotals; byPath: Map<string, VisitTotals> }> {
|
||||
): Promise<{ domain: AdminVisitTotals; byPath: Map<string, VisitTotals> }> {
|
||||
checkReportScope({ kind: 'domain', domain });
|
||||
const paths = ['/', ...currentPaths];
|
||||
for (const path of paths) checkReportScope({ kind: 'link', domain, path });
|
||||
@@ -106,7 +126,10 @@ export async function readDomainVisitTotals(
|
||||
if (row.scope_kind === 'domain') domainTotals = totals;
|
||||
else if (row.path !== null) byPath.set(row.path, totals);
|
||||
}
|
||||
return { domain: domainTotals, byPath };
|
||||
return {
|
||||
domain: separateRootVisits(domainTotals, byPath.get('/')!.validVisits),
|
||||
byPath
|
||||
};
|
||||
}
|
||||
|
||||
export async function readLinkVisitCounts(
|
||||
@@ -136,6 +159,10 @@ export async function readLinkVisitCounts(
|
||||
return rows;
|
||||
}
|
||||
|
||||
function separateRootVisits(totals: VisitTotals, rootVisits: number): AdminVisitTotals {
|
||||
return { ...totals, validVisits: totals.validVisits - rootVisits, rootVisits };
|
||||
}
|
||||
|
||||
function checkTotals(totals: VisitTotals): VisitTotals {
|
||||
if (
|
||||
!Number.isSafeInteger(totals.validVisits) ||
|
||||
|
||||
Reference in new issue
Block a user