Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ export function getOrganizationEventsQuery(request: GetOrganizationEventsRequest

/**
* Get session count with aggregations for stats and chart data.
* Uses aggregation: avg:value cardinality:user date:(date^offset cardinality:user)
* Uses aggregation: avg:value cardinality:user date:(date^timezone cardinality:user)
*/
export function getOrganizationSessionsCountQuery(request: GetOrganizationSessionsCountRequest) {
const queryClient = useQueryClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,34 +28,45 @@
let { linkToDetails = true, showStatus = true, showType = true, summary }: Props = $props();
let showBadge: boolean = $derived(showStatus && 'status' in summary && summary.status !== 'open');
let badgeStatus = $derived<StackStatus>(('status' in summary && (summary.status as StackStatus)) || StackStatus.Open);
// Stack summaries always link to the stack; event summaries only when asked to.
let isLinked = $derived(linkToDetails || summary.template_key.startsWith('stack-'));
</script>

{#if summary.template_key === 'event-summary'}
<EventSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-summary'}
<StackSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-simple-summary'}
<EventSimpleSummary {linkToDetails} {summary} />
{:else if summary.template_key === 'stack-simple-summary'}
<StackSimpleSummary {badgeStatus} {showBadge} {summary} />
{:else if summary.template_key === 'event-error-summary'}
<EventErrorSummary {linkToDetails} {summary} />
{:else if summary.template_key === 'stack-error-summary'}
<StackErrorSummary {badgeStatus} {showBadge} {summary} />
{:else if summary.template_key === 'event-session-summary'}
<EventSessionSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-session-summary'}
<StackSessionSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-notfound-summary'}
<EventNotFoundSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-notfound-summary'}
<StackNotFoundSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-feature-summary'}
<EventFeatureSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-feature-summary'}
<StackFeatureSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-log-summary'}
<EventLogSummary {linkToDetails} {showType} {summary} />
{:else}
<StackLogSummary {badgeStatus} {showBadge} {showType} {summary} />
{/if}
<!-- The whole summary is the link target, so its bold type and method light up with the link on hover. -->
<div class:linked-summary={isLinked}>
{#if summary.template_key === 'event-summary'}
<EventSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-summary'}
<StackSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-simple-summary'}
<EventSimpleSummary {linkToDetails} {summary} />
{:else if summary.template_key === 'stack-simple-summary'}
<StackSimpleSummary {badgeStatus} {showBadge} {summary} />
{:else if summary.template_key === 'event-error-summary'}
<EventErrorSummary {linkToDetails} {summary} />
{:else if summary.template_key === 'stack-error-summary'}
<StackErrorSummary {badgeStatus} {showBadge} {summary} />
{:else if summary.template_key === 'event-session-summary'}
<EventSessionSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-session-summary'}
<StackSessionSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-notfound-summary'}
<EventNotFoundSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-notfound-summary'}
<StackNotFoundSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-feature-summary'}
<EventFeatureSummary {linkToDetails} {showType} {summary} />
{:else if summary.template_key === 'stack-feature-summary'}
<StackFeatureSummary {badgeStatus} {showBadge} {showType} {summary} />
{:else if summary.template_key === 'event-log-summary'}
<EventLogSummary {linkToDetails} {showType} {summary} />
{:else}
<StackLogSummary {badgeStatus} {showBadge} {showType} {summary} />
{/if}
</div>

<style>
.linked-summary:hover :global(:is(a, strong)) {
color: var(--primary);
}
</style>
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
</script>

<script generics="TData extends RowData" lang="ts">
import type { ProblemDetails } from '@foundatiofx/fetchclient';

import ChevronDown from '@lucide/svelte/icons/chevron-down';
import { type RowData, type StockFeatures, type Table } from '@tanstack/svelte-table';
import { toast } from 'svelte-sonner';
Expand All @@ -13,9 +11,10 @@

import { Button } from '#comp/ui/button/index.ts';
import * as DropdownMenu from '#comp/ui/dropdown-menu/index.ts';
import { deleteEvent } from '#features/events/api.svelte.ts';
import { organization } from '#features/organizations/context.svelte.ts';
import { postBulkOperation } from '#features/tasks/api.svelte.ts';
import { BulkOperationSelectionKind, EVENTS_DELETE_OPERATION } from '#features/tasks/models.ts';
import { getProblemMessage } from '#shared/validation.ts';

import RemoveEventDialog from '../dialogs/remove-event-dialog.svelte';

Expand Down Expand Up @@ -54,75 +53,64 @@
}
});

const removeEvents = deleteEvent({
route: {
get ids() {
return ids;
}
}
});

const removeMatchingEvents = postBulkOperation();
const startBulk = postBulkOperation();

function confirmRemove(): void {
confirmedSelectionIdentity = selectionIdentity;
openRemoveEventDialog = true;
}

/**
* Deletes the selected events, or everything matching the filter, as a background task. Ids go in the request body, so
* any number of selected events works. When it can't be started the problem is shown and the selection is kept.
*/
async function remove() {
if (isRemoving || confirmedSelectionIdentity !== selectionIdentity) {
const target = allMatching;
const selectedIds = ids;
const organizationId = target?.organizationId ?? organization.current;
if (!organizationId || selectedCount === 0 || isRemoving || confirmedSelectionIdentity !== selectionIdentity) {
return;
}

isRemoving = true;
try {
if (allMatching) {
await removeAllMatching(allMatching);
try {
await startBulk.mutateAsync({
organization_id: organizationId,
selection: target
? {
filter: target.filter ?? '',
kind: BulkOperationSelectionKind.Filter,
offset: target.offset,
time: target.time
}
: {
ids: selectedIds,
kind: BulkOperationSelectionKind.Ids
},
type: EVENTS_DELETE_OPERATION
});
} catch (error) {
// Keep the selection so the user can try again, for example after another delete finishes.
toast.error(getProblemMessage(error, 'Unable to start deleting the selected events.'));
return;
}

await removeSelected();
const count = target
? `about ${Intl.NumberFormat().format(target.count)} events`
: selectedIds.length === 1
? '1 event'
: `${Intl.NumberFormat().format(selectedIds.length)} events`;
toast.success(`Deleting ${count}. Progress is shown at the bottom of the page.`);
table.resetRowSelection();
if (target) {
onAllMatchingStarted?.();
}
} finally {
isRemoving = false;
}
}

async function removeAllMatching(target: AllMatchingTarget) {
try {
await removeMatchingEvents.mutateAsync({
organization_id: target.organizationId,
selection: {
filter: target.filter ?? '',
kind: BulkOperationSelectionKind.Filter,
offset: target.offset,
time: target.time
},
type: EVENTS_DELETE_OPERATION
});
} catch (error) {
// Keep the selection so the user can try again, for example after another delete finishes.
toast.error((error as Partial<ProblemDetails>)?.title || 'Unable to start deleting the matching events.');
return;
}

toast.success(`Deleting about ${Intl.NumberFormat().format(target.count)} events. Progress is shown at the bottom of the page.`);
table.resetRowSelection();
onAllMatchingStarted?.();
}

async function removeSelected() {
const deletedCount = ids.length;
await removeEvents.mutateAsync();

if (deletedCount === 1) {
toast.success('Successfully deleted event.');
} else {
toast.success(`Successfully deleted ${Intl.NumberFormat().format(deletedCount)} events.`);
}

table.resetRowSelection();
}

function setOpen(isOpen: boolean): void {
open = selectedCount > 0 && isOpen;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const mutateAsync = vi.hoisted(() => vi.fn());
const deleteEvent = vi.hoisted(() => vi.fn(() => ({ mutateAsync })));
const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
const startBulkOperation = vi.hoisted(() => vi.fn());
const postBulkOperation = vi.hoisted(() => vi.fn(() => ({ mutateAsync: startBulkOperation })));

vi.mock('#features/events/api.svelte.ts', () => ({ deleteEvent }));
vi.mock('#features/organizations/context.svelte.ts', () => ({ organization: { current: 'current-organization-id' } }));
vi.mock('#features/tasks/api.svelte.ts', () => ({ postBulkOperation }));
vi.mock('svelte-sonner', () => ({ toast }));

import EventsBulkActionsDropdownMenu from './events-bulk-actions-dropdown-menu.svelte';

describe('EventsBulkActionsDropdownMenu', () => {
beforeEach(() => {
mutateAsync.mockResolvedValue(undefined);
startBulkOperation.mockReset();
startBulkOperation.mockResolvedValue(undefined);
deleteEvent.mockClear();
toast.success.mockClear();
toast.error.mockClear();
});
Expand Down Expand Up @@ -75,10 +71,14 @@ describe('EventsBulkActionsDropdownMenu', () => {
await fireEvent.click(screen.getByRole('button', { name: 'Delete Event' }));

// Assert
await waitFor(() => expect(mutateAsync).toHaveBeenCalledOnce());
await waitFor(() => expect(startBulkOperation).toHaveBeenCalledOnce());
expect(startBulkOperation).toHaveBeenCalledWith({
organization_id: 'current-organization-id',
selection: { ids: ['event-id'], kind: 'Ids' },
type: 'events.delete'
});
expect(resetRowSelection).toHaveBeenCalledOnce();
expect(toast.success).toHaveBeenCalledWith('Successfully deleted event.');
expect(startBulkOperation).not.toHaveBeenCalled();
expect(toast.success).toHaveBeenCalledWith('Deleting 1 event. Progress is shown at the bottom of the page.');
});

it('uses the selected count for the bulk delete confirmation', async () => {
Expand All @@ -95,8 +95,8 @@ describe('EventsBulkActionsDropdownMenu', () => {
await fireEvent.click(screen.getByRole('button', { name: 'Delete 2 Events' }));

// Assert
await waitFor(() => expect(mutateAsync).toHaveBeenCalledOnce());
expect(toast.success).toHaveBeenCalledWith('Successfully deleted 2 events.');
await waitFor(() => expect(startBulkOperation).toHaveBeenCalledOnce());
expect(toast.success).toHaveBeenCalledWith('Deleting 2 events. Progress is shown at the bottom of the page.');
});

it('closes the confirmation when selected row IDs change even if the count stays the same', async () => {
Expand All @@ -113,7 +113,6 @@ describe('EventsBulkActionsDropdownMenu', () => {

// Assert
await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
expect(mutateAsync).not.toHaveBeenCalled();
expect(startBulkOperation).not.toHaveBeenCalled();
});

Expand Down Expand Up @@ -156,7 +155,6 @@ describe('EventsBulkActionsDropdownMenu', () => {
selection: { filter: 'type:error', kind: 'Filter', offset: '-300m', time: '[now-7d TO now]' },
type: 'events.delete'
});
expect(mutateAsync).not.toHaveBeenCalled();
expect(resetRowSelection).toHaveBeenCalledOnce();
expect(onAllMatchingStarted).toHaveBeenCalledOnce();
expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('Deleting about 1,234 events'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,29 @@
summary: SummaryModel<SummaryTemplateKeys>;
}

const countFormat = new Intl.NumberFormat();
const compactCountFormat = new Intl.NumberFormat(undefined, {
notation: 'compact'
});
const percentFormat = new Intl.NumberFormat(undefined, {
maximumFractionDigits: 1,
style: 'percent'
});

let { summary }: Props = $props();
let source = $derived(summary as StackSummaryModel<SummaryTemplateKeys>);
let percentage = $derived(source.total_users > 0 ? (source.users / source.total_users) * 100.0 : 0);
let users = $derived(source.users ?? 0);
let totalUsers = $derived(source.total_users ?? 0);
let title = $derived(
totalUsers > 0
? `${countFormat.format(users)} of ${countFormat.format(totalUsers)} users (${percentFormat.format(users / totalUsers)})`
: `${countFormat.format(users)} users`
);
</script>

<abbr title={`${source.users} of ${source.total_users} users`}>
{percentage.toFixed(1)}%
</abbr>
<!-- A count reads well whether or not the project tracks users; a share of a large total rounds to 0.0% and says nothing. -->
{#if users > 0}
<abbr class="tabular-nums no-underline" {title}>{compactCountFormat.format(users)}</abbr>
{:else}
<span class="text-muted-foreground" title="No users were identified on these events.">—</span>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use Muted (check for typography in pr)

{/if}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ export { DEFAULT_LIMIT } from './constants';
*/
export const DEFAULT_OFFSET = new SvelteDate().getTimezoneOffset() !== 0 ? new SvelteDate().getTimezoneOffset() * -1 + 'm' : undefined;

/**
* The time zone date histograms bucket in. An IANA zone keeps day buckets on local midnight across daylight saving changes,
* which a fixed offset can't: buckets from the other half of the year would start at 1 AM or 11 PM local time.
*/
export const DEFAULT_HISTOGRAM_TIME_ZONE = getHistogramTimeZone();

export class FetchClientStatus {
public isLoading = $state(false);

Expand Down Expand Up @@ -46,10 +52,29 @@ export async function fetchApiJson<T>(path: string, init: RequestInit): Promise<
return (await response.json()) as T;
}

/** The `date` aggregation term, bucketed in the user's time zone, e.g. `date^Europe/Amsterdam`. */
export function getDateHistogramTerm(field = 'date'): string {
return DEFAULT_HISTOGRAM_TIME_ZONE ? `${field}^${DEFAULT_HISTOGRAM_TIME_ZONE}` : field;
}

export function useFetchClientStatus(target?: FetchClient | FetchClientProvider) {
return new FetchClientStatus(target);
}

function getHistogramTimeZone(): string | undefined {
try {
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
// Unquoted aggregation terms can't contain whitespace or query syntax characters.
if (timeZone && timeZone !== 'UTC' && /^[\w+\-/]+$/.test(timeZone)) {
return timeZone;
}
} catch {
// Fall back to the fixed offset below.
}

return DEFAULT_OFFSET;
}

async function toProblemDetails(response: Response): Promise<ProblemDetails> {
const contentType = response.headers.get('Content-Type') ?? '';
if (contentType.startsWith('application/problem+json') || contentType.startsWith('application/json')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
<style>
.floating-glow {
box-shadow:
0 0 0 1px color-mix(in oklab, var(--foreground) 32%, transparent),
0 0 1px 1px color-mix(in oklab, var(--foreground) 32%, transparent),
0 0 14px 2px color-mix(in oklab, var(--foreground) 18%, transparent);
}
</style>
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
return date.toLocaleString(undefined, {
day: 'numeric',
hour: 'numeric',
hour12: true,
minute: '2-digit',
month: 'short',
second: '2-digit',
Expand Down
Loading
Loading