Skip to main content

When Did I Start on Reports

This example demonstrates how to use the reporting.lifecycle.removeEventListener function.

In this example, the user is alerted the first time they create a new report. No alerts are created for subsequent reports.

In the below example, the user will be alerted for subsequent reports if they refresh the page (or otherwise reload the extension). Storing data externally, such as "have I created a report today", is left as an exercise to the reader.


Extension Code

https://github.com/radaisystems/radai-sdk/blob/main/examples/reporting-extensions-started-working/src/main.ts

import * as reporting from "@radai/reporting-extensions";

function startedShift() {
// Stop listening to `report-created` events
reporting.lifecycle.removeEventListener("report-opened", startedShift);

// Code to keep track of shift starting
const startedShiftLog = `Started shift at ${new Date()}.`;
reporting.alerts.notify(startedShiftLog, { level: "success" });
}

reporting.lifecycle.addEventListener("report-opened", startedShift);

Tests

https://github.com/radaisystems/radai-sdk/blob/main/examples/reporting-extensions-started-working/src/main.test.ts

import * as reporting from "@radai/reporting-extensions";
import { describe, expect, test, vi } from "vitest";

describe("report-opened", () => {
test("started shift is logged once", async () => {
// Spy on the `reporting.alerts.notify` function to make sure it's called
vi.spyOn(reporting.alerts, "notify");

// Mock the current date so we can validate the notification content
const date = new Date(2024, 1, 1);
vi.setSystemTime(date);

// Initialize the SDK
reporting.mocks.initialize();

// Import our script
await import("./main.js");

// Assert initial state
expect(reporting.alerts.notify).not.toHaveBeenCalled();

// Create a report and another report immediately after
reporting.mocks.createReport();
reporting.mocks.createReport();

// Ensure only a single notification has been fired
await vi.waitFor(() => {
expect(reporting.alerts.notify).toHaveBeenCalledTimes(1);
expect(reporting.alerts.notify).toHaveBeenCalledWith(
`Started shift at ${date}.`,
{ level: "success" }
);
});
});
});