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