Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.97% covered (success)
94.97%
170 / 179
80.00% covered (warning)
80.00%
16 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
Analytics_Dashboard
94.97% covered (success)
94.97%
170 / 179
80.00% covered (warning)
80.00%
16 / 20
67.57
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 register_section
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 get_no_orders_notice
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 runs_without_connection
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 get_local_mode_notice
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
9
 describe_scheduled_import
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 get_default_layout
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_store_performance_bookings
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
6.10
 remove_unavailable_widget_types
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 register_widget_types
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
5.01
 add_error_reporting_origin
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 is_section_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_woocommerce_available
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 current_user_can_view_store_reports
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_bookings_plugin_active
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 supports_widget_contract
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 load_build
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 build_dir
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 section_slug_is_taken
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 dashboard_has_section_slug
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
8.74
1<?php
2/**
3 * The WooCommerce section of the Premium Analytics dashboard.
4 *
5 * @package automattic/jetpack-woocommerce-stats
6 */
7
8namespace Automattic\Jetpack\WooCommerceStats;
9
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\PremiumAnalytics\Dashboard_Section;
12use Automattic\Jetpack\PremiumAnalytics\Sync\Sync_Status_Tracker;
13use Automattic\Jetpack\WooCommerceStats\Report_Execution\Local_Data_Status;
14use Automattic\Jetpack\WooCommerceStats\Report_Execution\Provider_Setting;
15use function Automattic\Jetpack\PremiumAnalytics\get_dashboard_default_widget_instance;
16use function Automattic\Jetpack\PremiumAnalytics\register_dashboard_section;
17use function Automattic\Jetpack\PremiumAnalytics\register_widget_types_from_manifest;
18use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_NAME;
19use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_TILE_CARD;
20use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_TILE_LIST;
21
22/**
23 * Registers the WooCommerce section and the package's widget types.
24 *
25 * The plugin that bundles it calls `init()`; both register when the dashboard's registries hydrate,
26 * gated here on WooCommerce and on the reader's store reports capability.
27 *
28 * @since 0.1.0-alpha
29 */
30class Analytics_Dashboard {
31
32    const PACKAGE_VERSION = '0.5.0';
33
34    /**
35     * Namespaced section identifier. Its slug, `woocommerce`, keys the section's URL and stored layouts.
36     */
37    const SECTION_ID = 'woocommerce-analytics/woocommerce';
38
39    /**
40     * Widget type names the package builds, from `widgets/*\/widget.json`.
41     */
42    const STORE_PERFORMANCE_TYPE         = 'woocommerce-analytics/store-performance';
43    const NET_SALES_OVER_TIME_TYPE       = 'woocommerce-analytics/net-sales-over-time';
44    const TOTAL_SALES_OVER_TIME_TYPE     = 'woocommerce-analytics/total-sales-over-time';
45    const GROSS_SALES_OVER_TIME_TYPE     = 'woocommerce-analytics/gross-sales-over-time';
46    const ORDERS_OVER_TIME_TYPE          = 'woocommerce-analytics/orders-over-time';
47    const AVERAGE_ORDER_VALUE_TYPE       = 'woocommerce-analytics/average-order-value';
48    const AVERAGE_ITEMS_PER_ORDER_TYPE   = 'woocommerce-analytics/average-items-per-order';
49    const ITEMS_SOLD_TYPE                = 'woocommerce-analytics/items-sold';
50    const BOOKINGS_OVER_TIME_TYPE        = 'woocommerce-analytics/bookings-over-time';
51    const VISITORS_OVER_TIME_TYPE        = 'woocommerce-analytics/visitors-over-time';
52    const NEW_VS_RETURNING_CUSTOMER_TYPE = 'woocommerce-analytics/new-vs-returning-customer';
53    const PAYMENT_STATUS_TYPE            = 'woocommerce-analytics/payment-status';
54    const ORDERS_FULFILLMENT_TYPE        = 'woocommerce-analytics/orders-fulfillment';
55    const COUPON_USAGE_OVER_TIME_TYPE    = 'woocommerce-analytics/coupon-usage-over-time';
56    const BOOKINGS_BY_STATUS_TYPE        = 'woocommerce-analytics/bookings-by-status';
57    const SESSIONS_BY_DEVICE_TYPE        = 'woocommerce-analytics/sessions-by-device';
58
59    /**
60     * The columns family, with the bookings variants of the first two.
61     */
62    const REVENUE_BY_CUSTOMER_TYPE_TYPE          = 'woocommerce-analytics/revenue-by-customer-type';
63    const BOOKINGS_REVENUE_BY_CUSTOMER_TYPE_TYPE = 'woocommerce-analytics/bookings-revenue-by-customer-type';
64    const SALES_BY_DEVICE_TYPE                   = 'woocommerce-analytics/sales-by-device';
65    const BOOKINGS_BY_DEVICE_TYPE                = 'woocommerce-analytics/bookings-by-device';
66    const TOTAL_RETURNS_TYPE                     = 'woocommerce-analytics/total-returns';
67    const SALES_BY_COUPON_TYPE                   = 'woocommerce-analytics/sales-by-coupon';
68    const TOP_PERFORMING_PRODUCTS_TYPE           = 'woocommerce-analytics/top-performing-products';
69    const TOP_PERFORMING_BOOKINGS_TYPE           = 'woocommerce-analytics/top-performing-bookings';
70    const SALES_BY_UTM_SOURCE_TYPE               = 'woocommerce-analytics/sales-by-utm-source';
71    const SALES_BY_UTM_CHANNEL_TYPE              = 'woocommerce-analytics/sales-by-utm-channel';
72    const SALES_BY_UTM_CAMPAIGN_TYPE             = 'woocommerce-analytics/sales-by-utm-campaign';
73    const VISITORS_BY_LOCATION_TYPE              = 'woocommerce-analytics/visitors-by-location';
74
75    /**
76     * The conversion funnel, for every product and for bookings.
77     */
78    const CONVERSION_RATE_TYPE                = 'woocommerce-analytics/conversion-rate';
79    const STORE_CONVERSION_RATE_BOOKINGS_TYPE = 'woocommerce-analytics/store-conversion-rate-bookings';
80
81    /**
82     * Registry actions of the dashboard package.
83     */
84    const REGISTER_SECTIONS_ACTION     = 'jetpack_premium_analytics_register_dashboard_sections';
85    const REGISTER_WIDGET_TYPES_ACTION = 'jetpack_premium_analytics_register_widget_types';
86
87    /**
88     * Text domain of the widget metadata and of the built widget bundles.
89     */
90    const TEXTDOMAIN = 'jetpack-woocommerce-stats-pkg';
91
92    /**
93     * Lowest widget contract the build works against: 2.4.0, the first to export `useOpenChartBucket`.
94     */
95    const MIN_WIDGET_API_VERSION = '2.4.0';
96
97    /**
98     * Widget categories the package builds but holds back from the tab for now: the bookings
99     * reports answer 500 on a store without a synced booking (WOOA7S-2287).
100     */
101    const HELD_BACK_WIDGET_CATEGORIES = array( 'bookings' );
102
103    /**
104     * Ahead of Traffic (10), so a store's dashboard opens on this tab.
105     */
106    const SECTION_ORDER = 5;
107
108    /**
109     * Widget types the tab offers in the inserter on top of its default layout: the over-time
110     * charts a store owner may prefer over Store performance.
111     */
112    const INSERTABLE_WIDGET_TYPES = array(
113        self::NET_SALES_OVER_TIME_TYPE,
114        self::TOTAL_SALES_OVER_TIME_TYPE,
115        self::GROSS_SALES_OVER_TIME_TYPE,
116        self::ORDERS_OVER_TIME_TYPE,
117        self::VISITORS_OVER_TIME_TYPE,
118    );
119
120    /**
121     * Filter through which WooCommerce detection is resolved, for hosts and tests without the plugin.
122     */
123    const WOOCOMMERCE_AVAILABLE_FILTER = 'jetpack_woocommerce_stats_woocommerce_available';
124
125    /**
126     * Widget categories that also need the WooCommerce Bookings extension.
127     */
128    const BOOKINGS_WIDGET_CATEGORIES = array( 'bookings' );
129
130    /**
131     * The module that offers the Bookings metric to Store performance.
132     */
133    const STORE_PERFORMANCE_BOOKINGS_MODULE = '@jetpack-woocommerce-stats/store-performance-bookings';
134
135    /**
136     * Action the dashboard page fires as it enqueues its scripts: its menu slug,
137     * `Analytics::MENU_PAGE_SLUG`, under wp-build's `_init` suffix.
138     */
139    const DASHBOARD_PAGE_INIT_ACTION = 'jetpack-premium-analytics-wp-admin_init';
140
141    /**
142     * Register the sync opt-in and the store tracking bootstrap, then hook the section and widget-type registrants on the dashboard's registry
143     * actions, the Bookings metric on the dashboard page, the reports proxy on REST requests and its cache reset on the end of the
144     * initial sync, and the store currency on the script data.
145     *
146     * Priority 20, after the dashboard package's own registrants: an older package that still
147     * registers the section itself is found by slug and left alone.
148     *
149     * Call it before plugins_loaded completes, for the sync opt-in ({@see Sync_Configuration::register()}).
150     *
151     * @return void
152     */
153    public static function init() {
154        Sync_Configuration::register();
155        WooCommerce_Analytics_Tracker::configure();
156
157        add_action( self::REGISTER_SECTIONS_ACTION, array( __CLASS__, 'register_section' ), 20 );
158        add_action( self::REGISTER_WIDGET_TYPES_ACTION, array( __CLASS__, 'register_widget_types' ), 20 );
159        add_action( self::DASHBOARD_PAGE_INIT_ACTION, array( __CLASS__, 'enqueue_store_performance_bookings' ) );
160
161        add_action( 'rest_api_init', array( Api_Proxy_Controller::class, 'init' ) );
162        add_action( Report_Execution\Report_Registry::REGISTER_ACTION, array( Report_Execution\Default_Reports::class, 'register' ) );
163        add_filter( 'jetpack_stats_transient_cleanup_prefixes', array( Api_Proxy_Controller::class, 'register_transient_cleanup_prefix' ) );
164        add_action( Sync_Status_Tracker::MILESTONE_ACTION, array( Api_Proxy_Controller::class, 'clear_cache' ) );
165
166        Store_Currency::init();
167    }
168
169    /**
170     * Register the WooCommerce section unless `woocommerce` or the older `store` slug is taken.
171     *
172     * @param object $registry The section registry being hydrated.
173     * @return void
174     */
175    public static function register_section( $registry ) {
176        if ( self::section_slug_is_taken( $registry ) ) {
177            return;
178        }
179
180        // A dashboard that predates the arg still sends a disconnected site to `/connect`.
181        $runs_without_connection = property_exists( Dashboard_Section::class, 'requires_connection' ) && self::runs_without_connection();
182
183        register_dashboard_section(
184            DASHBOARD_NAME,
185            self::SECTION_ID,
186            array(
187                'label'                   => __( 'WooCommerce', 'jetpack-woocommerce-stats-pkg' ),
188                'order'                   => self::SECTION_ORDER,
189                'is_available'            => array( __CLASS__, 'is_section_available' ),
190                // Nothing backfills historical orders to WordPress.com but the analytics full sync.
191                'requires_sync'           => true,
192                'requires_connection'     => ! $runs_without_connection,
193                'notice'                  => $runs_without_connection
194                    ? static function () {
195                        return self::get_local_mode_notice();
196                    }
197                    : array( __CLASS__, 'get_no_orders_notice' ),
198                'default_layout'          => array( __CLASS__, 'get_default_layout' ),
199                'insertable_widget_types' => self::INSERTABLE_WIDGET_TYPES,
200            )
201        );
202    }
203
204    /**
205     * The message above the tab while the store has never had an order.
206     *
207     * @return string|null The message, or null once the store has an order or without WooCommerce.
208     */
209    public static function get_no_orders_notice() {
210        if ( ! function_exists( 'wc_get_orders' ) ) {
211            return null;
212        }
213
214        // The registered statuses, so an abandoned checkout draft is not mistaken for a first order.
215        $orders = wc_get_orders(
216            array(
217                'type'   => 'shop_order',
218                'status' => array_keys( wc_get_order_statuses() ),
219                'limit'  => 1,
220                'return' => 'ids',
221            )
222        );
223
224        if ( ! empty( $orders ) ) {
225            return null;
226        }
227
228        return __( 'Your store has no orders yet. Your sales, orders and customers will show here after your first order.', 'jetpack-woocommerce-stats-pkg' );
229    }
230
231    /**
232     * Whether the tab opens on this disconnected site because its provider setting puts `local`
233     * ahead of `wpcom`. Behind it, `local` serves nothing: `wpcom` covers every report.
234     *
235     * @phan-suppress PhanAccessMethodInternal, PhanAccessClassConstantInternal -- Internal to this package, not to its sub-namespace.
236     *
237     * @return bool
238     */
239    private static function runs_without_connection() {
240        if ( ( new Connection_Manager() )->is_connected() || ! self::is_woocommerce_available() ) {
241            return false;
242        }
243
244        $providers = Provider_Setting::get_providers();
245        $local     = array_search( 'local', $providers, true );
246        $wpcom     = array_search( Provider_Setting::DEFAULT_PROVIDER, $providers, true );
247
248        return false !== $local && ( false === $wpcom || $local < $wpcom );
249    }
250
251    /**
252     * The message above the tab of a disconnected store set to local: what its own data lacks, then
253     * what the missing connection holds back. A store without orders gets that message between them.
254     *
255     * @phan-suppress PhanAccessMethodInternal -- Internal to this package, not to its sub-namespace.
256     *
257     * @return string
258     */
259    private static function get_local_mode_notice() {
260        $data_status = new Local_Data_Status();
261        $messages    = array();
262
263        if ( ! $data_status->is_analytics_enabled() ) {
264            $messages[] = __( 'WooCommerce Analytics is off, so this tab can’t read your store’s orders. Turn it on in WooCommerce › Settings › Advanced › Features.', 'jetpack-woocommerce-stats-pkg' );
265        } else {
266            $import = $data_status->get_import_status();
267            if ( $import && $import['failed_overflow_count'] > 0 ) {
268                // Retry reaches only the failures core stored; those past its cap need a full import.
269                $messages[] = sprintf(
270                    /* translators: %d: Number of orders. */
271                    _n(
272                        'WooCommerce Analytics couldn’t import more than %d order. To import them all, run Import historical data in WooCommerce › Analytics › Settings with “Skip previously imported customers and orders” checked.',
273                        'WooCommerce Analytics couldn’t import more than %d orders. To import them all, run Import historical data in WooCommerce › Analytics › Settings with “Skip previously imported customers and orders” checked.',
274                        $import['failed_count'],
275                        'jetpack-woocommerce-stats-pkg'
276                    ),
277                    $import['failed_count']
278                );
279            } elseif ( $import && $import['failed_count'] > 0 ) {
280                $messages[] = sprintf(
281                    /* translators: %d: Number of orders. */
282                    _n(
283                        'WooCommerce Analytics couldn’t import %d order. Retry it in WooCommerce › Analytics › Settings › Import historical data.',
284                        'WooCommerce Analytics couldn’t import %d orders. Retry them in WooCommerce › Analytics › Settings › Import historical data.',
285                        $import['failed_count'],
286                        'jetpack-woocommerce-stats-pkg'
287                    ),
288                    $import['failed_count']
289                );
290            }
291            if ( $import && 'scheduled' === $import['mode'] ) {
292                $messages[] = self::describe_scheduled_import( $import['last_processed_date'], $import['next_scheduled'] );
293            }
294        }
295
296        $no_orders = self::get_no_orders_notice();
297        if ( null !== $no_orders ) {
298            $messages[] = $no_orders;
299        }
300
301        $messages[] = __( 'Some reports need a Jetpack connection, so they can’t load yet.', 'jetpack-woocommerce-stats-pkg' );
302
303        return implode( ' ', $messages );
304    }
305
306    /**
307     * When a scheduled WooCommerce Analytics import last ran and runs next, as its Data status says.
308     *
309     * @param string|null $last The last update, in store time; null before the first.
310     * @param string|null $next The next update, in store time; null when none is scheduled.
311     * @return string
312     */
313    private static function describe_scheduled_import( $last, $next ) {
314        $format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
315        $parts  = array(
316            $last
317                /* translators: %s: Date and time. */
318                ? sprintf( __( 'Your store’s data was last updated on %s.', 'jetpack-woocommerce-stats-pkg' ), mysql2date( $format, $last ) )
319                : __( 'Your store’s data hasn’t been updated yet.', 'jetpack-woocommerce-stats-pkg' ),
320        );
321        if ( $next ) {
322            /* translators: %s: Date and time. */
323            $parts[] = sprintf( __( 'The next update runs on %s.', 'jetpack-woocommerce-stats-pkg' ), mysql2date( $format, $next ) );
324        }
325        $parts[] = __( 'To update it now, go to WooCommerce › Analytics › Settings.', 'jetpack-woocommerce-stats-pkg' );
326
327        return implode( ' ', $parts );
328    }
329
330    /**
331     * The default layout of the WooCommerce tab; the inserter offers its types plus
332     * `INSERTABLE_WIDGET_TYPES`.
333     *
334     * Each group below fills one row of the dashboard grid.
335     *
336     * @return array[] Widget instances, as `get_dashboard_default_widget_instance()` builds them.
337     */
338    public static function get_default_layout() {
339        return array(
340            get_dashboard_default_widget_instance( 'default-store-performance-widget-instance', self::STORE_PERFORMANCE_TYPE, 0, 'full', DASHBOARD_TILE_CARD ),
341
342            get_dashboard_default_widget_instance( 'default-top-performing-products-widget-instance', self::TOP_PERFORMING_PRODUCTS_TYPE, 10, 1, DASHBOARD_TILE_LIST ),
343            get_dashboard_default_widget_instance( 'default-items-sold-widget-instance', self::ITEMS_SOLD_TYPE, 15, 1, DASHBOARD_TILE_CARD ),
344            get_dashboard_default_widget_instance( 'default-average-order-value-widget-instance', self::AVERAGE_ORDER_VALUE_TYPE, 20, 1, DASHBOARD_TILE_CARD ),
345            get_dashboard_default_widget_instance( 'default-average-items-per-order-widget-instance', self::AVERAGE_ITEMS_PER_ORDER_TYPE, 30, 1, DASHBOARD_TILE_CARD ),
346
347            get_dashboard_default_widget_instance( 'default-conversion-rate-widget-instance', self::CONVERSION_RATE_TYPE, 40, 1, DASHBOARD_TILE_CARD ),
348            get_dashboard_default_widget_instance( 'default-visitors-by-location-widget-instance', self::VISITORS_BY_LOCATION_TYPE, 50, 2, DASHBOARD_TILE_LIST ),
349
350            get_dashboard_default_widget_instance( 'default-new-vs-returning-customer-widget-instance', self::NEW_VS_RETURNING_CUSTOMER_TYPE, 60, 1, DASHBOARD_TILE_CARD ),
351            get_dashboard_default_widget_instance( 'default-revenue-by-customer-type-widget-instance', self::REVENUE_BY_CUSTOMER_TYPE_TYPE, 70, 1, DASHBOARD_TILE_CARD ),
352            get_dashboard_default_widget_instance( 'default-total-returns-widget-instance', self::TOTAL_RETURNS_TYPE, 80, 1, DASHBOARD_TILE_CARD ),
353
354            get_dashboard_default_widget_instance( 'default-sales-by-utm-channel-widget-instance', self::SALES_BY_UTM_CHANNEL_TYPE, 90, 1, DASHBOARD_TILE_LIST ),
355            get_dashboard_default_widget_instance( 'default-sales-by-utm-source-widget-instance', self::SALES_BY_UTM_SOURCE_TYPE, 100, 1, DASHBOARD_TILE_LIST ),
356            get_dashboard_default_widget_instance( 'default-sales-by-utm-campaign-widget-instance', self::SALES_BY_UTM_CAMPAIGN_TYPE, 110, 1, DASHBOARD_TILE_LIST ),
357
358            get_dashboard_default_widget_instance( 'default-orders-fulfillment-widget-instance', self::ORDERS_FULFILLMENT_TYPE, 120, 1, DASHBOARD_TILE_CARD ),
359            get_dashboard_default_widget_instance( 'default-sales-by-coupon-widget-instance', self::SALES_BY_COUPON_TYPE, 130, 1, DASHBOARD_TILE_LIST ),
360            get_dashboard_default_widget_instance( 'default-coupon-usage-over-time-widget-instance', self::COUPON_USAGE_OVER_TIME_TYPE, 140, 1, DASHBOARD_TILE_CARD ),
361
362            get_dashboard_default_widget_instance( 'default-payment-status-widget-instance', self::PAYMENT_STATUS_TYPE, 150, 1, DASHBOARD_TILE_CARD ),
363            get_dashboard_default_widget_instance( 'default-sessions-by-device-widget-instance', self::SESSIONS_BY_DEVICE_TYPE, 160, 1, DASHBOARD_TILE_CARD ),
364            get_dashboard_default_widget_instance( 'default-sales-by-device-widget-instance', self::SALES_BY_DEVICE_TYPE, 170, 1, DASHBOARD_TILE_CARD ),
365        );
366    }
367
368    /**
369     * Load the Bookings metric with the dashboard on a store running the Bookings extension.
370     *
371     * Enqueued as a module of its own: the page's boot runs only the init modules its build names,
372     * and a boot dependency is preloaded, not run. The build's own registrant hooks
373     * `wp_default_scripts`, already fired on this page hook, so it runs here.
374     *
375     * @return void
376     */
377    public static function enqueue_store_performance_bookings() {
378        if ( ! self::is_bookings_plugin_active() || ! self::supports_widget_contract() || ! self::is_woocommerce_available() || ! self::current_user_can_view_store_reports() ) {
379            return;
380        }
381
382        self::load_build();
383        if ( ! function_exists( 'jetpack_woocommerce_stats_register_script_modules' ) ) {
384            return;
385        }
386        jetpack_woocommerce_stats_register_script_modules();
387
388        wp_enqueue_script_module( self::STORE_PERFORMANCE_BOOKINGS_MODULE );
389    }
390
391    /**
392     * The manifest minus the categories held back from the tab and the bookings categories
393     * without their extension.
394     *
395     * @param array[] $widget_modules     Widget module records of the build manifest.
396     * @param bool    $bookings_available Whether the WooCommerce Bookings extension is active.
397     * @return array[] The records the package registers.
398     */
399    private static function remove_unavailable_widget_types( $widget_modules, $bookings_available ) {
400        return array_values(
401            array_filter(
402                $widget_modules,
403                static function ( $widget_module ) use ( $bookings_available ) {
404                    $category = $widget_module['category'] ?? '';
405
406                    if ( in_array( $category, self::HELD_BACK_WIDGET_CATEGORIES, true ) ) {
407                        return false;
408                    }
409
410                    return $bookings_available || ! in_array( $category, self::BOOKINGS_WIDGET_CATEGORIES, true );
411                }
412            )
413        );
414    }
415
416    /**
417     * Register the widget types from the package's build manifest.
418     *
419     * Loads the generated build first: after `init` it registers the widget script modules on the
420     * spot, so they reach the page import map the same request.
421     *
422     * Registers nothing without WooCommerce or for a reader who cannot see store reports: the types
423     * would only collect 403s from the proxy.
424     *
425     * @param object $registry The widget type registry being hydrated.
426     * @return void
427     */
428    public static function register_widget_types( $registry ) {
429        add_filter( 'jetpack_premium_analytics_error_reporting_script_origins', array( __CLASS__, 'add_error_reporting_origin' ) );
430
431        if ( ! self::supports_widget_contract() || ! self::is_woocommerce_available() || ! self::current_user_can_view_store_reports() ) {
432            return;
433        }
434
435        self::load_build();
436        if ( ! function_exists( 'jetpack_woocommerce_stats_get_registered_widget_modules' ) ) {
437            return;
438        }
439
440        register_widget_types_from_manifest(
441            self::remove_unavailable_widget_types( jetpack_woocommerce_stats_get_registered_widget_modules(), self::is_bookings_plugin_active() ),
442            array(
443                'textdomain'    => self::TEXTDOMAIN,
444                'i18n_manifest' => add_query_arg( 'ver', self::PACKAGE_VERSION, plugins_url( 'i18n-manifest.json', self::build_dir() . '/build.php' ) ),
445            ),
446            $registry
447        );
448    }
449
450    /**
451     * Append this package's dashboard build directories to the error reporting origins.
452     *
453     * The widget and module directories rather than the whole build, which also carries script that
454     * never runs on the dashboard. Every widget and module builds into one of these two, so a new
455     * one needs no change here.
456     *
457     * @param string[] $origins Absolute URL prefixes, each ending in a slash.
458     * @return string[]
459     */
460    public static function add_error_reporting_origin( $origins ) {
461        $origins = is_array( $origins ) ? $origins : array();
462        $build   = trailingslashit( plugins_url( '', self::build_dir() . '/build.php' ) );
463
464        $origins[] = $build . 'widgets/';
465        $origins[] = $build . 'modules/';
466
467        return $origins;
468    }
469
470    /**
471     * Whether the WooCommerce tab is available: WooCommerce is active and the reader may see store
472     * reports.
473     *
474     * @return bool
475     */
476    public static function is_section_available() {
477        return self::is_woocommerce_available() && self::current_user_can_view_store_reports();
478    }
479
480    /**
481     * Whether WooCommerce is active.
482     *
483     * @return bool
484     */
485    public static function is_woocommerce_available() {
486        $is_available = class_exists( 'WooCommerce' ) || function_exists( 'WC' );
487
488        /**
489         * Filters whether WooCommerce was detected.
490         *
491         * @since 0.2.0
492         *
493         * @param bool $is_available Whether WooCommerce was detected in the current request.
494         */
495        return (bool) apply_filters( self::WOOCOMMERCE_AVAILABLE_FILTER, $is_available );
496    }
497
498    /**
499     * Whether the current user may read the store reports, the rule the reports proxy enforces.
500     *
501     * @return bool
502     */
503    public static function current_user_can_view_store_reports() {
504        // phpcs:ignore WordPress.WP.Capabilities.Unknown -- WooCommerce registers this capability.
505        return current_user_can( 'manage_options' ) || current_user_can( 'view_woocommerce_reports' );
506    }
507
508    /**
509     * Whether the WooCommerce Bookings extension is active; `is_plugin_active()` only exists in
510     * admin contexts, hence the guard.
511     *
512     * @return bool
513     */
514    private static function is_bookings_plugin_active() {
515        return class_exists( 'WC_Bookings' )
516            || ( function_exists( 'is_plugin_active' ) && \is_plugin_active( 'woocommerce-bookings/woocommerce-bookings.php' ) );
517    }
518
519    /**
520     * Whether the dashboard's widget contract is one the widgets were built against.
521     *
522     * On an older contract the SDK module lacks a name the widgets import, and they fail to load.
523     *
524     * @return bool
525     */
526    private static function supports_widget_contract() {
527        // The dashboard loads the file naming its contract when its widget registry is first read,
528        // which has not happened yet when the dashboard page enqueues its scripts.
529        if (
530            ! defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' )
531            && function_exists( 'Automattic\\Jetpack\\PremiumAnalytics\\ensure_widget_registry_ready' )
532        ) {
533            \Automattic\Jetpack\PremiumAnalytics\ensure_widget_registry_ready();
534        }
535
536        if ( ! defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ) {
537            return false;
538        }
539
540        $version = \Automattic\Jetpack\PremiumAnalytics\WIDGET_API_VERSION;
541
542        return version_compare( $version, self::MIN_WIDGET_API_VERSION, '>=' ) && version_compare( $version, '3', '<' );
543    }
544
545    /**
546     * Load the generated build once. Guarded by symbol, not by path: two copies of the package
547     * can share a request.
548     *
549     * @return void
550     */
551    private static function load_build() {
552        if ( function_exists( 'jetpack_woocommerce_stats_get_registered_widget_modules' ) ) {
553            return;
554        }
555        $loader = self::build_dir() . '/build.php';
556        if ( file_exists( $loader ) ) {
557            require_once $loader;
558        }
559    }
560
561    /**
562     * Directory of the wp-build output.
563     *
564     * @return string
565     */
566    private static function build_dir() {
567        return dirname( __DIR__ ) . '/build';
568    }
569
570    /**
571     * Whether this tab's slug, or the `store` slug an older package still registers, is taken.
572     *
573     * @param object $registry The section registry being hydrated.
574     * @return bool
575     */
576    private static function section_slug_is_taken( $registry ) {
577        foreach ( array( 'woocommerce', 'store' ) as $slug ) {
578            if ( self::dashboard_has_section_slug( $registry, DASHBOARD_NAME, $slug ) ) {
579                return true;
580            }
581        }
582
583        return false;
584    }
585
586    /**
587     * Whether a section with the slug is registered on the dashboard.
588     *
589     * Reads the registry through the slug lookup when the package offers it, and through the full
590     * list otherwise: the package and this one ship on different cadences.
591     *
592     * @param object $registry       The registry being hydrated.
593     * @param string $dashboard_name Dashboard identifier.
594     * @param string $slug           Section slug.
595     * @return bool
596     */
597    private static function dashboard_has_section_slug( $registry, $dashboard_name, $slug ) {
598        if ( method_exists( $registry, 'get_registered_by_slug' ) ) {
599            return null !== $registry->get_registered_by_slug( $dashboard_name, $slug );
600        }
601
602        foreach ( $registry->get_all_registered( $dashboard_name ) as $section ) {
603            if ( $section->slug === $slug ) {
604                return true;
605            }
606        }
607
608        return false;
609    }
610}