diff --git a/projects/packages/premium-analytics/.phan/config.php b/projects/packages/premium-analytics/.phan/config.php index 29b2b1e4c014..1bccf4858d63 100644 --- a/projects/packages/premium-analytics/.phan/config.php +++ b/projects/packages/premium-analytics/.phan/config.php @@ -15,7 +15,10 @@ array( // WooCommerce stubs for the TEMPORARY interim sync module port (WOOA7S-1550). // WooCommerce is a runtime, not composer, dependency; these let Phan resolve WC symbols. - '+stubs' => array( 'woocommerce', 'woocommerce-internal' ), + // 'wpcom' also pulls in wpcomsh's wpcom-features files (.phan/config.base.php), + // which is where wpcom_site_has_feature() is defined — it is not in the + // generated wpcom stubs. + '+stubs' => array( 'woocommerce', 'woocommerce-internal', 'wpcom' ), 'exclude_file_regex' => array( 'build/', // Test WooCommerce stubs would redefine the WC symbols the +stubs above provide. diff --git a/projects/packages/premium-analytics/changelog/wooa7s-1718-gate-videos-on-videopress b/projects/packages/premium-analytics/changelog/wooa7s-1718-gate-videos-on-videopress new file mode 100644 index 000000000000..4e16f07c1c2a --- /dev/null +++ b/projects/packages/premium-analytics/changelog/wooa7s-1718-gate-videos-on-videopress @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Make the Top videos widget, the Videos report, and the video detail page unavailable on sites without VideoPress, matching the Calypso Stats gating. diff --git a/projects/packages/premium-analytics/packages/site-sync/src/jetpack-script-data.d.ts b/projects/packages/premium-analytics/packages/site-sync/src/jetpack-script-data.d.ts index b2b4a099796d..09ea0c19ac27 100644 --- a/projects/packages/premium-analytics/packages/site-sync/src/jetpack-script-data.d.ts +++ b/projects/packages/premium-analytics/packages/site-sync/src/jetpack-script-data.d.ts @@ -15,6 +15,8 @@ declare module '@automattic/jetpack-script-data' { has_store_data: boolean; // Whether CSV export controls should render. Defaults to true server-side. csv_exports_enabled?: boolean; + // Whether the site runs VideoPress, which gates the video surfaces. + has_videopress?: boolean; }; } } diff --git a/projects/packages/premium-analytics/routes/reports/registry.test.ts b/projects/packages/premium-analytics/routes/reports/registry.test.ts index d250d7edff81..1da51639619d 100644 --- a/projects/packages/premium-analytics/routes/reports/registry.test.ts +++ b/projects/packages/premium-analytics/routes/reports/registry.test.ts @@ -1,7 +1,7 @@ /** * External dependencies */ -import { isSimpleSite } from '@automattic/jetpack-script-data'; +import { getScriptData, isSimpleSite } from '@automattic/jetpack-script-data'; /** * Internal dependencies */ @@ -9,13 +9,25 @@ import { getReportDefinition } from './registry'; jest.mock( '@automattic/jetpack-script-data', () => ( { isSimpleSite: jest.fn( () => true ), + getScriptData: jest.fn(), } ) ); const mockIsSimpleSite = isSimpleSite as jest.Mock; +const mockGetScriptData = getScriptData as jest.Mock; + +/** + * Point the mocked script data at a site with or without VideoPress. + * + * @param hasVideoPress - Whether the site runs VideoPress. + */ +function setVideoPress( hasVideoPress: boolean ) { + mockGetScriptData.mockReturnValue( { premium_analytics: { has_videopress: hasVideoPress } } ); +} describe( 'getReportDefinition', () => { beforeEach( () => { mockIsSimpleSite.mockReturnValue( true ); + setVideoPress( true ); } ); it( 'returns undefined for an unknown report', () => { @@ -51,4 +63,20 @@ describe( 'getReportDefinition', () => { expect( getReportDefinition( 'posts' )?.id ).toBe( 'posts' ); } ); + + it( 'returns the videos report on sites running VideoPress', () => { + expect( getReportDefinition( 'videos' )?.id ).toBe( 'videos' ); + } ); + + it( 'hides the videos report without VideoPress', () => { + setVideoPress( false ); + + expect( getReportDefinition( 'videos' ) ).toBeUndefined(); + } ); + + it( 'hides the videos report when the site never published the flag', () => { + mockGetScriptData.mockReturnValue( undefined ); + + expect( getReportDefinition( 'videos' ) ).toBeUndefined(); + } ); } ); diff --git a/projects/packages/premium-analytics/routes/reports/registry.ts b/projects/packages/premium-analytics/routes/reports/registry.ts index f80e0059a8e3..40f129d0e735 100644 --- a/projects/packages/premium-analytics/routes/reports/registry.ts +++ b/projects/packages/premium-analytics/routes/reports/registry.ts @@ -6,6 +6,7 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ +import { isVideoPressAvailable } from '../site-readiness'; // Import the tab resolver from `config/tabs` directly rather than the report's // `config` barrel. `route.ts` imports this registry in `beforeLoad`, so the // registry must stay free of React/UI at module scope; the `config/index.ts` @@ -162,6 +163,10 @@ export const REPORTS: Record< string, ReportDefinition > = { id: 'videos', getTitle: () => __( 'Videos', 'jetpack-premium-analytics-pkg' ), getDescription: () => __( 'See how your videos perform.', 'jetpack-premium-analytics-pkg' ), + // Play counts only exist for VideoPress-hosted videos, and Calypso gates + // its Videos module on the same signal. Mirrors the widget-level gate in + // `src/widget-type-support.php`. + isAvailable: isVideoPressAvailable, load: () => import( './videos/page' ), }, utm: { diff --git a/projects/packages/premium-analytics/routes/site-readiness.ts b/projects/packages/premium-analytics/routes/site-readiness.ts index 061894134e09..9b6675ce7c08 100644 --- a/projects/packages/premium-analytics/routes/site-readiness.ts +++ b/projects/packages/premium-analytics/routes/site-readiness.ts @@ -22,3 +22,18 @@ export function isPremiumAnalyticsInitialSyncFinished(): boolean { isSimpleSite() || ( getScriptData()?.premium_analytics?.initial_full_sync_finished ?? 0 ) > 0 ); } + +/** + * Check whether the site's VideoPress-backed surfaces should be shown. + * + * Defaults to false, unlike the sibling `csv_exports_enabled` flag: showing the + * video surfaces on a site that cannot produce play data is the empty report + * this gate exists to remove. Safe to default that way because every path that + * renders the dashboard runs `Analytics::load_dashboard_components()`, which + * registers the filter that injects the flag (`src/videopress-availability.php`). + * + * @return Whether VideoPress is available on this site. + */ +export function isVideoPressAvailable(): boolean { + return getScriptData()?.premium_analytics?.has_videopress ?? false; +} diff --git a/projects/packages/premium-analytics/routes/use-detail-breadcrumbs.test.ts b/projects/packages/premium-analytics/routes/use-detail-breadcrumbs.test.ts index 35abc9f6326a..62bf3cdca66f 100644 --- a/projects/packages/premium-analytics/routes/use-detail-breadcrumbs.test.ts +++ b/projects/packages/premium-analytics/routes/use-detail-breadcrumbs.test.ts @@ -52,7 +52,29 @@ const validOrigins = [ [ 'utm', 'UTM', 'campaign' ], ] as const; +/** + * Point the script data at a site with or without VideoPress. `videos` is only a + * valid origin on sites running VideoPress, and the report registry reads that + * from script data. + * + * @param hasVideoPress - Whether the site runs VideoPress. + */ +function setVideoPress( hasVideoPress: boolean ) { + Object.defineProperty( window, 'JetpackScriptData', { + configurable: true, + value: { premium_analytics: { has_videopress: hasVideoPress } }, + } ); +} + describe( 'useDetailBreadcrumbs', () => { + beforeEach( () => { + setVideoPress( true ); + } ); + + afterAll( () => { + delete window.JetpackScriptData; + } ); + it.each( validOrigins )( 'adds the %s report before the detail title', ( report, label, section ) => { @@ -86,6 +108,19 @@ describe( 'useDetailBreadcrumbs', () => { expect( result.current ).toEqual( [ { label: 'Detail title' } ] ); } ); + // `?origin=videos` outlives the feature: it survives in shared URLs, browser + // history, and bookmarks taken before a site turned VideoPress off. A known + // but unavailable report must be as unlinkable as an unknown one, or the crumb + // points at a page the route guard bounces straight back to the dashboard. + it( 'drops the videos crumb on a site without VideoPress', () => { + setVideoPress( false ); + mockSearch( 'videos' ); + + const { result } = renderHook( () => useDetailBreadcrumbs( 'A video' ) ); + + expect( result.current ).toEqual( [ { label: 'A video' } ] ); + } ); + // The origin is untrusted: it is a plain query param anyone can edit, so an // inherited object property must not read as a report either. it.each( [ 'bogus', 'constructor', 'toString' ] )( 'ignores the %s report id', report => { diff --git a/projects/packages/premium-analytics/routes/video-detail/route.test.ts b/projects/packages/premium-analytics/routes/video-detail/route.test.ts index 91c535f9e033..7a1cdb732fdf 100644 --- a/projects/packages/premium-analytics/routes/video-detail/route.test.ts +++ b/projects/packages/premium-analytics/routes/video-detail/route.test.ts @@ -2,6 +2,7 @@ import { needsReportDateParamsSeed } from '@jetpack-premium-analytics/data'; import { isPremiumAnalyticsInitialSyncFinished, isPremiumAnalyticsSiteConnected, + isVideoPressAvailable, } from '../site-readiness'; import { route } from './route'; @@ -21,6 +22,7 @@ jest.mock( '@jetpack-premium-analytics/data', () => ( { jest.mock( '../site-readiness', () => ( { isPremiumAnalyticsSiteConnected: jest.fn( () => true ), isPremiumAnalyticsInitialSyncFinished: jest.fn( () => true ), + isVideoPressAvailable: jest.fn( () => true ), } ) ); jest.mock( '@wordpress/route', () => ( { @@ -74,6 +76,14 @@ describe( 'video detail route.beforeLoad', () => { } ); + it( 'redirects home without VideoPress', async () => { + ( isVideoPressAvailable as jest.Mock ).mockReturnValueOnce( false ); + + await expect( beforeLoad( { videoId: '42' }, settledSearch ) ).rejects.toMatchObject( { + to: '/', + } ); + } ); + it( 'passes through a settled URL without redirecting', async () => { await expect( beforeLoad( { videoId: '42' }, settledSearch ) ).resolves.toBeUndefined(); } ); diff --git a/projects/packages/premium-analytics/routes/video-detail/route.ts b/projects/packages/premium-analytics/routes/video-detail/route.ts index 4d92fd4d4eff..e882afc8a3fc 100644 --- a/projects/packages/premium-analytics/routes/video-detail/route.ts +++ b/projects/packages/premium-analytics/routes/video-detail/route.ts @@ -15,6 +15,7 @@ import { ensureDashboardEntities } from '../dashboard-entities'; import { isPremiumAnalyticsInitialSyncFinished, isPremiumAnalyticsSiteConnected, + isVideoPressAvailable, } from '../site-readiness'; type VideoDetailParams = { videoId?: string }; @@ -33,8 +34,8 @@ function isValidVideoId( value: string | undefined ): value is string { /** * Route lifecycle for the video detail page. * - * The page is available only to connected sites after the initial analytics - * sync, and only for positive integer attachment IDs. + * The page is available only to connected sites running VideoPress, after the + * initial analytics sync, and only for positive integer attachment IDs. */ export const route = { beforeLoad: async ( { @@ -49,6 +50,13 @@ export const route = { throw redirect( { to: '/syncing' } ); } + // Kept apart from the id check below: a bookmarked URL on a site without + // VideoPress and a malformed one are different events, even though both + // currently land on the dashboard. + if ( ! isVideoPressAvailable() ) { + throw redirect( { to: '/' } ); + } + const videoId = params?.videoId; if ( ! isValidVideoId( videoId ) ) { throw redirect( { to: '/' } ); diff --git a/projects/packages/premium-analytics/routes/video-detail/stage.test.tsx b/projects/packages/premium-analytics/routes/video-detail/stage.test.tsx index f6d2abe1aba2..8b21f1b13928 100644 --- a/projects/packages/premium-analytics/routes/video-detail/stage.test.tsx +++ b/projects/packages/premium-analytics/routes/video-detail/stage.test.tsx @@ -138,6 +138,15 @@ function mockSummary( overrides: Record< string, unknown > = {} ) { } describe( 'video detail stage', () => { + // The page only renders on sites running VideoPress, and the report registry + // behind the Videos crumb reads that from script data. + beforeAll( () => { + Object.defineProperty( window, 'JetpackScriptData', { + configurable: true, + value: { premium_analytics: { has_videopress: true } }, + } ); + } ); + beforeEach( () => { jest.clearAllMocks(); mockDashboardLayouts.length = 0; @@ -148,6 +157,10 @@ describe( 'video detail stage', () => { }; } ); + afterAll( () => { + delete window.JetpackScriptData; + } ); + it( 'shows a not-found state with a date-preserving link back to Videos', () => { mockSummary( { isNotFound: true } ); diff --git a/projects/packages/premium-analytics/src/class-analytics.php b/projects/packages/premium-analytics/src/class-analytics.php index 44b632dc9af8..500cd9d31423 100644 --- a/projects/packages/premium-analytics/src/class-analytics.php +++ b/projects/packages/premium-analytics/src/class-analytics.php @@ -327,6 +327,13 @@ private static function load_dashboard_components() { require_once __DIR__ . '/csv-exports.php'; } configure_csv_exports(); + + // VideoPress availability for the client's video routes. The widget layer + // reads the same signal through widget-type-support.php. + if ( ! function_exists( __NAMESPACE__ . '\\configure_videopress_availability' ) ) { + require_once __DIR__ . '/videopress-availability.php'; + } + configure_videopress_availability(); } /** diff --git a/projects/packages/premium-analytics/src/dashboard-layout.php b/projects/packages/premium-analytics/src/dashboard-layout.php index 20ddb1d44e31..9ebc1edba29a 100644 --- a/projects/packages/premium-analytics/src/dashboard-layout.php +++ b/projects/packages/premium-analytics/src/dashboard-layout.php @@ -247,7 +247,7 @@ function get_dashboard_default_section_layouts() { 'max' => 10, ) ), - // Row 4: VideoPress + clicks + authors. + // Row 4: VideoPress (sites running VideoPress only) + clicks + authors. get_dashboard_default_widget_instance( 'default-videopress-widget-instance', 'jpa/videopress', diff --git a/projects/packages/premium-analytics/src/videopress-availability.php b/projects/packages/premium-analytics/src/videopress-availability.php new file mode 100644 index 000000000000..14e703416446 --- /dev/null +++ b/projects/packages/premium-analytics/src/videopress-availability.php @@ -0,0 +1,105 @@ +is_wpcom_platform() ) { + $is_available = function_exists( 'wpcom_site_has_feature' ) && \wpcom_site_has_feature( 'videopress' ); + } else { + // `false` skips the module registry the standalone Premium Analytics plugin + // does not ship, which would otherwise report every module inactive. + $is_available = ( new Modules() )->is_active( 'videopress', false ) + || Constants::is_defined( 'JETPACK_VIDEOPRESS_ROOT_FILE' ); + } + + /** + * Filters whether Premium Analytics treats VideoPress as available. + * + * Hides the Top videos widget, the Videos report, and the video detail page + * when false. + * + * @param bool $is_available Whether VideoPress was detected in the current request. + */ + return (bool) apply_filters( VIDEOPRESS_AVAILABLE_FILTER, $is_available ); +} + +/** + * Configures the VideoPress script data. + * + * @return void + */ +function configure_videopress_availability() { + add_filter( 'jetpack_admin_js_script_data', __NAMESPACE__ . '\\inject_videopress_script_data', 20 ); +} + +/** + * Injects the VideoPress availability flag into JetpackScriptData. + * + * The client cannot read `site.plan.features` for this: that key is only + * populated when the Publicize package happens to be loaded, which the + * standalone Premium Analytics plugin never loads. + * + * @param array $data The script data passed by the assets package. + * @return array + */ +function inject_videopress_script_data( array $data ): array { + if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) { + $data['premium_analytics'] = array(); + } + + $data['premium_analytics']['has_videopress'] = is_videopress_available(); + + return $data; +} diff --git a/projects/packages/premium-analytics/src/widget-type-support.php b/projects/packages/premium-analytics/src/widget-type-support.php index ab2c1457ca96..b571d8a2c9d6 100644 --- a/projects/packages/premium-analytics/src/widget-type-support.php +++ b/projects/packages/premium-analytics/src/widget-type-support.php @@ -3,7 +3,9 @@ * Widget type support shared by the registry and default layouts. * * Persisted layouts are left unchanged so missing types remain as removable - * ghost widgets. Temporary restrictions belong in the runtime types filter. + * ghost widgets. This is for hard availability — the host, or a feature the site + * either has or does not. Request-dependent or soft state (shown locked, say) + * belongs in the runtime types filter instead. * * @package automattic/jetpack-premium-analytics */ @@ -12,21 +14,38 @@ use Automattic\Jetpack\Status\Host; +// Guarded on a symbol the file declares, so a second copy of the package can't +// redeclare it. See the include block in Analytics::load_dashboard_components(). +if ( ! function_exists( __NAMESPACE__ . '\\is_videopress_available' ) ) { + require_once __DIR__ . '/videopress-availability.php'; +} + +/** + * Widget types that only have data on a site running VideoPress. + */ +const VIDEOPRESS_WIDGET_TYPES = array( + 'jpa/videopress', + 'jpa/video-detail-highlights', + 'jpa/video-detail-views-performance', + 'jpa/video-detail-embeds', +); + /** * Returns the current widget support context. * - * @return array{is_wpcom_simple:bool} Widget support context. + * @return array{is_wpcom_simple:bool,has_videopress:bool} Widget support context. */ function get_widget_support_context() { return array( 'is_wpcom_simple' => ( new Host() )->is_wpcom_simple(), + 'has_videopress' => is_videopress_available(), ); } /** * Returns unsupported widget types for a context. * - * @param array{is_wpcom_simple:bool} $context Widget support context. + * @param array{is_wpcom_simple?:bool,has_videopress?:bool} $context Widget support context; a missing key reads as false. * @return string[] Unsupported widget type names. */ function get_unsupported_widget_types( $context ) { @@ -34,7 +53,7 @@ function get_unsupported_widget_types( $context ) { // File download tracking is served only on WPCOM Simple. Calypso applies // the same boundary, which excludes self-hosted Jetpack and Atomic sites. - if ( ! $context['is_wpcom_simple'] ) { + if ( empty( $context['is_wpcom_simple'] ) ) { $unsupported[] = 'jpa/file-downloads'; // Share counts are recorded when the share request is processed, which @@ -45,15 +64,22 @@ function get_unsupported_widget_types( $context ) { $unsupported[] = 'jpa/shares'; } + // Play counts only exist for VideoPress-hosted videos, so without VideoPress + // these widgets have nothing to report. Calypso gates its Videos module the + // same way (see videopress-availability.php). + if ( empty( $context['has_videopress'] ) ) { + $unsupported = array_merge( $unsupported, VIDEOPRESS_WIDGET_TYPES ); + } + return $unsupported; } /** * Removes unsupported widget records. * - * @param array $items Widget records. - * @param string $type_key Record key containing the widget type. - * @param array{is_wpcom_simple:bool} $context Widget support context. + * @param array $items Widget records. + * @param string $type_key Record key containing the widget type. + * @param array{is_wpcom_simple?:bool,has_videopress?:bool} $context Widget support context; a missing key reads as false. * @return array Filtered and re-indexed widget records. */ function remove_unsupported_widget_items( $items, $type_key, $context ) { diff --git a/projects/packages/premium-analytics/tests/js/site-readiness.test.ts b/projects/packages/premium-analytics/tests/js/site-readiness.test.ts index 21ff3c27f100..dfd70610d320 100644 --- a/projects/packages/premium-analytics/tests/js/site-readiness.test.ts +++ b/projects/packages/premium-analytics/tests/js/site-readiness.test.ts @@ -4,6 +4,7 @@ import { isPremiumAnalyticsInitialSyncFinished, isPremiumAnalyticsSiteConnected, + isVideoPressAvailable, } from '../../routes/site-readiness'; /** @@ -62,4 +63,20 @@ describe( 'Premium Analytics site readiness', () => { expect( isPremiumAnalyticsSiteConnected() ).toBe( true ); expect( isPremiumAnalyticsInitialSyncFinished() ).toBe( false ); } ); + + it( 'reads VideoPress availability from the server flag', () => { + setScriptData( { premium_analytics: { has_videopress: true } } ); + + expect( isVideoPressAvailable() ).toBe( true ); + } ); + + it.each( [ + [ 'the flag is false', { premium_analytics: { has_videopress: false } } ], + [ 'the flag is absent', { premium_analytics: { initial_full_sync_finished: 123 } } ], + [ 'no script data was published', {} ], + ] )( 'treats VideoPress as unavailable when %s', ( _case, data ) => { + setScriptData( data ); + + expect( isVideoPressAvailable() ).toBe( false ); + } ); } ); diff --git a/projects/packages/premium-analytics/tests/php/Analytics_Test.php b/projects/packages/premium-analytics/tests/php/Analytics_Test.php index b9497cc88dd9..7af1db20f54b 100644 --- a/projects/packages/premium-analytics/tests/php/Analytics_Test.php +++ b/projects/packages/premium-analytics/tests/php/Analytics_Test.php @@ -960,6 +960,13 @@ public function test_front_end_request_registers_no_admin_surface() { ), 'The CSV export script data is not wired on a front-end request.' ); + $this->assertFalse( + has_filter( + 'jetpack_admin_js_script_data', + __NAMESPACE__ . '\\inject_videopress_script_data' + ), + 'The VideoPress availability flag is not wired on a front-end request.' + ); } /** @@ -1016,5 +1023,12 @@ public function test_wpcom_simple_admin_request_keeps_the_dashboard() { ), 'Simple still wires the CSV export script data.' ); + $this->assertNotFalse( + has_filter( + 'jetpack_admin_js_script_data', + __NAMESPACE__ . '\\inject_videopress_script_data' + ), + 'Simple still publishes the VideoPress availability flag.' + ); } } diff --git a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php index bc5217df0d64..d91a0f547f3e 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -8,6 +8,7 @@ namespace Automattic\Jetpack\PremiumAnalytics; use Automattic\Jetpack\Constants; +use Automattic\Jetpack\Status\Cache; use WorDBless\BaseTestCase; use WP_REST_Request; use WP_REST_Server; @@ -36,6 +37,10 @@ public function tear_down() { wp_set_current_user( 0 ); remove_all_filters( SUBSCRIBERS_DASHBOARD_SECTION_AVAILABLE_FILTER ); Constants::clear_constants(); + // The default layout now reaches Host::is_wpcom_platform(), which memoizes + // `is_woa_site` past Constants::clear_constants(). + Cache::clear(); + remove_all_filters( VIDEOPRESS_AVAILABLE_FILTER ); parent::tear_down(); } @@ -239,6 +244,26 @@ public function test_traffic_default_excludes_simple_only_widgets_on_self_hosted $this->assertContains( 'jpa/clicks', $layout_types, 'Regular widget instances remain in the default layout.' ); } + /** + * The Top videos instance follows VideoPress, which this test env lacks. + */ + public function test_traffic_default_excludes_videopress_widget_without_videopress() { + $layout_types = array_column( get_dashboard_default_layout_for( DASHBOARD_TRAFFIC_SECTION_ID ), 'type' ); + + $this->assertNotContains( 'jpa/videopress', $layout_types, 'Top videos must not be part of the default layout without VideoPress.' ); + } + + /** + * With VideoPress, the Top videos instance is back in the default layout. + */ + public function test_traffic_default_keeps_videopress_widget_with_videopress() { + add_filter( VIDEOPRESS_AVAILABLE_FILTER, '__return_true' ); + + $layout_types = array_column( get_dashboard_default_layout_for( DASHBOARD_TRAFFIC_SECTION_ID ), 'type' ); + + $this->assertContains( 'jpa/videopress', $layout_types ); + } + /** * WPCOM Simple keeps Simple-only widgets in the default layout. */ diff --git a/projects/packages/premium-analytics/tests/php/Videopress_Availability_Test.php b/projects/packages/premium-analytics/tests/php/Videopress_Availability_Test.php new file mode 100644 index 000000000000..cdb3cd2eba9a --- /dev/null +++ b/projects/packages/premium-analytics/tests/php/Videopress_Availability_Test.php @@ -0,0 +1,177 @@ +assertFalse( is_videopress_available() ); + } + + /** + * The Jetpack VideoPress module makes it available. + */ + public function test_videopress_is_available_with_the_jetpack_module() { + update_option( 'jetpack_active_modules', array( 'videopress' ) ); + + $this->assertTrue( is_videopress_available() ); + } + + /** + * The standalone VideoPress plugin defines its root-file constant as it loads. + */ + public function test_videopress_is_available_with_the_standalone_plugin() { + Constants::set_constant( 'JETPACK_VIDEOPRESS_ROOT_FILE', '/plugins/videopress/jetpack-videopress.php' ); + + $this->assertTrue( is_videopress_available() ); + } + + /** + * The WPCOM platform reads the plan feature, never the module list. + * + * The module stays active throughout, so every assertion here also proves the + * platform branch was the one taken: the self-hosted branch would answer true + * in all three cases. + * + * @dataProvider provide_wpcom_platform_sites + * + * @param array $constants Constants that place the site on the platform. + */ + #[DataProvider( 'provide_wpcom_platform_sites' )] + public function test_videopress_follows_the_plan_feature_on_the_wpcom_platform( $constants ) { + foreach ( $constants as $name => $value ) { + Constants::set_constant( $name, $value ); + } + update_option( 'jetpack_active_modules', array( 'videopress' ) ); + + $this->assertFalse( is_videopress_available(), 'A plan without the feature has no video surfaces.' ); + + $GLOBALS['jpa_test_wpcom_features'] = array( 'videopress' ); + $this->assertTrue( is_videopress_available(), 'The videopress plan feature turns the surfaces on.' ); + + // Guards the slug itself: a near-miss must not read as entitled. + $GLOBALS['jpa_test_wpcom_features'] = array( 'videopress-1tb-storage' ); + $this->assertFalse( is_videopress_available(), 'Only the exact `videopress` slug counts.' ); + } + + /** + * The constants that place a site on each half of the WPCOM platform. + * + * @return array}> + */ + public static function provide_wpcom_platform_sites() { + return array( + 'Simple' => array( array( 'IS_WPCOM' => true ) ), + 'Atomic' => array( + array( + 'ATOMIC_SITE_ID' => 123, + 'ATOMIC_CLIENT_ID' => 456, + 'WPCOMSH__PLUGIN_FILE' => '/plugins/wpcomsh/wpcomsh.php', + ), + ), + ); + } + + /** + * Consumers can override the detection either way. + */ + public function test_videopress_availability_is_filterable() { + add_filter( VIDEOPRESS_AVAILABLE_FILTER, '__return_true' ); + $this->assertTrue( is_videopress_available(), 'The filter can force detection on.' ); + + remove_all_filters( VIDEOPRESS_AVAILABLE_FILTER ); + update_option( 'jetpack_active_modules', array( 'videopress' ) ); + $this->assertTrue( is_videopress_available(), 'Baseline: the module makes it available.' ); + + add_filter( VIDEOPRESS_AVAILABLE_FILTER, '__return_false' ); + $this->assertFalse( is_videopress_available(), 'The filter can force detection off.' ); + } + + /** + * The flag rides along with the rest of the Premium Analytics script data. + */ + public function test_script_data_carries_the_flag_without_clobbering_siblings() { + add_filter( VIDEOPRESS_AVAILABLE_FILTER, '__return_true' ); + + $data = inject_videopress_script_data( + array( + 'premium_analytics' => array( + 'initial_full_sync_finished' => 0, + ), + ) + ); + + $this->assertSame( 0, $data['premium_analytics']['initial_full_sync_finished'] ); + $this->assertTrue( $data['premium_analytics']['has_videopress'] ); + } + + /** + * Sites without VideoPress publish the flag as false rather than omitting it. + */ + public function test_script_data_reports_false_without_videopress() { + $data = inject_videopress_script_data( array() ); + + $this->assertFalse( $data['premium_analytics']['has_videopress'] ); + } + + /** + * Configure registers the script data filter. + */ + public function test_configure_registers_script_data_filter() { + configure_videopress_availability(); + + $this->assertNotFalse( + has_filter( 'jetpack_admin_js_script_data', __NAMESPACE__ . '\\inject_videopress_script_data' ) + ); + } +} diff --git a/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php b/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php index 57d0feb60873..39572beb7511 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php @@ -8,6 +8,7 @@ namespace Automattic\Jetpack\PremiumAnalytics; use Automattic\Jetpack\Constants; +use Automattic\Jetpack\Status\Cache; use PHPUnit\Framework\Attributes\CoversFunction; use WorDBless\BaseTestCase; @@ -43,10 +44,18 @@ class Widget_Availability_Test extends BaseTestCase { /** * Reset constants and availability filters between tests. + * + * The support context now reaches Host::is_wpcom_platform(), which memoizes + * `is_woa_site` into the process-global status cache; clearing constants alone + * would leave a stale host verdict for the next test that sets Atomic ones. */ public function tear_down() { Constants::clear_constants(); + Cache::clear(); + $GLOBALS['jpa_test_wpcom_features'] = array(); + delete_option( 'jetpack_active_modules' ); remove_all_filters( WOOCOMMERCE_DASHBOARD_SECTION_AVAILABLE_FILTER ); + remove_all_filters( VIDEOPRESS_AVAILABLE_FILTER ); parent::tear_down(); } @@ -66,6 +75,14 @@ private function widget_candidates() { 'name' => 'jpa/file-downloads', 'category' => 'traffic', ), + array( + 'name' => 'jpa/videopress', + 'category' => 'stats', + ), + array( + 'name' => 'jpa/video-detail-highlights', + 'category' => 'stats', + ), array( 'name' => 'jpa/shares', 'category' => 'traffic', @@ -126,17 +143,21 @@ private function store_report_widget_candidates() { } /** - * Filters the standard candidates with explicit host context. + * Filters the standard candidates with an explicit support context. * * @param bool $is_wpcom_simple Whether the site is WPCOM Simple. + * @param bool $has_videopress Whether the site runs VideoPress. * @return string[] Remaining type names. */ - private function available_names( $is_wpcom_simple ) { + private function available_names( $is_wpcom_simple, $has_videopress = true ) { return array_column( remove_unsupported_widget_items( $this->widget_candidates(), 'name', - array( 'is_wpcom_simple' => $is_wpcom_simple ) + array( + 'is_wpcom_simple' => $is_wpcom_simple, + 'has_videopress' => $has_videopress, + ) ), 'name' ); @@ -159,6 +180,138 @@ public function test_type_policy_keeps_file_downloads_on_simple() { $this->assertContains( 'jpa/file-downloads', $this->available_names( true ) ); } + /** + * Without VideoPress, every gated video widget is unavailable. + */ + public function test_type_policy_removes_video_widgets_without_videopress() { + $candidates = array_map( + static function ( $name ) { + return array( + 'name' => $name, + 'category' => 'stats', + ); + }, + VIDEOPRESS_WIDGET_TYPES + ); + + $this->assertSame( + array(), + remove_unsupported_widget_items( + $candidates, + 'name', + array( + 'is_wpcom_simple' => true, + 'has_videopress' => false, + ) + ), + 'Every type in VIDEOPRESS_WIDGET_TYPES must be dropped, not just the ones listed as candidates.' + ); + + $this->assertContains( 'jpa/hello-world', $this->available_names( true, false ) ); + } + + /** + * With VideoPress, the video widgets stay available. + */ + public function test_type_policy_keeps_video_widgets_with_videopress() { + $names = $this->available_names( false, true ); + + $this->assertContains( 'jpa/videopress', $names ); + $this->assertContains( 'jpa/video-detail-highlights', $names ); + } + + /** + * The gate and the manifests agree in both directions: a renamed widget can't + * drop out of the gate, and a new video widget can't be added without joining + * it. + * + * The second half rests on a naming heuristic, which bounds what it can catch: + * a VideoPress-backed widget named without `video` would not be demanded here, + * and an unrelated `video-*` widget would be demanded wrongly. Widget manifests + * carry no "requires" field to key on instead; if one is ever added, this + * should read that rather than the name. + */ + public function test_videopress_widget_types_match_the_manifest() { + $manifests = glob( __DIR__ . '/../../widgets/*/widget.json' ); + $this->assertNotEmpty( $manifests, 'No widget manifests found — the glob path is wrong.' ); + + $video_names = array(); + foreach ( $manifests as $manifest ) { + // Assert rather than skip: a manifest silently dropped here is absent from + // both sides of the comparison below, so the guard would pass while the + // gate is missing a type — the one failure this test exists to catch. + $raw = file_get_contents( $manifest ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents + $this->assertNotFalse( $raw, "Could not read $manifest" ); + + $widget = json_decode( $raw, true ); + $this->assertIsArray( $widget, "Malformed manifest: $manifest" ); + $this->assertArrayHasKey( 'name', $widget, "Manifest declares no name: $manifest" ); + + if ( str_contains( $widget['name'], 'video' ) ) { + $video_names[] = $widget['name']; + } + } + + $gated = VIDEOPRESS_WIDGET_TYPES; + sort( $gated ); + sort( $video_names ); + + $this->assertSame( $gated, $video_names, 'Every video widget must be listed in VIDEOPRESS_WIDGET_TYPES.' ); + } + + /** + * The registry callback drops the video widgets when VideoPress is absent. + */ + public function test_registry_callback_removes_video_widgets_without_videopress() { + $names = array_column( + filter_registrable_widget_types_by_availability( $this->widget_candidates() ), + 'name' + ); + + $this->assertNotContains( 'jpa/videopress', $names ); + } + + /** + * Atomic reads the plan feature at the widget layer too — an active module is + * not enough there, and the feature alone is. + */ + public function test_registry_callback_follows_the_plan_feature_on_atomic() { + Constants::set_constant( 'ATOMIC_SITE_ID', 123 ); + Constants::set_constant( 'ATOMIC_CLIENT_ID', 456 ); + Constants::set_constant( 'WPCOMSH__PLUGIN_FILE', '/plugins/wpcomsh/wpcomsh.php' ); + update_option( 'jetpack_active_modules', array( 'videopress' ) ); + + $names = array_column( + filter_registrable_widget_types_by_availability( $this->widget_candidates() ), + 'name' + ); + + $this->assertNotContains( 'jpa/videopress', $names, 'An active module does not stand in for the plan feature on Atomic.' ); + + $GLOBALS['jpa_test_wpcom_features'] = array( 'videopress' ); + + $names = array_column( + filter_registrable_widget_types_by_availability( $this->widget_candidates() ), + 'name' + ); + + $this->assertContains( 'jpa/videopress', $names, 'The plan feature brings the video widgets back on Atomic.' ); + } + + /** + * Forcing availability on puts them back, proving the context reads the helper. + */ + public function test_registry_callback_keeps_video_widgets_with_videopress() { + add_filter( VIDEOPRESS_AVAILABLE_FILTER, '__return_true' ); + + $names = array_column( + filter_registrable_widget_types_by_availability( $this->widget_candidates() ), + 'name' + ); + + $this->assertContains( 'jpa/videopress', $names ); + } + /** * Shares is unavailable outside WPCOM Simple, where nothing records a share. */ @@ -190,7 +343,10 @@ public function test_type_policy_keeps_non_array_records() { array( 'name' => 'jpa/file-downloads' ), ), 'name', - array( 'is_wpcom_simple' => false ) + array( + 'is_wpcom_simple' => false, + 'has_videopress' => false, + ) ) ); } @@ -203,7 +359,14 @@ public function test_type_policy_keeps_records_without_type_key() { $this->assertSame( $items, - remove_unsupported_widget_items( $items, 'type', array( 'is_wpcom_simple' => false ) ) + remove_unsupported_widget_items( + $items, + 'type', + array( + 'is_wpcom_simple' => false, + 'has_videopress' => false, + ) + ) ); } @@ -214,7 +377,10 @@ public function test_type_policy_reindexes_filtered_records() { $filtered = remove_unsupported_widget_items( $this->widget_candidates(), 'name', - array( 'is_wpcom_simple' => false ) + array( + 'is_wpcom_simple' => false, + 'has_videopress' => false, + ) ); $this->assertSame( range( 0, count( $filtered ) - 1 ), array_keys( $filtered ), 'Filtered candidates must stay a JSON list.' ); diff --git a/projects/packages/premium-analytics/tests/php/bootstrap.php b/projects/packages/premium-analytics/tests/php/bootstrap.php index 6c278b821fa4..04d5ef4400c8 100644 --- a/projects/packages/premium-analytics/tests/php/bootstrap.php +++ b/projects/packages/premium-analytics/tests/php/bootstrap.php @@ -21,3 +21,8 @@ // and be exercised. Loaded after Test_Environment::init() so WordPress base classes // (e.g. WP_REST_Controller) are already available for the stubs to extend. require_once __DIR__ . '/mocks/woocommerce-mocks.php'; + +// Controllable stand-in for the WPCOM platform's feature gate, so the Simple/Atomic +// branch of is_videopress_available() can be driven in both directions. Inert until a +// test populates $GLOBALS['jpa_test_wpcom_features']. +require_once __DIR__ . '/mocks/wpcom-feature-mocks.php'; diff --git a/projects/packages/premium-analytics/tests/php/mocks/wpcom-feature-mocks.php b/projects/packages/premium-analytics/tests/php/mocks/wpcom-feature-mocks.php new file mode 100644 index 000000000000..2254940aa703 --- /dev/null +++ b/projects/packages/premium-analytics/tests/php/mocks/wpcom-feature-mocks.php @@ -0,0 +1,40 @@ +