Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.75% covered (success)
91.75%
89 / 97
80.00% covered (warning)
80.00%
12 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Analytics_Dashboard
91.75% covered (success)
91.75%
89 / 97
80.00% covered (warning)
80.00%
12 / 15
39.85
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 register_section
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 get_default_layout
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
1
 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.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
5.01
 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_store_section_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 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%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 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\PremiumAnalytics\Enablement_Setting;
11use function Automattic\Jetpack\PremiumAnalytics\get_dashboard_default_widget_instance;
12use function Automattic\Jetpack\PremiumAnalytics\register_dashboard_section;
13use function Automattic\Jetpack\PremiumAnalytics\register_widget_types_from_manifest;
14use const Automattic\Jetpack\PremiumAnalytics\DASHBOARD_NAME;
15
16/**
17 * Registers the WooCommerce section and the package's widget types.
18 *
19 * The plugin that bundles it calls `init()`; both register when the dashboard's registries hydrate,
20 * gated here on WooCommerce and on the reader's store reports capability.
21 *
22 * @since 0.1.0-alpha
23 */
24class Analytics_Dashboard {
25
26    const PACKAGE_VERSION = '0.1.0';
27
28    /**
29     * Namespaced section identifier. Its slug, `woocommerce`, keys the section's URL and stored layouts.
30     */
31    const SECTION_ID = 'woocommerce-analytics/woocommerce';
32
33    /**
34     * Widget type names the package builds, from `widgets/*\/widget.json`.
35     */
36    const STORE_PERFORMANCE_TYPE         = 'woocommerce-analytics/store-performance';
37    const NET_SALES_OVER_TIME_TYPE       = 'woocommerce-analytics/net-sales-over-time';
38    const TOTAL_SALES_OVER_TIME_TYPE     = 'woocommerce-analytics/total-sales-over-time';
39    const GROSS_SALES_OVER_TIME_TYPE     = 'woocommerce-analytics/gross-sales-over-time';
40    const ORDERS_OVER_TIME_TYPE          = 'woocommerce-analytics/orders-over-time';
41    const AVERAGE_ORDER_VALUE_TYPE       = 'woocommerce-analytics/average-order-value';
42    const AVERAGE_ITEMS_PER_ORDER_TYPE   = 'woocommerce-analytics/average-items-per-order';
43    const BOOKINGS_OVER_TIME_TYPE        = 'woocommerce-analytics/bookings-over-time';
44    const VISITORS_OVER_TIME_TYPE        = 'woocommerce-analytics/visitors-over-time';
45    const NEW_VS_RETURNING_CUSTOMER_TYPE = 'woocommerce-analytics/new-vs-returning-customer';
46    const PAYMENT_STATUS_TYPE            = 'woocommerce-analytics/payment-status';
47    const ORDERS_FULFILLMENT_TYPE        = 'woocommerce-analytics/orders-fulfillment';
48    const COUPON_USAGE_OVER_TIME_TYPE    = 'woocommerce-analytics/coupon-usage-over-time';
49    const BOOKINGS_BY_STATUS_TYPE        = 'woocommerce-analytics/bookings-by-status';
50    const SESSIONS_BY_DEVICE_TYPE        = 'woocommerce-analytics/sessions-by-device';
51
52    /**
53     * The columns family, with the bookings variants of the first two.
54     */
55    const REVENUE_BY_CUSTOMER_TYPE_TYPE          = 'woocommerce-analytics/revenue-by-customer-type';
56    const BOOKINGS_REVENUE_BY_CUSTOMER_TYPE_TYPE = 'woocommerce-analytics/bookings-revenue-by-customer-type';
57    const SALES_BY_DEVICE_TYPE                   = 'woocommerce-analytics/sales-by-device';
58    const BOOKINGS_BY_DEVICE_TYPE                = 'woocommerce-analytics/bookings-by-device';
59    const TOTAL_RETURNS_TYPE                     = 'woocommerce-analytics/total-returns';
60    const SALES_BY_COUPON_TYPE                   = 'woocommerce-analytics/sales-by-coupon';
61    const TOP_PERFORMING_PRODUCTS_TYPE           = 'woocommerce-analytics/top-performing-products';
62    const TOP_PERFORMING_BOOKINGS_TYPE           = 'woocommerce-analytics/top-performing-bookings';
63    const SALES_BY_UTM_SOURCE_TYPE               = 'woocommerce-analytics/sales-by-utm-source';
64    const SALES_BY_UTM_CHANNEL_TYPE              = 'woocommerce-analytics/sales-by-utm-channel';
65    const SALES_BY_UTM_CAMPAIGN_TYPE             = 'woocommerce-analytics/sales-by-utm-campaign';
66    const VISITORS_BY_LOCATION_TYPE              = 'woocommerce-analytics/visitors-by-location';
67
68    /**
69     * The conversion funnel, for every product and for bookings.
70     */
71    const CONVERSION_RATE_TYPE                = 'woocommerce-analytics/conversion-rate';
72    const STORE_CONVERSION_RATE_BOOKINGS_TYPE = 'woocommerce-analytics/store-conversion-rate-bookings';
73
74    /**
75     * Registry actions of the dashboard package.
76     */
77    const REGISTER_SECTIONS_ACTION     = 'jetpack_premium_analytics_register_dashboard_sections';
78    const REGISTER_WIDGET_TYPES_ACTION = 'jetpack_premium_analytics_register_widget_types';
79
80    /**
81     * Text domain of the widget metadata and of the built widget bundles.
82     */
83    const TEXTDOMAIN = 'jetpack-woocommerce-stats-pkg';
84
85    /**
86     * Lowest widget contract the build works against: Visitors by location draws `Locations`,
87     * which the dashboard ships from 1.11.0.
88     */
89    const MIN_WIDGET_API_VERSION = '1.11.0';
90
91    /**
92     * Widget categories the package builds but holds back from the tab for now: the bookings
93     * reports answer 500 on a store without a synced booking (WOOA7S-2287).
94     */
95    const HELD_BACK_WIDGET_CATEGORIES = array( 'bookings' );
96
97    /**
98     * Ahead of Traffic (10), so a store's dashboard opens on this tab.
99     */
100    const SECTION_ORDER = 5;
101
102    /**
103     * Filter through which WooCommerce detection is resolved, for hosts and tests without the plugin.
104     */
105    const WOOCOMMERCE_AVAILABLE_FILTER = 'jetpack_woocommerce_stats_woocommerce_available';
106
107    /**
108     * Widget categories that also need the WooCommerce Bookings extension.
109     */
110    const BOOKINGS_WIDGET_CATEGORIES = array( 'bookings' );
111
112    /**
113     * Hook both registrants on the dashboard's registry actions, the reports proxy on REST
114     * requests, and the store currency on the script data.
115     *
116     * Priority 20, after the dashboard package's own registrants: an older package that still
117     * registers the section itself is found by slug and left alone.
118     *
119     * @return void
120     */
121    public static function init() {
122        add_action( self::REGISTER_SECTIONS_ACTION, array( __CLASS__, 'register_section' ), 20 );
123        add_action( self::REGISTER_WIDGET_TYPES_ACTION, array( __CLASS__, 'register_widget_types' ), 20 );
124
125        add_action( 'rest_api_init', array( Api_Proxy_Controller::class, 'init' ) );
126        add_filter( 'jetpack_stats_transient_cleanup_prefixes', array( Api_Proxy_Controller::class, 'register_transient_cleanup_prefix' ) );
127
128        Store_Currency::init();
129    }
130
131    /**
132     * Register the WooCommerce section unless `woocommerce` or the older `store` slug is taken.
133     *
134     * @param object $registry The section registry being hydrated.
135     * @return void
136     */
137    public static function register_section( $registry ) {
138        if ( self::section_slug_is_taken( $registry ) ) {
139            return;
140        }
141
142        register_dashboard_section(
143            DASHBOARD_NAME,
144            self::SECTION_ID,
145            array(
146                'label'          => __( 'WooCommerce', 'jetpack-woocommerce-stats-pkg' ),
147                'order'          => self::SECTION_ORDER,
148                'is_available'   => array( __CLASS__, 'is_section_available' ),
149                // Nothing backfills historical orders to WordPress.com but the analytics full sync.
150                'requires_sync'  => true,
151                'default_layout' => array( __CLASS__, 'get_default_layout' ),
152            )
153        );
154    }
155
156    /**
157     * The default layout of the WooCommerce tab, which is also what the inserter offers there.
158     *
159     * A new composition, built up as the widgets land in the package.
160     *
161     * @return array[] Widget instances, as `get_dashboard_default_widget_instance()` builds them.
162     */
163    public static function get_default_layout() {
164        return array(
165            get_dashboard_default_widget_instance( 'default-store-performance-widget-instance', self::STORE_PERFORMANCE_TYPE, 0, 'full', 2 ),
166            get_dashboard_default_widget_instance( 'default-visitors-by-location-widget-instance', self::VISITORS_BY_LOCATION_TYPE, 10, 2, 2 ),
167            get_dashboard_default_widget_instance( 'default-net-sales-over-time-widget-instance', self::NET_SALES_OVER_TIME_TYPE, 20, 1, 2 ),
168            get_dashboard_default_widget_instance( 'default-total-sales-over-time-widget-instance', self::TOTAL_SALES_OVER_TIME_TYPE, 30, 1, 2 ),
169            get_dashboard_default_widget_instance( 'default-gross-sales-over-time-widget-instance', self::GROSS_SALES_OVER_TIME_TYPE, 40, 1, 2 ),
170            get_dashboard_default_widget_instance( 'default-orders-over-time-widget-instance', self::ORDERS_OVER_TIME_TYPE, 50, 1, 2 ),
171            get_dashboard_default_widget_instance( 'default-average-order-value-widget-instance', self::AVERAGE_ORDER_VALUE_TYPE, 60, 1, 2 ),
172            get_dashboard_default_widget_instance( 'default-average-items-per-order-widget-instance', self::AVERAGE_ITEMS_PER_ORDER_TYPE, 70, 1, 2 ),
173            get_dashboard_default_widget_instance( 'default-visitors-over-time-widget-instance', self::VISITORS_OVER_TIME_TYPE, 80, 1, 2 ),
174            get_dashboard_default_widget_instance( 'default-conversion-rate-widget-instance', self::CONVERSION_RATE_TYPE, 90, 1, 2 ),
175            get_dashboard_default_widget_instance( 'default-new-vs-returning-customer-widget-instance', self::NEW_VS_RETURNING_CUSTOMER_TYPE, 100, 1, 2 ),
176            get_dashboard_default_widget_instance( 'default-payment-status-widget-instance', self::PAYMENT_STATUS_TYPE, 110, 1, 2 ),
177            get_dashboard_default_widget_instance( 'default-orders-fulfillment-widget-instance', self::ORDERS_FULFILLMENT_TYPE, 120, 1, 2 ),
178            get_dashboard_default_widget_instance( 'default-coupon-usage-over-time-widget-instance', self::COUPON_USAGE_OVER_TIME_TYPE, 130, 1, 2 ),
179            get_dashboard_default_widget_instance( 'default-sessions-by-device-widget-instance', self::SESSIONS_BY_DEVICE_TYPE, 140, 1, 2 ),
180            get_dashboard_default_widget_instance( 'default-top-performing-products-widget-instance', self::TOP_PERFORMING_PRODUCTS_TYPE, 150, 1, 2 ),
181            get_dashboard_default_widget_instance( 'default-sales-by-utm-source-widget-instance', self::SALES_BY_UTM_SOURCE_TYPE, 160, 1, 2 ),
182            get_dashboard_default_widget_instance( 'default-sales-by-utm-channel-widget-instance', self::SALES_BY_UTM_CHANNEL_TYPE, 170, 1, 2 ),
183            get_dashboard_default_widget_instance( 'default-sales-by-utm-campaign-widget-instance', self::SALES_BY_UTM_CAMPAIGN_TYPE, 180, 1, 2 ),
184            get_dashboard_default_widget_instance( 'default-revenue-by-customer-type-widget-instance', self::REVENUE_BY_CUSTOMER_TYPE_TYPE, 190, 1, 2 ),
185            get_dashboard_default_widget_instance( 'default-sales-by-device-widget-instance', self::SALES_BY_DEVICE_TYPE, 200, 1, 2 ),
186            get_dashboard_default_widget_instance( 'default-total-returns-widget-instance', self::TOTAL_RETURNS_TYPE, 210, 1, 2 ),
187            get_dashboard_default_widget_instance( 'default-sales-by-coupon-widget-instance', self::SALES_BY_COUPON_TYPE, 220, 1, 2 ),
188
189        );
190    }
191
192    /**
193     * The manifest minus the categories held back from the tab and the bookings categories
194     * without their extension.
195     *
196     * @param array[] $widget_modules     Widget module records of the build manifest.
197     * @param bool    $bookings_available Whether the WooCommerce Bookings extension is active.
198     * @return array[] The records the package registers.
199     */
200    private static function remove_unavailable_widget_types( $widget_modules, $bookings_available ) {
201        return array_values(
202            array_filter(
203                $widget_modules,
204                static function ( $widget_module ) use ( $bookings_available ) {
205                    $category = $widget_module['category'] ?? '';
206
207                    if ( in_array( $category, self::HELD_BACK_WIDGET_CATEGORIES, true ) ) {
208                        return false;
209                    }
210
211                    return $bookings_available || ! in_array( $category, self::BOOKINGS_WIDGET_CATEGORIES, true );
212                }
213            )
214        );
215    }
216
217    /**
218     * Register the widget types from the package's build manifest.
219     *
220     * Loads the generated build first: after `init` it registers the widget script modules on the
221     * spot, so they reach the page import map the same request.
222     *
223     * Registers nothing without WooCommerce or for a reader who cannot see store reports: the types
224     * would only collect 403s from the proxy.
225     *
226     * @param object $registry The widget type registry being hydrated.
227     * @return void
228     */
229    public static function register_widget_types( $registry ) {
230        if ( ! self::supports_widget_contract() || ! self::is_woocommerce_available() || ! self::current_user_can_view_store_reports() ) {
231            return;
232        }
233
234        self::load_build();
235        if ( ! function_exists( 'jetpack_woocommerce_stats_get_registered_widget_modules' ) ) {
236            return;
237        }
238
239        register_widget_types_from_manifest(
240            self::remove_unavailable_widget_types( jetpack_woocommerce_stats_get_registered_widget_modules(), self::is_bookings_plugin_active() ),
241            array(
242                'textdomain'    => self::TEXTDOMAIN,
243                'i18n_manifest' => add_query_arg( 'ver', self::PACKAGE_VERSION, plugins_url( 'i18n-manifest.json', self::build_dir() . '/build.php' ) ),
244            ),
245            $registry
246        );
247    }
248
249    /**
250     * Whether the WooCommerce tab is available: WooCommerce is active, the reader may see store
251     * reports, and a site that opted in on its own carries the dashboard's store flag.
252     *
253     * @return bool
254     */
255    public static function is_section_available() {
256        return self::is_store_section_enabled() && self::is_woocommerce_available() && self::current_user_can_view_store_reports();
257    }
258
259    /**
260     * Whether WooCommerce is active.
261     *
262     * @return bool
263     */
264    public static function is_woocommerce_available() {
265        $is_available = class_exists( 'WooCommerce' ) || function_exists( 'WC' );
266
267        /**
268         * Filters whether WooCommerce was detected.
269         *
270         * @since $$next-version$$
271         *
272         * @param bool $is_available Whether WooCommerce was detected in the current request.
273         */
274        return (bool) apply_filters( self::WOOCOMMERCE_AVAILABLE_FILTER, $is_available );
275    }
276
277    /**
278     * Whether the current user may read the store reports, the rule the reports proxy enforces.
279     *
280     * @return bool
281     */
282    public static function current_user_can_view_store_reports() {
283        // phpcs:ignore WordPress.WP.Capabilities.Unknown -- WooCommerce registers this capability.
284        return current_user_can( 'manage_options' ) || current_user_can( 'view_woocommerce_reports' );
285    }
286
287    /**
288     * The dashboard's soft-launch policy: a site that opted in through the option needs the store
289     * flag; the blog sticker and the enabled filter leave the option off and keep every section.
290     *
291     * @return bool
292     */
293    private static function is_store_section_enabled() {
294        if ( ! get_option( Enablement_Setting::ENABLED_OPTION ) ) {
295            return true;
296        }
297
298        // An older dashboard package may have loaded dashboard-policy.php without the flag.
299        $is_flag_enabled = 'Automattic\\Jetpack\\PremiumAnalytics\\is_dashboard_store_section_enabled';
300
301        return function_exists( $is_flag_enabled ) && $is_flag_enabled();
302    }
303
304    /**
305     * Whether the WooCommerce Bookings extension is active; `is_plugin_active()` only exists in
306     * admin contexts, hence the guard.
307     *
308     * @return bool
309     */
310    private static function is_bookings_plugin_active() {
311        return class_exists( 'WC_Bookings' )
312            || ( function_exists( 'is_plugin_active' ) && \is_plugin_active( 'woocommerce-bookings/woocommerce-bookings.php' ) );
313    }
314
315    /**
316     * Whether the dashboard's widget contract is one the widgets were built against.
317     *
318     * On an older contract the SDK module lacks a name the widgets import, and they fail to load.
319     *
320     * @return bool
321     */
322    private static function supports_widget_contract() {
323        if ( ! defined( 'Automattic\\Jetpack\\PremiumAnalytics\\WIDGET_API_VERSION' ) ) {
324            return false;
325        }
326
327        $version = \Automattic\Jetpack\PremiumAnalytics\WIDGET_API_VERSION;
328
329        return version_compare( $version, self::MIN_WIDGET_API_VERSION, '>=' ) && version_compare( $version, '2', '<' );
330    }
331
332    /**
333     * Load the generated build once. Guarded by symbol, not by path: two copies of the package
334     * can share a request.
335     *
336     * @return void
337     */
338    private static function load_build() {
339        if ( function_exists( 'jetpack_woocommerce_stats_get_registered_widget_modules' ) ) {
340            return;
341        }
342        $loader = self::build_dir() . '/build.php';
343        if ( file_exists( $loader ) ) {
344            require_once $loader;
345        }
346    }
347
348    /**
349     * Directory of the wp-build output.
350     *
351     * @return string
352     */
353    private static function build_dir() {
354        return dirname( __DIR__ ) . '/build';
355    }
356
357    /**
358     * Whether this tab's slug, or the `store` slug an older package still registers, is taken.
359     *
360     * @param object $registry The section registry being hydrated.
361     * @return bool
362     */
363    private static function section_slug_is_taken( $registry ) {
364        foreach ( array( 'woocommerce', 'store' ) as $slug ) {
365            if ( self::dashboard_has_section_slug( $registry, DASHBOARD_NAME, $slug ) ) {
366                return true;
367            }
368        }
369
370        return false;
371    }
372
373    /**
374     * Whether a section with the slug is registered on the dashboard.
375     *
376     * Reads the registry through the slug lookup when the package offers it, and through the full
377     * list otherwise: the package and this one ship on different cadences.
378     *
379     * @param object $registry       The registry being hydrated.
380     * @param string $dashboard_name Dashboard identifier.
381     * @param string $slug           Section slug.
382     * @return bool
383     */
384    private static function dashboard_has_section_slug( $registry, $dashboard_name, $slug ) {
385        if ( method_exists( $registry, 'get_registered_by_slug' ) ) {
386            return null !== $registry->get_registered_by_slug( $dashboard_name, $slug );
387        }
388
389        foreach ( $registry->get_all_registered( $dashboard_name ) as $section ) {
390            if ( $section->slug === $slug ) {
391                return true;
392            }
393        }
394
395        return false;
396    }
397}