Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 6 additions & 35 deletions includes/Admin/Menu.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,13 @@ public function enqueue_landing_scripts_and_styles( $hook_suffix ): void {
true
);

// Inject functional data (locale, version, anon_id, experiment
// bootstrap flags). The landing bundle owns PostHog initialisation,
// flag resolution, and identify ordering (flag-before-identify, spec
// §5.1); the plugin must NOT init PostHog or identify here — doing so
// shares the bundle's localStorage identity, breaks the anon-bucket
// exposure, and double-fires CTA tracking.
wp_add_inline_script( 'wcpos-welcome', $this->landing_inline_script(), 'before' );
wp_add_inline_script( 'wcpos-welcome', self::get_posthog_inline_script(), 'before' );
wp_add_inline_script( 'wcpos-welcome', $this->landing_tracking_inline_script(), 'after' );
}
}

Expand Down Expand Up @@ -430,39 +434,6 @@ private function landing_inline_script(): string {
);
}

/**
* Track clicks from the remote upgrade landing content.
*
* @return string
*/
private function landing_tracking_inline_script(): string {
return <<<JS
(function() {
var root = document.getElementById('woocommerce-pos-upgrade');
if (!root) {
return;
}

document.addEventListener('click', function(event) {
var target = event.target;
if (!target || !target.closest) {
return;
}

var link = target.closest('#woocommerce-pos-upgrade a[href*="wcpos.com/pro"]');
if (!link || !window.wcpos || !window.wcpos.posthog || !window.wcpos.posthog.capture) {
return;
}

window.wcpos.posthog.capture('upgrade_cta_clicked', {
placement: 'admin_landing_banner',
destination: link.href
});
});
})();
JS;
}

/**
* Print a tiny global click tracker for PHP-rendered admin upsell links.
*/
Expand Down
159 changes: 159 additions & 0 deletions includes/Services/Feature_Flags.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<?php
/**
* Feature flag resolver for the wp-admin landing page.
*
* Resolves the `landing-variant` A/B experiment server-side so the value can
* be injected into `window.wcpos.landing` and bootstrapped into the landing
* bundle's PostHog client at first paint — no network round-trip, no flicker,
* and no dependency on the PostHog `/flags` endpoint (which the self-hosted
* proxy does not authenticate for the public project token).
*
* Assignment uses PostHog's standard consistent-hashing algorithm — the same
* one the server SDKs use for local evaluation — so a given distinct id always
* maps to the same variant, with the configured rollout split. This keeps the
* recorded `$feature_flag_response` stable and the experiment denominators
* valid (landing-experiments spec §5.1).
*
* @package WCPOS\WooCommercePOS\Services
*/

namespace WCPOS\WooCommercePOS\Services;

/**
* Feature_Flags service.
*/
class Feature_Flags {
/**
* The landing-page experiment flag key. Program-wide identifier shared with
* the wp-admin-landing bundle (`FLAG_KEY` in variant-loader.ts); do not rename.
*
* @var string
*/
const LANDING_FLAG_KEY = 'landing-variant';

/**
* PostHog's hashing constant: 0xFFFFFFFFFFFFFFF (15 hex digits, 2^60 - 1).
* The first 15 hex digits of the SHA-1 are scaled by this to a [0, 1) float.
*
* @var int
*/
const LONG_SCALE = 0xFFFFFFFFFFFFFFF;

/**
* Multivariate variants for `landing-variant`, in PostHog config order.
*
* The order and rollout percentages mirror the flag definition in PostHog so
* local assignment matches what `get_all_feature_flags()` resolves there.
* `free-plus` is the reference arm and the bundle's fallback variant.
*
* KEEP IN SYNC: this is the source of truth for assignment while the
* self-hosted `/flags` endpoint is unusable. If the flag's variants, order,
* or split change in the PostHog UI, update this AND the wp-admin-landing
* bundle (`VALID_VARIANTS` / `FALLBACK_VARIANT` in variant-loader.ts), or the
* experiment denominators will silently skew. See wcpos/wp-admin-landing#39.
*
* @var array<int, array{key: string, rollout: int}>
*/
const LANDING_VARIANTS = array(
array(
'key' => 'indie',
'rollout' => 50,
),
array(
'key' => 'free-plus',
'rollout' => 50,
),
);

/**
* Build the feature-flag bootstrap map for the landing page.
*
* Returns a map of resolved flags keyed for PostHog's `bootstrap.featureFlags`
* (e.g. `array( 'landing-variant' => 'indie' )`). Empty when no distinct id is
* available, in which case the bundle resolves the variant itself.
*
* @param string $distinct_id Stable anonymous identifier for the visitor/site.
*
* @return array<string, string>
*/
public function get_landing_bootstrap_flags( string $distinct_id ): array {
$flags = array();
$variant = $this->get_landing_variant( $distinct_id );

if ( null !== $variant ) {
$flags[ self::LANDING_FLAG_KEY ] = $variant;
}

/**
* Filters the feature flags bootstrapped into the landing page.
*
* Allows forcing a variant (for QA) or extending the bootstrap with
* additional flags. Values must be strings or booleans, matching
* PostHog's `bootstrap.featureFlags` contract.
*
* @since 1.9.7
*
* @param array<string, string|bool> $flags Resolved flag map.
* @param string $distinct_id The visitor distinct id.
*/
return apply_filters( 'woocommerce_pos_landing_bootstrap_flags', $flags, $distinct_id );
}

/**
* Resolve the `landing-variant` value for a distinct id.
*
* @param string $distinct_id Stable anonymous identifier.
*
* @return null|string The variant key, or null when no distinct id is given.
*/
public function get_landing_variant( string $distinct_id ): ?string {
if ( '' === $distinct_id ) {
return null;
}

return $this->match_variant( self::LANDING_FLAG_KEY, $distinct_id, self::LANDING_VARIANTS );
}

/**
* Map a distinct id to a variant using PostHog's consistent-hash lookup.
*
* The variant hash is salted with `variant` and compared against the
* cumulative rollout ranges built from the variant order.
*
* @param string $key Flag key.
* @param string $distinct_id Distinct id.
* @param array<int, array{key: string, rollout: int}> $variants Ordered variants.
*
* @return null|string
*/
private function match_variant( string $key, string $distinct_id, array $variants ): ?string {
$hash_value = $this->hash( $key, $distinct_id, 'variant' );

$value_min = 0.0;
foreach ( $variants as $variant ) {
$value_max = $value_min + ( $variant['rollout'] / 100 );
if ( $hash_value >= $value_min && $hash_value < $value_max ) {
return $variant['key'];
}
$value_min = $value_max;
}

return null;
}

/**
* PostHog consistent hash: SHA-1 of `key.distinct_id+salt`, first 15 hex
* digits scaled to a deterministic [0, 1) float.
*
* @param string $key Flag key.
* @param string $distinct_id Distinct id.
* @param string $salt Hash salt (`variant` for variant selection).
*
* @return float
*/
private function hash( string $key, string $distinct_id, string $salt = '' ): float {
$hex = substr( sha1( $key . '.' . $distinct_id . $salt ), 0, 15 );

return (float) ( hexdec( $hex ) / self::LONG_SCALE );
}
}
18 changes: 12 additions & 6 deletions includes/Services/Landing_Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,23 @@ class Landing_Profile {
/**
* Get functional data that is always available (no consent required).
*
* Used for translations, feature gating, and schema versioning.
* Used for translations, feature gating, and schema versioning. Includes the
* anonymous identity and the server-resolved experiment flags so the landing
* bundle can bootstrap its A/B variant at first paint without a network flag
* fetch (landing-experiments spec §5.1).
*
* @return array
*/
public function get_functional_data(): array {
$anon_id = ( new Anon_ID() )->get();

return array(
'schema_version' => 2, // bumped: anon_id added (landing-experiments spec §5.1).
'locale' => get_locale(),
'plugin_version' => PLUGIN_VERSION,
'pro_active' => class_exists( '\WCPOS\WooCommercePOSPro\WooCommercePOSPro' ),
'anon_id' => ( new Anon_ID() )->get(),
'schema_version' => 2, // bumped: anon_id added (landing-experiments spec §5.1).
'locale' => get_locale(),
'plugin_version' => PLUGIN_VERSION,
'pro_active' => class_exists( '\WCPOS\WooCommercePOSPro\WooCommercePOSPro' ),
'anon_id' => $anon_id,
'bootstrap_flags' => ( new Feature_Flags() )->get_landing_bootstrap_flags( $anon_id ),
);
}

Expand Down
123 changes: 123 additions & 0 deletions tests/includes/Admin/Test_Menu_Landing_Bootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php
/**
* Tests for the wp-admin landing page bootstrap wiring.
*
* @package WCPOS\WooCommercePOS\Tests\Admin
*/

namespace WCPOS\WooCommercePOS\Tests\Admin;

use WCPOS\WooCommercePOS\Admin\Menu;
use WCPOS\WooCommercePOS\Services\Analytics;
use WCPOS\WooCommercePOS\Services\Settings as SettingsService;
use WP_UnitTestCase;

/**
* Tests that the landing page delegates PostHog ownership to the bundle.
*
* @covers \WCPOS\WooCommercePOS\Admin\Menu
*/
class Test_Menu_Landing_Bootstrap extends WP_UnitTestCase {
/**
* The menu instance under test.
*
* @var Menu
*/
private $menu;

Comment thread
wcpos-bot[bot] marked this conversation as resolved.
/**
* Original general settings snapshot for restoration.
*
* @var array
*/
private $original_general_settings = array();

/**
* Set up test fixtures.
*/
public function setUp(): void {
parent::setUp();

Analytics::reset_instance();

// Keep the consent-gated server-side capture/group calls off the network.
add_filter( 'pre_http_request', '__return_empty_array' );

// Clear any landing handle left registered by an earlier test so the
// inline-script assertions below see only this test's enqueue.
wp_deregister_script( 'wcpos-welcome' );

$user_id = self::factory()->user->create( array( 'role' => 'administrator' ) );
wp_set_current_user( $user_id );
wp_get_current_user()->add_cap( 'manage_woocommerce_pos' );

// Consent ON: under the old code this is exactly when the plugin emitted
// a real posthog.init + identify, so the regression assertions below are
// meaningful rather than vacuous.
$this->original_general_settings = (array) woocommerce_pos_get_settings( 'general' );
$settings = $this->original_general_settings;
$settings['tracking_consent'] = 'allowed';
SettingsService::instance()->save_settings( 'general', $settings );

$this->menu = new Menu();
}

/**
* Tear down test fixtures.
*/
public function tearDown(): void {
SettingsService::instance()->save_settings( 'general', $this->original_general_settings );
remove_filter( 'pre_http_request', '__return_empty_array' );
Analytics::reset_instance();
wp_set_current_user( 0 );
wp_deregister_script( 'wcpos-welcome' );

parent::tearDown();
}

/**
* Reads the inline scripts attached to the landing bundle at a position.
*
* @param string $position Either `before` or `after`.
*
* @return string Concatenated inline script source.
*/
private function inline_scripts( string $position ): string {
$data = wp_scripts()->get_data( 'wcpos-welcome', $position );

return \is_array( $data ) ? implode( "\n", $data ) : (string) $data;
}

/**
* The landing page must still inject the functional data block so the bundle
* can read locale/version/anon_id/bootstrap_flags.
*/
public function test_landing_page_injects_functional_data(): void {
$this->menu->enqueue_landing_scripts_and_styles( $this->menu->toplevel_screen_id );

$this->assertStringContainsString( 'wcpos.landing', $this->inline_scripts( 'before' ) );
}

/**
* The plugin must NOT initialise PostHog on the landing page — the bundle
* owns init/identify (flag-before-identify). An early init here shares the
* bundle's localStorage identity and breaks anon-bucket exposure.
*/
public function test_landing_page_does_not_initialise_posthog(): void {
$this->menu->enqueue_landing_scripts_and_styles( $this->menu->toplevel_screen_id );

$before = $this->inline_scripts( 'before' );
$this->assertStringNotContainsString( 'posthog.init', $before );
$this->assertStringNotContainsString( 'posthog.identify', $before );
}

/**
* The redundant DOM-level CTA tracker (which depended on window.wcpos.posthog
* and double-fired against the bundle's own React tracking) must be gone.
*/
public function test_landing_page_has_no_duplicate_cta_tracking(): void {
$this->menu->enqueue_landing_scripts_and_styles( $this->menu->toplevel_screen_id );

$this->assertStringNotContainsString( 'upgrade_cta_clicked', $this->inline_scripts( 'after' ) );
}
}
Loading
Loading