diff --git a/docs/SPEC.md b/docs/SPEC.md index c02ca876..97ca0a7d 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -485,7 +485,7 @@ Every AI call above starts from one of three places: a sequence an administrator | Any user-supplied URL | Adding a URL source, the URL preview utility route, analyzing or sideloading an image card | Plain GET. `SsrfGuard` blocks private IPs and sets redirects to 0 | | `en.wikipedia.org/w/api.php` | The Wikipedia research assistant runs | The search query | | Parse.ly Content API and Suggestions API, through wp-parsely's service classes | Smart links, headline suggestions, performance tools, the poll and the warmers | **Post content** (smart links, title suggestions), headlines and URLs | -| VIP Telemetry library (Pendo and Tracks), only when `Automattic\VIP\Telemetry\Telemetry` exists | Tool runs, agent runs, transition gates, rate-limit hits | Counts, outcomes and durations. No content | +| VIP Telemetry library (Tracks), only when `Automattic\VIP\Telemetry\Telemetry` exists | Tool runs, agent runs, transition gates, rate-limit hits, experiment toggles. From the browser: sequence editing, My Work filters and grouping, and editor workflow actions | Counts, outcomes, durations, IDs and option values. No content | Parse.ly calls require the wp-parsely plugin and its `apikey`/`api_secret` option. @@ -499,11 +499,12 @@ Parse.ly calls require the wp-parsely plugin and its `apikey`/`api_secret` optio | User-supplied URLs | 10 s for metadata, 30 s for downloads | `vip-workflows/includes/integrations/class-url-meta-extractor.php`, `vip-workflows/includes/integrations/class-ssrf-guard.php`, `vip-workflows/includes/api/class-ideation-controller.php` | | Wikipedia | 5 s through `vip_safe_wp_remote_get` | `workflow-assistant-wikipedia/workflow-assistant-wikipedia.php` | | Parse.ly | Set by wp-parsely | `workflow-parsely/includes/class-parsely-client.php` | -| VIP Telemetry | Errors are swallowed | `vip-workflows/includes/telemetry/class-tracker.php` | +| VIP Telemetry | Errors are swallowed. The browser sends nothing where the library isn't loaded or `vip_env` is `local` | `vip-workflows/includes/telemetry/class-tracker.php`, `vip-workflows/src/common/tracks.js` | Other outbound behavior: - The browser embeds YouTube and Vimeo iframes for video cards (`vip-workflows/src/admin/components/ideation/cards/ImageCard.js`). +- Browser telemetry queues events on `window._tkq` and loads `stats.wp.com/w.js` on the first event, not before. - `ContentExtractor` (`vip-workflows/includes/integrations/class-content-extractor.php`) has no callers. - **Jetpack:** no PHP, JS or Composer reference anywhere in the core plugin or the extensions. Parse.ly goes through wp-parsely, not Jetpack. diff --git a/vip-workflows/includes/admin/class-admin.php b/vip-workflows/includes/admin/class-admin.php index 1c6f272d..920ffedc 100644 --- a/vip-workflows/includes/admin/class-admin.php +++ b/vip-workflows/includes/admin/class-admin.php @@ -487,6 +487,7 @@ public function enqueue_scripts( string $hook_suffix ): void { 'myWork' => array( 'windowDays' => \VIPWorkflows\API\WorkflowController::MY_WORK_WINDOW_DAYS, ), + 'tracks' => \VIPWorkflows\Telemetry\Tracker::get_client_properties(), ); if ( self::screen_carries_skills( $hook_suffix ) ) { diff --git a/vip-workflows/includes/api/class-experiments-controller.php b/vip-workflows/includes/api/class-experiments-controller.php index 6b3b3839..f50adefc 100644 --- a/vip-workflows/includes/api/class-experiments-controller.php +++ b/vip-workflows/includes/api/class-experiments-controller.php @@ -10,6 +10,7 @@ namespace VIPWorkflows\API; use VIPWorkflows\Plugin; +use VIPWorkflows\Telemetry\Tracker; use WP_Error; use WP_REST_Controller; use WP_REST_Request; @@ -112,12 +113,30 @@ public function toggle_experiment( WP_REST_Request $request ) { ); } + $was_enabled = $registry->is_enabled( $id ); + if ( $enabled ) { $registry->enable( $id ); } else { $registry->disable( $id ); } + // The vip_workflows_experiments filter can pin an experiment on or off + // whatever was requested, so compare the effective state before and after. + $is_enabled = $registry->is_enabled( $id ); + + // Recorded here rather than in the browser: the Settings screen reloads + // as soon as its save resolves, which would drop an event still queued. + if ( $was_enabled !== $is_enabled ) { + Tracker::record( + 'settings_experiment_toggled', + array( + 'experiment_id' => $id, + 'enabled' => $is_enabled, + ) + ); + } + return new WP_REST_Response( $registry->to_array() ); } } diff --git a/vip-workflows/includes/editor/class-editor-integration.php b/vip-workflows/includes/editor/class-editor-integration.php index 590b7064..aad3a3ec 100644 --- a/vip-workflows/includes/editor/class-editor-integration.php +++ b/vip-workflows/includes/editor/class-editor-integration.php @@ -167,6 +167,7 @@ public function enqueue_editor_assets(): void { 'metadataFields' => $metadata_fields, 'roles' => $roles, 'workflowStatus' => $workflow_status, + 'tracks' => \VIPWorkflows\Telemetry\Tracker::get_client_properties(), ) ) . ';', 'before' diff --git a/vip-workflows/includes/telemetry/class-tracker.php b/vip-workflows/includes/telemetry/class-tracker.php index 34c96244..085bf0be 100644 --- a/vip-workflows/includes/telemetry/class-tracker.php +++ b/vip-workflows/includes/telemetry/class-tracker.php @@ -9,6 +9,9 @@ namespace VIPWorkflows\Telemetry; +use function Automattic\VIP\Telemetry\Tracks\get_base_properties_of_track_event; +use function Automattic\VIP\Telemetry\Tracks\get_base_properties_of_track_user; + /** * Records product-usage events through the VIP Telemetry library. * @@ -85,6 +88,41 @@ public static function is_available(): bool { return null !== self::telemetry(); } + /** + * Base properties for the events the browser records (src/common/tracks.js). + * + * The same base properties the library puts on server events, from its own + * two helpers: the site and environment (VIP environment and organization, + * WordPress and mu-plugins versions, hosting provider, and similar), and + * the anonymized user. Plus the plugin version. The browser records nothing + * when this is null, or when the environment is local. + * + * Called while an admin screen renders, so a helper that throws (the + * library is outside this plugin's control) yields null, the same as no + * library, rather than breaking the screen. record() does the same. + * + * @return array|null Null where the VIP Telemetry library isn't loaded or fails. + */ + public static function get_client_properties(): ?array { + if ( + ! self::is_available() + || ! function_exists( '\\Automattic\\VIP\\Telemetry\\Tracks\\get_base_properties_of_track_event' ) + || ! function_exists( '\\Automattic\\VIP\\Telemetry\\Tracks\\get_base_properties_of_track_user' ) + ) { + return null; + } + + try { + return array_merge( + get_base_properties_of_track_event(), + get_base_properties_of_track_user(), + array( 'plugin_version' => VIP_WORKFLOWS_VERSION ) + ); + } catch ( \Throwable $e ) { + return null; + } + } + /** * Replace the Telemetry instance, for tests. Pass null to use the library. * diff --git a/vip-workflows/package-lock.json b/vip-workflows/package-lock.json index d730ae20..f12f2ec0 100644 --- a/vip-workflows/package-lock.json +++ b/vip-workflows/package-lock.json @@ -25396,6 +25396,13 @@ "webpack": "^5.0.0" } }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true, + "license": "ISC" + }, "node_modules/minimatch": { "version": "11.0.7", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", diff --git a/vip-workflows/src/admin/components/SequencesList.js b/vip-workflows/src/admin/components/SequencesList.js index ae1216a7..31b96629 100644 --- a/vip-workflows/src/admin/components/SequencesList.js +++ b/vip-workflows/src/admin/components/SequencesList.js @@ -26,6 +26,7 @@ import { __, _n, sprintf } from '@wordpress/i18n'; import { plus } from '@wordpress/icons'; import { ModalActions } from '../../common/ModalActions'; +import { recordTracksEvent } from '../../common/tracks'; import AdminPage from './AdminPage'; import { CardGridView } from './CardGridView'; import { HowToModal } from './HowToModal'; @@ -321,6 +322,11 @@ export function SequencesList() { variant="primary" icon={ plus } href="#/new?type=workflow" + onClick={ () => + recordTracksEvent( 'sequence_create_started', { + source: 'header', + } ) + } > { __( 'New sequence', 'vip-workflows' ) } @@ -376,6 +382,14 @@ export function SequencesList() { diff --git a/vip-workflows/src/editor/components/WorkflowRequiredModal.js b/vip-workflows/src/editor/components/WorkflowRequiredModal.js index a7ae676f..87271ec2 100644 --- a/vip-workflows/src/editor/components/WorkflowRequiredModal.js +++ b/vip-workflows/src/editor/components/WorkflowRequiredModal.js @@ -14,6 +14,7 @@ import { store as noticesStore } from '@wordpress/notices'; import apiFetch from '@wordpress/api-fetch'; import { __ } from '@wordpress/i18n'; import { ModalActions } from '../../common/ModalActions'; +import { recordTracksEvent } from '../../common/tracks'; export function WorkflowRequiredModal( { postId, mode, onSelect, onSkip } ) { const [ sequences, setSequences ] = useState( [] ); @@ -58,6 +59,9 @@ export function WorkflowRequiredModal( { postId, mode, onSelect, onSkip } ) { data: { sequence_id: parseInt( selectedId, 10 ) }, } ) .then( () => { + recordTracksEvent( 'editor_workflow_selected', { + source: 'required_modal', + } ); onSelect?.(); } ) .catch( ( err ) => { diff --git a/vip-workflows/src/editor/components/WorkflowSummaryRows.js b/vip-workflows/src/editor/components/WorkflowSummaryRows.js index c5029f32..1e88cdd0 100644 --- a/vip-workflows/src/editor/components/WorkflowSummaryRows.js +++ b/vip-workflows/src/editor/components/WorkflowSummaryRows.js @@ -34,6 +34,7 @@ import { __ } from '@wordpress/i18n'; import { STORE_NAME } from '../store'; import { useConfirm } from '../../common/use-confirm'; +import { recordTracksEvent } from '../../common/tracks'; import { getOrphanedWorkflowRemoveConfirmation, getRemoveFromWorkflowConfirmation, @@ -132,6 +133,9 @@ export function WorkflowSummaryRows( { grouped = true } = {} ) { try { await assignSequence( sequenceId ); + recordTracksEvent( 'editor_workflow_selected', { + source: 'summary_row', + } ); } catch ( err ) { setActionError( err.message || @@ -171,6 +175,7 @@ export function WorkflowSummaryRows( { grouped = true } = {} ) { try { await removeWorkflow(); + recordTracksEvent( 'editor_workflow_removed' ); } catch ( err ) { setActionError( err.message || diff --git a/vip-workflows/src/editor/index.js b/vip-workflows/src/editor/index.js index fc5fd48a..6e1e2f9c 100644 --- a/vip-workflows/src/editor/index.js +++ b/vip-workflows/src/editor/index.js @@ -15,6 +15,7 @@ import { __ } from '@wordpress/i18n'; import { STORE_NAME } from './store'; import { refreshPostEntity } from './refresh-post-entity'; +import { usePanelToggleTracking } from './use-panel-toggle-tracking'; import { WorkflowPanel } from './components/WorkflowPanel'; import { WorkflowSaveGuard } from './components/WorkflowSaveGuard'; import { TransitionFlow } from './components/TransitionFlow'; @@ -58,6 +59,8 @@ function WorkflowPlugin() { const [ showModal, setShowModal ] = useState( showWorkflowModal ); + usePanelToggleTracking(); + const registry = useRegistry(); const { fetchWorkflowStatus } = useDispatch( STORE_NAME ); diff --git a/vip-workflows/src/editor/use-panel-toggle-tracking.js b/vip-workflows/src/editor/use-panel-toggle-tracking.js new file mode 100644 index 00000000..c9e451ed --- /dev/null +++ b/vip-workflows/src/editor/use-panel-toggle-tracking.js @@ -0,0 +1,30 @@ +/** + * Records the Workflow document panel being opened or closed. + * + * Core keeps the panel's open state in the user's editor preferences and offers + * no click callback, so this watches that state and records each change after + * the first read — the state a post loads with is not a toggle. + */ + +import { useEffect, useRef } from '@wordpress/element'; +import { useSelect } from '@wordpress/data'; + +import { recordTracksEvent } from '../common/tracks'; +import { WORKFLOW_PANEL_NAME } from './store'; + +export function usePanelToggleTracking() { + const opened = useSelect( + ( select ) => + select( 'core/editor' ).isEditorPanelOpened( WORKFLOW_PANEL_NAME ), + [] + ); + const previous = useRef( opened ); + + useEffect( () => { + if ( previous.current === opened ) { + return; + } + previous.current = opened; + recordTracksEvent( 'editor_panel_toggled', { opened } ); + }, [ opened ] ); +} diff --git a/vip-workflows/tests/phpunit/Unit/ExperimentsControllerTest.php b/vip-workflows/tests/phpunit/Unit/ExperimentsControllerTest.php index 1533daed..6168a6b5 100644 --- a/vip-workflows/tests/phpunit/Unit/ExperimentsControllerTest.php +++ b/vip-workflows/tests/phpunit/Unit/ExperimentsControllerTest.php @@ -99,6 +99,7 @@ public function test_toggle_enables_available_experiment(): void $registry = Mockery::mock( ExperimentRegistry::class ); $registry->shouldReceive( 'get' )->with( 'ideation' )->andReturn( $experiment ); + $registry->shouldReceive( 'is_enabled' )->with( 'ideation' )->andReturn( false ); $registry->shouldReceive( 'enable' )->once()->with( 'ideation' )->andReturn( true ); $registry->shouldReceive( 'to_array' )->andReturn( array() ); $this->seed_plugin_with_registry( $registry ); @@ -116,6 +117,7 @@ public function test_toggle_disables_experiment(): void $registry = Mockery::mock( ExperimentRegistry::class ); $registry->shouldReceive( 'get' )->with( 'ideation' )->andReturn( $experiment ); + $registry->shouldReceive( 'is_enabled' )->with( 'ideation' )->andReturn( true ); $registry->shouldReceive( 'disable' )->once()->with( 'ideation' )->andReturn( true ); $registry->shouldReceive( 'to_array' )->andReturn( array() ); $this->seed_plugin_with_registry( $registry ); @@ -126,6 +128,95 @@ public function test_toggle_disables_experiment(): void $this->assertInstanceOf( 'WP_REST_Response', $response ); } + public function test_a_toggle_that_changes_the_experiment_is_recorded(): void + { + $telemetry = $this->recording_telemetry(); + $this->seed_toggleable_registry( false, true ); + + $this->controller->toggle_experiment( $this->create_mock_request( array( 'id' => 'ideation', 'enabled' => true ) ) ); + + $this->assertSame( + array( + array( + 'event' => 'settings_experiment_toggled', + 'properties' => array( + 'experiment_id' => 'ideation', + 'enabled' => true, + ), + ), + ), + $telemetry->calls + ); + } + + public function test_a_toggle_that_changes_nothing_is_not_recorded(): void + { + $telemetry = $this->recording_telemetry(); + $this->seed_toggleable_registry( true, true ); + + $this->controller->toggle_experiment( $this->create_mock_request( array( 'id' => 'ideation', 'enabled' => true ) ) ); + + $this->assertSame( array(), $telemetry->calls ); + } + + public function test_a_toggle_overridden_by_the_experiments_filter_is_not_recorded(): void + { + $telemetry = $this->recording_telemetry(); + // Pinned on by the filter: disabling it leaves it enabled. + $this->seed_toggleable_registry( true, true ); + + $this->controller->toggle_experiment( $this->create_mock_request( array( 'id' => 'ideation', 'enabled' => false ) ) ); + + $this->assertSame( array(), $telemetry->calls ); + } + + /** + * Seed a registry whose ideation experiment is available, enabled or not + * before the toggle and after it. + * + * @param bool $before Whether the experiment is enabled before the toggle. + * @param bool $after Whether it is enabled after. + */ + private function seed_toggleable_registry( bool $before, bool $after ): void + { + $experiment = Mockery::mock( Experiment::class ); + $experiment->shouldReceive( 'is_available' )->andReturn( true ); + + $registry = Mockery::mock( ExperimentRegistry::class ); + $registry->shouldReceive( 'get' )->with( 'ideation' )->andReturn( $experiment ); + $registry->shouldReceive( 'is_enabled' )->with( 'ideation' )->andReturn( $before, $after ); + $registry->shouldReceive( 'enable', 'disable' )->andReturn( true ); + $registry->shouldReceive( 'to_array' )->andReturn( array() ); + $this->seed_plugin_with_registry( $registry ); + } + + /** + * Install a Telemetry double that records what it is sent, as a logged-in user. + * + * @return object + */ + private function recording_telemetry(): object + { + \Brain\Monkey\Functions\when( 'get_current_user_id' )->justReturn( 1 ); + + $telemetry = new class() { + /** @var array */ + public array $calls = array(); + + public function record_event( string $event, array $properties = array() ): bool + { + $this->calls[] = array( + 'event' => $event, + 'properties' => $properties, + ); + return true; + } + }; + \VIPWorkflows\Telemetry\Tracker::set_telemetry( $telemetry ); + + return $telemetry; + } + /** * Create a mock WP_REST_Request returning the given params. * diff --git a/vip-workflows/tests/phpunit/Unit/TrackerTest.php b/vip-workflows/tests/phpunit/Unit/TrackerTest.php index c62a61a6..f7c37821 100644 --- a/vip-workflows/tests/phpunit/Unit/TrackerTest.php +++ b/vip-workflows/tests/phpunit/Unit/TrackerTest.php @@ -220,4 +220,61 @@ public function test_it_is_available_when_there_is_a_telemetry_instance(): void $this->assertTrue( Tracker::is_available() ); } + + public function test_without_the_library_the_browser_gets_no_properties(): void + { + $this->assertNull( Tracker::get_client_properties() ); + } + + public function test_without_the_tracks_helpers_the_browser_gets_no_properties(): void + { + $this->assertFalse( function_exists( '\\Automattic\\VIP\\Telemetry\\Tracks\\get_base_properties_of_track_event' ), 'This test assumes the mu-plugin library is not loaded.' ); + Tracker::set_telemetry( $this->telemetry() ); + + $this->assertNull( Tracker::get_client_properties() ); + } + + /** + * In its own process, because the Tracks helper it declares cannot be undone. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_the_browser_gets_the_library_base_properties_and_the_plugin_version(): void + { + if ( ! defined( 'VIP_WORKFLOWS_VERSION' ) ) { + define( 'VIP_WORKFLOWS_VERSION', '0.0.1' ); + } + eval( 'namespace Automattic\\VIP\\Telemetry\\Tracks; function get_base_properties_of_track_event() { return array( "vip_env" => "production", "vip_org" => 42 ); } function get_base_properties_of_track_user() { return array( "_ui" => "abc", "_ut" => "vip:user_email", "plugin_version" => "stale" ); }' ); + Tracker::set_telemetry( $this->telemetry() ); + + $this->assertSame( + array( + 'vip_env' => 'production', + 'vip_org' => 42, + '_ui' => 'abc', + '_ut' => 'vip:user_email', + 'plugin_version' => VIP_WORKFLOWS_VERSION, + ), + Tracker::get_client_properties() + ); + } + + /** + * A library helper that throws yields no properties rather than breaking + * the admin screen it runs on. + * + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_a_throwing_library_helper_gives_the_browser_no_properties(): void + { + if ( ! defined( 'VIP_WORKFLOWS_VERSION' ) ) { + define( 'VIP_WORKFLOWS_VERSION', '0.0.1' ); + } + eval( 'namespace Automattic\\VIP\\Telemetry\\Tracks; function get_base_properties_of_track_event() { throw new \\Error( "Class not found" ); } function get_base_properties_of_track_user() { return array(); }' ); + Tracker::set_telemetry( $this->telemetry() ); + + $this->assertNull( Tracker::get_client_properties() ); + } } diff --git a/vip-workflows/tests/unit-js/filter-change.test.js b/vip-workflows/tests/unit-js/filter-change.test.js new file mode 100644 index 00000000..81c091cb --- /dev/null +++ b/vip-workflows/tests/unit-js/filter-change.test.js @@ -0,0 +1,74 @@ +/** + * Unit tests for describeFilterChange, which decides when My Work's filters + * changed enough to record, and what to record about it. + */ + +import { describeFilterChange } from '../../src/admin/utils/filter-change'; + +const author = ( value ) => ( { field: 'author', operator: 'isAny', value } ); +const stage = ( value ) => ( { + field: 'status_label', + operator: 'isAny', + value, +} ); + +describe( 'describeFilterChange', () => { + it( 'ignores a filter picked from the menu that has no value yet', () => { + expect( + describeFilterChange( [], [ author( undefined ) ] ) + ).toBeNull(); + expect( describeFilterChange( [], [ author( [] ) ] ) ).toBeNull(); + } ); + + it( 'ignores a view change that leaves the filters alone', () => { + expect( + describeFilterChange( [ author( [ 3 ] ) ], [ author( [ 3 ] ) ] ) + ).toBeNull(); + expect( describeFilterChange( undefined, undefined ) ).toBeNull(); + } ); + + it( 'reports a filter being applied, with the count now applied', () => { + expect( + describeFilterChange( + [ author( [ 3 ] ) ], + [ author( [ 3 ] ), stage( [ 'Review' ] ) ] + ) + ).toEqual( { field: 'status_label', filter_count: 2 } ); + } ); + + it( 'reports a changed value or operator on the same field', () => { + expect( + describeFilterChange( [ author( [ 3 ] ) ], [ author( [ 3, 4 ] ) ] ) + ).toEqual( { field: 'author', filter_count: 1 } ); + expect( + describeFilterChange( + [ author( [ 3 ] ) ], + [ { ...author( [ 3 ] ), operator: 'isNone' } ] + ) + ).toEqual( { field: 'author', filter_count: 1 } ); + } ); + + it( 'reports a filter being removed', () => { + expect( + describeFilterChange( + [ author( [ 3 ] ), stage( [ 'Review' ] ) ], + [ stage( [ 'Review' ] ) ] + ) + ).toEqual( { field: 'author', filter_count: 1 } ); + } ); + + it( 'reports a reset of several filters as multiple', () => { + expect( + describeFilterChange( + [ author( [ 3 ] ), stage( [ 'Review' ] ) ], + [] + ) + ).toEqual( { field: 'multiple', filter_count: 0 } ); + } ); + + it( 'never returns a filter value', () => { + const change = describeFilterChange( [], [ stage( [ 'Secret' ] ) ] ); + + expect( JSON.stringify( change ) ).not.toContain( 'Secret' ); + } ); +} ); diff --git a/vip-workflows/tests/unit-js/my-dashboard-filters.test.js b/vip-workflows/tests/unit-js/my-dashboard-filters.test.js index b0c54d25..0bb00e48 100644 --- a/vip-workflows/tests/unit-js/my-dashboard-filters.test.js +++ b/vip-workflows/tests/unit-js/my-dashboard-filters.test.js @@ -26,6 +26,9 @@ import { render, waitFor, act, screen } from './helpers/render-wp-component'; import apiFetch from '@wordpress/api-fetch'; jest.mock( '@wordpress/api-fetch', () => jest.fn() ); +jest.mock( '../../src/common/tracks', () => ( { + recordTracksEvent: jest.fn(), +} ) ); const mockCaptured = { props: null }; @@ -66,6 +69,7 @@ import { MyWorkPage } from '../../src/admin/pages/MyWorkPage'; import { MyQueuePage } from '../../src/admin/pages/MyQueuePage'; import { MyIdeationPage } from '../../src/admin/pages/MyIdeationPage'; import { adminGlobals } from './helpers/admin-globals'; +import { recordTracksEvent } from '../../src/common/tracks'; const WORKFLOW_ROW = { post_id: 1, @@ -517,6 +521,24 @@ describe( 'My Work view persistence', () => { expect( stored.groupBy ).toEqual( { field: 'author' } ); } ); + it( 'records a grouping change once it is saved', async () => { + await fieldsOf( MyWorkPage, [ WORKFLOW_ROW ] ); + recordTracksEvent.mockClear(); + + act( () => { + mockCaptured.props.onChangeView( { + ...mockCaptured.props.view, + groupBy: { field: 'author' }, + } ); + } ); + + expect( recordTracksEvent ).toHaveBeenCalledTimes( 1 ); + expect( recordTracksEvent ).toHaveBeenCalledWith( + 'dashboard_grouping_changed', + { group_by: 'author' } + ); + } ); + it( 'loads a previously persisted view on mount', async () => { window.vipWorkflowsAdmin = adminGlobals(); window.localStorage.setItem( @@ -567,6 +589,7 @@ describe( 'My Work view persistence', () => { it( 'reports failed writes and preserves the saved view', async () => { await fieldsOf( MyWorkPage, [ WORKFLOW_ROW ] ); const previousView = mockCaptured.props.view; + recordTracksEvent.mockClear(); window.localStorage.setItem( 'vip_workflows_my_work_view_42', JSON.stringify( previousView ) @@ -589,6 +612,7 @@ describe( 'My Work view persistence', () => { } ) ).toBeInTheDocument(); expect( mockCaptured.props.view ).toEqual( previousView ); + expect( recordTracksEvent ).not.toHaveBeenCalled(); expect( JSON.parse( window.localStorage.getItem( diff --git a/vip-workflows/tests/unit-js/panel-toggle-tracking.test.js b/vip-workflows/tests/unit-js/panel-toggle-tracking.test.js new file mode 100644 index 00000000..f19b7164 --- /dev/null +++ b/vip-workflows/tests/unit-js/panel-toggle-tracking.test.js @@ -0,0 +1,60 @@ +/** + * Unit tests for usePanelToggleTracking: the Workflow panel's open state as + * the post loads is not recorded; every change after it is. + */ + +import { renderHook } from '@testing-library/react'; + +import { usePanelToggleTracking } from '../../src/editor/use-panel-toggle-tracking'; +import { recordTracksEvent } from '../../src/common/tracks'; + +let mockOpened = false; + +jest.mock( '@wordpress/data', () => ( { + useSelect: ( selector ) => + selector( () => ( { isEditorPanelOpened: () => mockOpened } ) ), +} ) ); + +jest.mock( '../../src/editor/store', () => ( { + WORKFLOW_PANEL_NAME: 'vip-workflows/workflow', +} ) ); + +jest.mock( '../../src/common/tracks', () => ( { + recordTracksEvent: jest.fn(), +} ) ); + +describe( 'usePanelToggleTracking', () => { + beforeEach( () => { + jest.clearAllMocks(); + } ); + + it( 'records nothing for the state the post loads with', () => { + mockOpened = true; + const { rerender } = renderHook( () => usePanelToggleTracking() ); + rerender(); + + expect( recordTracksEvent ).not.toHaveBeenCalled(); + } ); + + it( 'records each open and close after that', () => { + mockOpened = false; + const { rerender } = renderHook( () => usePanelToggleTracking() ); + + mockOpened = true; + rerender(); + mockOpened = false; + rerender(); + + expect( recordTracksEvent ).toHaveBeenNthCalledWith( + 1, + 'editor_panel_toggled', + { opened: true } + ); + expect( recordTracksEvent ).toHaveBeenNthCalledWith( + 2, + 'editor_panel_toggled', + { opened: false } + ); + expect( recordTracksEvent ).toHaveBeenCalledTimes( 2 ); + } ); +} ); diff --git a/vip-workflows/tests/unit-js/tracks.test.js b/vip-workflows/tests/unit-js/tracks.test.js new file mode 100644 index 00000000..6a0aaab3 --- /dev/null +++ b/vip-workflows/tests/unit-js/tracks.test.js @@ -0,0 +1,159 @@ +/** + * Unit tests for the browser Tracks helper. + * + * The helper must stay silent wherever PHP localized no base properties (off + * VIP) and on local environments, and otherwise queue the prefixed event with + * the base properties under the event's own, loading the Tracks script once. + */ + +import { + getTracksBaseProperties, + recordTracksEvent, +} from '../../src/common/tracks'; + +const base = { + plugin_version: '1.0.0', + vip_env: 'production', + vip_org: 1, + is_vip_user: false, + hosting_provider: 'wpvip', + is_multisite: false, + wp_version: '6.9', + _ui: 'abc', + _ut: 'vip:user_email', +}; + +/** + * The Tracks script tags on the page. + * + * @return {HTMLScriptElement[]} Script elements loading stats.wp.com/w.js. + */ +const trackScripts = () => + Array.from( + document.querySelectorAll( 'script[src*="stats.wp.com/w.js"]' ) + ); + +describe( 'recordTracksEvent', () => { + beforeEach( () => { + delete window._tkq; + delete window.vipWorkflowsAdmin; + delete window.vipWorkflowsEditor; + trackScripts().forEach( ( script ) => script.remove() ); + } ); + + it( 'records nothing when no base properties were localized', () => { + window.vipWorkflowsAdmin = { tracks: null }; + + recordTracksEvent( 'editor_history_opened' ); + + expect( window._tkq ).toBeUndefined(); + expect( trackScripts() ).toHaveLength( 0 ); + } ); + + it( 'records nothing when the screen has no localized data at all', () => { + recordTracksEvent( 'editor_history_opened' ); + + expect( getTracksBaseProperties() ).toBeNull(); + expect( window._tkq ).toBeUndefined(); + expect( trackScripts() ).toHaveLength( 0 ); + } ); + + it( 'records nothing on a local environment', () => { + window.vipWorkflowsEditor = { tracks: { ...base, vip_env: 'local' } }; + + recordTracksEvent( 'editor_history_opened' ); + + expect( window._tkq ).toBeUndefined(); + expect( trackScripts() ).toHaveLength( 0 ); + } ); + + it( 'queues the prefixed event with the editor base properties', () => { + window.vipWorkflowsEditor = { tracks: base }; + + recordTracksEvent( 'editor_history_opened' ); + + expect( window._tkq ).toEqual( [ + [ 'recordEvent', 'vip_workflows_editor_history_opened', base ], + ] ); + } ); + + it( 'queues with the admin base properties, event properties last, undefined dropped', () => { + window.vipWorkflowsAdmin = { tracks: base }; + + recordTracksEvent( 'sequence_create_started', { + source: 'header', + plugin_version: 'overridden', + missing: undefined, + } ); + + expect( window._tkq ).toEqual( [ + [ + 'recordEvent', + 'vip_workflows_sequence_create_started', + { ...base, source: 'header', plugin_version: 'overridden' }, + ], + ] ); + } ); + + it( 'keeps events another script already queued', () => { + window.vipWorkflowsAdmin = { tracks: base }; + window._tkq = [ [ 'recordEvent', 'other_event', {} ] ]; + + recordTracksEvent( 'editor_history_opened' ); + + expect( window._tkq ).toHaveLength( 2 ); + expect( window._tkq[ 0 ] ).toEqual( [ + 'recordEvent', + 'other_event', + {}, + ] ); + } ); + + it( 'loads the Tracks script once, on the first event', () => { + window.vipWorkflowsAdmin = { tracks: base }; + + recordTracksEvent( 'editor_history_opened' ); + recordTracksEvent( 'editor_history_opened' ); + + expect( trackScripts() ).toHaveLength( 1 ); + expect( trackScripts()[ 0 ].src ).toBe( 'https://stats.wp.com/w.js' ); + expect( trackScripts()[ 0 ].async ).toBe( true ); + } ); + + it( 'does not load the Tracks script again when another plugin has', () => { + window.vipWorkflowsAdmin = { tracks: base }; + const existing = document.createElement( 'script' ); + existing.src = '//stats.wp.com/w.js'; + document.head.appendChild( existing ); + + recordTracksEvent( 'editor_history_opened' ); + + expect( trackScripts() ).toEqual( [ existing ] ); + } ); + + it( 'tries loading the Tracks script again after it fails once', () => { + window.vipWorkflowsAdmin = { tracks: base }; + + recordTracksEvent( 'editor_history_opened' ); + trackScripts()[ 0 ].dispatchEvent( new Event( 'error' ) ); + expect( trackScripts() ).toHaveLength( 0 ); + + recordTracksEvent( 'editor_history_opened' ); + + expect( trackScripts() ).toHaveLength( 1 ); + expect( window._tkq ).toHaveLength( 2 ); + } ); + + it( 'swallows a failure in the Tracks queue', () => { + window.vipWorkflowsAdmin = { tracks: base }; + window._tkq = { + push: () => { + throw new Error( 'boom' ); + }, + }; + + expect( () => + recordTracksEvent( 'editor_history_opened' ) + ).not.toThrow(); + } ); +} );