diff --git a/projects/packages/premium-analytics/changelog/add-wooa7s-1717-hide-file-downloads-on-self-hosted b/projects/packages/premium-analytics/changelog/add-wooa7s-1717-hide-file-downloads-on-self-hosted new file mode 100644 index 000000000000..6fa633ff1b58 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/add-wooa7s-1717-hide-file-downloads-on-self-hosted @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Hide the File downloads widget and report outside WordPress.com Simple sites, matching the Calypso Stats gating. diff --git a/projects/packages/premium-analytics/routes/reports/registry.test.ts b/projects/packages/premium-analytics/routes/reports/registry.test.ts new file mode 100644 index 000000000000..1596398197ed --- /dev/null +++ b/projects/packages/premium-analytics/routes/reports/registry.test.ts @@ -0,0 +1,45 @@ +/** + * External dependencies + */ +import { isSimpleSite } from '@automattic/jetpack-script-data'; +/** + * Internal dependencies + */ +import { getReportDefinition } from './registry'; + +jest.mock( '@automattic/jetpack-script-data', () => ( { + isSimpleSite: jest.fn( () => true ), +} ) ); + +const mockIsSimpleSite = isSimpleSite as jest.Mock; + +describe( 'getReportDefinition', () => { + beforeEach( () => { + mockIsSimpleSite.mockReturnValue( true ); + } ); + + it( 'returns undefined for an unknown report', () => { + expect( getReportDefinition( 'unknown' ) ).toBeUndefined(); + expect( getReportDefinition( undefined ) ).toBeUndefined(); + } ); + + it( 'returns the downloads report on Simple sites', () => { + expect( getReportDefinition( 'downloads' )?.id ).toBe( 'downloads' ); + } ); + + it( 'hides the downloads report on non-Simple sites', () => { + // Calypso only shows file downloads on Simple sites ("not yet supported + // in Jetpack environment", which includes Atomic); the route guard + // redirects an unavailable report to the dashboard, same as an unknown + // one. + mockIsSimpleSite.mockReturnValue( false ); + + expect( getReportDefinition( 'downloads' ) ).toBeUndefined(); + } ); + + it( 'keeps other reports available on non-Simple sites', () => { + mockIsSimpleSite.mockReturnValue( false ); + + expect( getReportDefinition( 'posts' )?.id ).toBe( 'posts' ); + } ); +} ); diff --git a/projects/packages/premium-analytics/routes/reports/registry.ts b/projects/packages/premium-analytics/routes/reports/registry.ts index 25dd8298fafc..5b0bbb9e24cb 100644 --- a/projects/packages/premium-analytics/routes/reports/registry.ts +++ b/projects/packages/premium-analytics/routes/reports/registry.ts @@ -1,6 +1,7 @@ /** * External dependencies */ +import { isSimpleSite } from '@automattic/jetpack-script-data'; import { __ } from '@wordpress/i18n'; /** * Internal dependencies @@ -55,6 +56,13 @@ export type ReportDefinition = { */ resolveSection?: ( value: string | undefined ) => string; + /** + * Whether the report is available on this site, resolved at lookup time. + * An unavailable report is treated like an unknown one — the route guard + * redirects it to the dashboard. Omit for reports available everywhere. + */ + isAvailable?: () => boolean; + /** * Dynamic import of the report's page component (default export). Kept as a * thunk so React/UI is only pulled in when the report actually renders, and @@ -107,6 +115,11 @@ export const REPORTS: Record< string, ReportDefinition > = { downloads: { id: 'downloads', getTitle: () => __( 'File downloads', 'jetpack-premium-analytics' ), + // File download tracking happens on WPCOM infrastructure; Calypso only + // shows the module on Simple sites ("not yet supported in Jetpack + // environment") and we mirror that boundary. Mirrors the widget-level + // gate in `src/widget-type-support.php`. + isAvailable: isSimpleSite, load: () => import( './downloads/page' ), }, emails: { @@ -161,5 +174,11 @@ export const REPORTS: Record< string, ReportDefinition > = { * @return The matching definition, or `undefined` when the id is missing or unknown. */ export function getReportDefinition( id: string | undefined ): ReportDefinition | undefined { - return id ? REPORTS[ id ] : undefined; + const definition = id ? REPORTS[ id ] : undefined; + + if ( definition?.isAvailable && ! definition.isAvailable() ) { + return undefined; + } + + return definition; } diff --git a/projects/packages/premium-analytics/src/dashboard-layout.php b/projects/packages/premium-analytics/src/dashboard-layout.php index 15b0d611f041..9c9479039763 100644 --- a/projects/packages/premium-analytics/src/dashboard-layout.php +++ b/projects/packages/premium-analytics/src/dashboard-layout.php @@ -16,6 +16,9 @@ require_once __DIR__ . '/dashboard-grammar.php'; require_once __DIR__ . '/rest-namespace.php'; +// Availability policy for default layout instances: defaults are read outside +// the widget registry bootstrap, so the policy must be loaded here explicitly. +require_once __DIR__ . '/widget-type-support.php'; /** * Identifier of the Premium Analytics dashboard, formatted as `_` @@ -62,7 +65,11 @@ function get_dashboard_default_layout_for( $dashboard_name ) { */ $default = apply_filters( DASHBOARD_DEFAULT_LAYOUT_FILTER, array(), $dashboard_name ); - return is_array( $default ) ? array_values( $default ) : array(); + return remove_unsupported_widget_items( + is_array( $default ) ? array_values( $default ) : array(), + 'type', + get_widget_support_context() + ); } /** diff --git a/projects/packages/premium-analytics/src/widget-availability.php b/projects/packages/premium-analytics/src/widget-availability.php index f29aa94225b7..dc73887e3321 100644 --- a/projects/packages/premium-analytics/src/widget-availability.php +++ b/projects/packages/premium-analytics/src/widget-availability.php @@ -5,17 +5,19 @@ * Premium Analytics' policy over the neutral filters in widget-types.php: * availability is the consumer's job, core only offers the hooks. * - * Ships two policies, both hooked on the registry-time filter (a hard hide, - * which keeps every registry consumer correct without a filtered accessor): - * developer-only widget types are never registered in production, and the - * commerce widget categories are only registered while the plugin backing - * them (WooCommerce, plus WooCommerce Bookings for `bookings`) is active. + * Policies are hooked on the registry-time filter (a hard hide, which keeps + * every registry consumer correct without a filtered accessor): developer-only + * widget types are never registered in production, Simple-only types are only + * registered on WPCOM Simple, and commerce categories require their plugins. * * @package automattic/jetpack-premium-analytics */ namespace Automattic\Jetpack\PremiumAnalytics; +require_once __DIR__ . '/widget-types.php'; +require_once __DIR__ . '/widget-type-support.php'; + /** * Widget categories that are only meaningful with WooCommerce active. */ @@ -69,6 +71,22 @@ function filter_registrable_widget_types_by_environment( $widget_candidates ) { add_filter( REGISTRABLE_WIDGET_TYPES_FILTER, __NAMESPACE__ . '\\filter_registrable_widget_types_by_environment' ); +/** + * Applies shared type-level availability at registry time. + * + * @param array $widget_candidates Manifest candidates. + * @return array Filtered candidates. + */ +function filter_registrable_widget_types_by_availability( $widget_candidates ) { + return remove_unsupported_widget_items( + $widget_candidates, + 'name', + get_widget_support_context() + ); +} + +add_filter( REGISTRABLE_WIDGET_TYPES_FILTER, __NAMESPACE__ . '\\filter_registrable_widget_types_by_availability' ); + /** * Removes candidates whose commerce category lacks its backing plugin. * diff --git a/projects/packages/premium-analytics/src/widget-type-support.php b/projects/packages/premium-analytics/src/widget-type-support.php new file mode 100644 index 000000000000..23678d84bfd4 --- /dev/null +++ b/projects/packages/premium-analytics/src/widget-type-support.php @@ -0,0 +1,68 @@ + ( new Host() )->is_wpcom_simple(), + ); +} + +/** + * Returns unsupported widget types for a context. + * + * @param array{is_wpcom_simple:bool} $context Widget support context. + * @return string[] Unsupported widget type names. + */ +function get_unsupported_widget_types( $context ) { + $unsupported = array(); + + // 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'] ) { + $unsupported[] = 'jpa/file-downloads'; + } + + 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. + * @return array Filtered and re-indexed widget records. + */ +function remove_unsupported_widget_items( $items, $type_key, $context ) { + $unsupported = get_unsupported_widget_types( $context ); + + if ( empty( $unsupported ) ) { + return $items; + } + + return array_values( + array_filter( + $items, + static function ( $item ) use ( $type_key, $unsupported ) { + return ! is_array( $item ) + || ! in_array( $item[ $type_key ] ?? '', $unsupported, true ); + } + ) + ); +} 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 a0b45e9c9b8e..71a7cb9f237f 100644 --- a/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php +++ b/projects/packages/premium-analytics/tests/php/Dashboard_Layout_Test.php @@ -7,6 +7,7 @@ namespace Automattic\Jetpack\PremiumAnalytics; +use Automattic\Jetpack\Constants; use PHPUnit\Framework\TestCase; use WP_REST_Server; @@ -21,11 +22,12 @@ class Dashboard_Layout_Test extends TestCase { const LEGACY_ROUTE = '/jetpack/v4/dashboards/(?P[a-z][a-z0-9-]*(?:_[a-z0-9-]+)*)/default-layout'; /** - * Reset REST globals after route registration tests. + * Reset REST globals and constants between tests. */ protected function tearDown(): void { global $wp_rest_server; $wp_rest_server = null; + Constants::clear_constants(); parent::tearDown(); } @@ -75,6 +77,28 @@ public function test_dashboard_name_resolves_traffic_default() { $this->assertNotContains( 'jpa/hello-world', $layout_types ); } + /** + * Default layouts pass through the availability policy: on self-hosted + * Jetpack sites (this test env), Simple-only widget instances are dropped. + */ + public function test_traffic_default_excludes_simple_only_widgets_on_self_hosted() { + $layout_types = array_column( get_dashboard_default_layout_for( DASHBOARD_TRAFFIC_SECTION_ID ), 'type' ); + + $this->assertNotContains( 'jpa/file-downloads', $layout_types, 'Simple-only widget instances must not be part of the default layout on self-hosted sites.' ); + $this->assertContains( 'jpa/clicks', $layout_types, 'Regular widget instances remain in the default layout.' ); + } + + /** + * WPCOM Simple keeps Simple-only widgets in the default layout. + */ + public function test_traffic_default_keeps_simple_only_widgets_on_wpcom_simple() { + Constants::set_constant( 'IS_WPCOM', true ); + + $layout_types = array_column( get_dashboard_default_layout_for( DASHBOARD_TRAFFIC_SECTION_ID ), 'type' ); + + $this->assertContains( 'jpa/file-downloads', $layout_types ); + } + /** * Traffic section aliases resolve to the same default layout. */ 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 326f02724871..30df334ddea2 100644 --- a/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php +++ b/projects/packages/premium-analytics/tests/php/Widget_Availability_Test.php @@ -7,6 +7,7 @@ namespace Automattic\Jetpack\PremiumAnalytics; +use Automattic\Jetpack\Constants; use PHPUnit\Framework\Attributes\CoversFunction; use WorDBless\BaseTestCase; @@ -16,12 +17,20 @@ /** * @covers ::Automattic\Jetpack\PremiumAnalytics\get_available_widget_types + * @covers ::Automattic\Jetpack\PremiumAnalytics\get_widget_support_context + * @covers ::Automattic\Jetpack\PremiumAnalytics\get_unsupported_widget_types + * @covers ::Automattic\Jetpack\PremiumAnalytics\remove_unsupported_widget_items + * @covers ::Automattic\Jetpack\PremiumAnalytics\filter_registrable_widget_types_by_availability * @covers ::Automattic\Jetpack\PremiumAnalytics\filter_registrable_widget_types_by_environment * @covers ::Automattic\Jetpack\PremiumAnalytics\remove_dev_only_widget_types * @covers ::Automattic\Jetpack\PremiumAnalytics\filter_registrable_widget_types_by_plugin * @covers ::Automattic\Jetpack\PremiumAnalytics\remove_plugin_gated_widget_types */ #[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\get_available_widget_types' )] +#[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\get_widget_support_context' )] +#[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\get_unsupported_widget_types' )] +#[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\remove_unsupported_widget_items' )] +#[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\filter_registrable_widget_types_by_availability' )] #[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\filter_registrable_widget_types_by_environment' )] #[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\remove_dev_only_widget_types' )] #[CoversFunction( 'Automattic\Jetpack\PremiumAnalytics\filter_registrable_widget_types_by_plugin' )] @@ -29,9 +38,10 @@ class Widget_Availability_Test extends BaseTestCase { /** - * Reset availability filters between tests. + * Reset constants and availability filters between tests. */ public function tear_down() { + Constants::clear_constants(); remove_all_filters( WOOCOMMERCE_DASHBOARD_SECTION_AVAILABLE_FILTER ); parent::tear_down(); @@ -48,6 +58,10 @@ private function widget_candidates() { 'name' => 'jpa/react-query-dev-tool', 'category' => 'developer', ), + array( + 'name' => 'jpa/file-downloads', + 'category' => 'traffic', + ), array( 'name' => 'jpa/hello-world', 'category' => 'demo', @@ -85,6 +99,84 @@ private function commerce_widget_candidates() { ); } + /** + * Filters the standard candidates with explicit host context. + * + * @param bool $is_wpcom_simple Whether the site is WPCOM Simple. + * @return string[] Remaining type names. + */ + private function available_names( $is_wpcom_simple ) { + return array_column( + remove_unsupported_widget_items( + $this->widget_candidates(), + 'name', + array( 'is_wpcom_simple' => $is_wpcom_simple ) + ), + 'name' + ); + } + + /** + * File downloads is unavailable outside WPCOM Simple. + */ + public function test_type_policy_removes_file_downloads_on_non_simple() { + $names = $this->available_names( false ); + + $this->assertNotContains( 'jpa/file-downloads', $names ); + $this->assertContains( 'jpa/hello-world', $names ); + } + + /** + * WPCOM Simple keeps File downloads. + */ + public function test_type_policy_keeps_file_downloads_on_simple() { + $this->assertContains( 'jpa/file-downloads', $this->available_names( true ) ); + } + + /** + * Non-array records pass through unchanged. + */ + public function test_type_policy_keeps_non_array_records() { + $record = (object) array( 'name' => 'jpa/file-downloads' ); + + $this->assertSame( + array( $record ), + remove_unsupported_widget_items( + array( + $record, + array( 'name' => 'jpa/file-downloads' ), + ), + 'name', + array( 'is_wpcom_simple' => false ) + ) + ); + } + + /** + * Records without the type key are not support-gated. + */ + public function test_type_policy_keeps_records_without_type_key() { + $items = array( array( 'uuid' => 'no-type' ) ); + + $this->assertSame( + $items, + remove_unsupported_widget_items( $items, 'type', array( 'is_wpcom_simple' => false ) ) + ); + } + + /** + * Filtered candidates are re-indexed so they stay a JSON list. + */ + public function test_type_policy_reindexes_filtered_records() { + $filtered = remove_unsupported_widget_items( + $this->widget_candidates(), + 'name', + array( 'is_wpcom_simple' => false ) + ); + + $this->assertSame( range( 0, count( $filtered ) - 1 ), array_keys( $filtered ), 'Filtered candidates must stay a JSON list.' ); + } + /** * In production, developer-only candidates are dropped; the rest pass through. */ @@ -166,6 +258,35 @@ public function test_uncategorized_widgets_pass_through() { ); } + /** + * The host callback removes File downloads on Atomic. + */ + public function test_registry_callback_removes_file_downloads_on_atomic() { + Constants::set_constant( 'ATOMIC_SITE_ID', 123 ); + Constants::set_constant( 'ATOMIC_CLIENT_ID', 456 ); + + $names = array_column( + filter_registrable_widget_types_by_availability( $this->widget_candidates() ), + 'name' + ); + + $this->assertNotContains( 'jpa/file-downloads', $names ); + } + + /** + * The host callback keeps File downloads on WPCOM Simple. + */ + public function test_registry_callback_keeps_file_downloads_on_wpcom_simple() { + Constants::set_constant( 'IS_WPCOM', true ); + + $names = array_column( + filter_registrable_widget_types_by_availability( $this->widget_candidates() ), + 'name' + ); + + $this->assertContains( 'jpa/file-downloads', $names ); + } + /** * The registry-time callback follows the store section's availability * signal, so forcing the section visible also surfaces its widgets. diff --git a/projects/packages/premium-analytics/widgets/file-downloads/render.tsx b/projects/packages/premium-analytics/widgets/file-downloads/render.tsx index 9d7d88f5b9b1..ca2a5e3a6623 100644 --- a/projects/packages/premium-analytics/widgets/file-downloads/render.tsx +++ b/projects/packages/premium-analytics/widgets/file-downloads/render.tsx @@ -41,93 +41,6 @@ type FileDownloadsRenderAttributes = FileDownloadsAttributes & type FileDownloadsWidgetProps = WidgetRenderProps< FileDownloadsRenderAttributes >; const DATA_FORMAT = { type: 'number' as const, options: { useMultipliers: true, decimals: 0 } }; -const FILE_DOWNLOADS_UNAVAILABLE_STATUS = 404; - -function toStatusNumber( value: unknown ): number | null { - if ( typeof value === 'number' ) { - return value; - } - - if ( typeof value === 'string' ) { - const status = Number.parseInt( value, 10 ); - return Number.isNaN( status ) ? null : status; - } - - return null; -} - -function getErrorStatus( error: unknown ): number | null { - if ( ! error || typeof error !== 'object' ) { - return null; - } - - const err = error as Record< string, unknown >; - - const status = toStatusNumber( err.status ); - if ( status !== null ) { - return status; - } - - if ( err.data && typeof err.data === 'object' ) { - const data = err.data as Record< string, unknown >; - const dataStatus = toStatusNumber( data.status ); - if ( dataStatus !== null ) { - return dataStatus; - } - } - - if ( err.response && typeof err.response === 'object' ) { - const response = err.response as Record< string, unknown >; - const responseStatus = toStatusNumber( response.status ); - if ( responseStatus !== null ) { - return responseStatus; - } - } - - return null; -} - -function getErrorText( error: unknown ): string { - if ( ! error || typeof error !== 'object' ) { - return ''; - } - - const err = error as Record< string, unknown >; - const candidates = [ - err.message, - err.error, - err.code, - err.data && typeof err.data === 'object' - ? ( err.data as Record< string, unknown > ).message - : undefined, - err.data && typeof err.data === 'object' - ? ( err.data as Record< string, unknown > ).error - : undefined, - err.response && typeof err.response === 'object' - ? ( err.response as Record< string, unknown > ).message - : undefined, - ]; - - return candidates - .filter( ( candidate ): candidate is string => typeof candidate === 'string' ) - .join( ' ' ); -} - -function getFileDownloadsErrorMessage( error: unknown ) { - const errorText = getErrorText( error ).toLowerCase(); - const isUnavailableMessage = - errorText.includes( 'file download' ) && - ( errorText.includes( 'not available' ) || errorText.includes( 'jetpack site' ) ); - - if ( getErrorStatus( error ) === FILE_DOWNLOADS_UNAVAILABLE_STATUS || isUnavailableMessage ) { - return __( - 'File download stats are not available for Jetpack sites.', - 'jetpack-premium-analytics' - ); - } - - return undefined; -} /** * A single normalized file-downloads row, ready for the leaderboard. @@ -264,11 +177,8 @@ type FileDownloadsInnerProps = { */ function FileDownloadsInner( { max }: FileDownloadsInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = + const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = useStatsFileDownloads( reportParams as StatsReportParams, { maxRows: max } ); - // File downloads has a known unsupported case (404 on Jetpack sites); Retry - // can't succeed there, so the action is dropped for that message. - const unavailableMessage = getFileDownloadsErrorMessage( error ); const rows = useMemo( () => toFileDownloadRows( comparisonRows?.rows ?? [] ), @@ -288,15 +198,11 @@ function FileDownloadsInner( { max }: FileDownloadsInnerProps ) { isError={ rows.length === 0 && isError } isEmpty={ rows.length === 0 } error={ { - description: - unavailableMessage ?? - __( - "We couldn't load file downloads. Please try again in a moment.", - 'jetpack-premium-analytics' - ), - actions: unavailableMessage - ? [] - : [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], + description: __( + "We couldn't load file downloads. Please try again in a moment.", + 'jetpack-premium-analytics' + ), + actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], } } empty={ { icon: download,