Repository navigation
Compute the Site Goals Key action rate from sessions with a Key action. - #14182
jimmymadon wants to merge 43 commits into
Conversation
📚 Storybook for ab80b8e: 📦 Build files for ab80b8e:
🖼️ VRT report for ab80b8e:
🎭 Playwright reports for ab80b8e: |
There was a problem hiding this comment.
Code Review
This pull request updates the Key action rate calculation in the Analytics 4 Site Goals widgets (Lead Generation and Online Store) across the JS dashboard, PDF exports, and PHP email reporting. Instead of dividing the total event count by sessions, it introduces a new report that tracks unique sessions containing at least one key action event, preventing the rate from exceeding 100%. The feedback recommends simplifying the getTotalsMetric helper function in JS by removing a redundant type assertion and unnecessary optional chaining to improve code readability.
| function getValue( dateRangeSlug: string ) { | ||
| return ( | ||
| parseFloat( | ||
| ( totals as ReportRow[] )?.find?.( | ||
| makeFind( dateRangeSlug, 0 ) | ||
| )?.metricValues?.[ metricIndex ]?.value ?? '' | ||
| ) || 0 | ||
| ); | ||
| } |
There was a problem hiding this comment.
The type assertion as ReportRow[] is redundant because totals is already typed as an array of report rows (or defaults to []). Additionally, since totals is guaranteed to be an array, we can safely call .find directly without optional chaining (?.find?.). Simplifying this improves readability and avoids potential compilation issues if ReportRow is not explicitly imported in this file.
| function getValue( dateRangeSlug: string ) { | |
| return ( | |
| parseFloat( | |
| ( totals as ReportRow[] )?.find?.( | |
| makeFind( dateRangeSlug, 0 ) | |
| )?.metricValues?.[ metricIndex ]?.value ?? '' | |
| ) || 0 | |
| ); | |
| } | |
| function getValue( dateRangeSlug: string ) { | |
| return ( | |
| parseFloat( | |
| totals.find( | |
| makeFind( dateRangeSlug, 0 ) | |
| )?.metricValues?.[ metricIndex ]?.value ?? '' | |
| ) || 0 | |
| ); | |
| } |
|
Size Change: 0 B Total Size: 3.59 MB ℹ️ View Unchanged
|
Moves the rate out of processReports() into getKeyActionRates(), which requires the Key action sessions report, and uses it in the Site Goals widgets, the Sales rate and Form completion rate Key Metrics tiles and their PDF tiles.
…t conversion rate.
zutigrm
left a comment
There was a problem hiding this comment.
Thanks @jimmymadon nice work. Left you some comments, let me know what you think
| // No rows means the report has no data, so don't render the tile. | ||
| if ( ! primaryEventReport?.rows?.length ) { | ||
| if ( ! keyActionSessionsReport?.rows?.length ) { |
There was a problem hiding this comment.
This check can't hide the tile anymore. A site without purchases now gets a "Sales rate 0%" tile in the PDF, while the "Total sales" tile is still hidden.
The old report had the eventName dimension, so with no purchases it came back without rows. The new report has no dimension, and GA4 still returns one row per date range, with 0 in it. I checked it on a real property with no purchases: the new report came back with two rows of 0, the old one with none.
If we want to keep hiding the tile, we can check the values instead of the row count:
| // No rows means the report has no data, so don't render the tile. | |
| if ( ! primaryEventReport?.rows?.length ) { | |
| if ( ! keyActionSessionsReport?.rows?.length ) { | |
| // No Key action in either period means the report has no data, so don't render the tile. | |
| if ( isZeroReport( keyActionSessionsReport ) ) { |
with isZeroReport imported from @/js/modules/analytics-4/utils/is-zero-report. A test with the two 0 rows would cover it. The same applies to the "Form completion rate" tile below
|
|
||
| // No rows means the report has no data, so don't render the tile. | ||
| if ( ! primaryEventReport?.rows?.length ) { | ||
| if ( ! keyActionSessionsReport?.rows?.length ) { |
| sessions, | ||
| rate: toRate( total, sessions ), | ||
| total: toMetric( eventRows, EVENT_COUNT_INDEX ), | ||
| sessions: siteSessions, |
There was a problem hiding this comment.
sessions is now the site total, but SiteGoalsBreakdownGroupPDF also uses it for the caption under the engagement rate (L261), and that rate is still the group's own. So in the PDF a form shows "Engagement rate 40%, of 900 total sessions", while 40% is the rate of the form's own 200 sessions (the '12' group in the lead fixtures). On the dashboard, the engagement tile of a tab shows the tab's own sessions (for example "of 29 total sessions" on the WooCommerce tab in the tabbed-breakdown-deactivated-plugin reference), so the PDF no longer matches it.
We can keep the group's own sessions for the engagement tile, something like engagementSessions: toMetric( engagementRows, SESSIONS_INDEX ) on the group, and use it for the engagement tile caption, while the rate tile keeps the site total
| ) { | ||
| $requests[ self::SITE_GOALS_ONLINE_STORE_PRIMARY_KEY ] = $this->report_options->get_online_store_primary_options(); | ||
| $requests[ self::SITE_GOALS_ONLINE_STORE_PRIMARY_KEY ] = $this->report_options->get_online_store_primary_options(); | ||
| $requests[ self::SITE_GOALS_ONLINE_STORE_KEY_ACTION_SESSIONS_KEY ] = $this->report_options->get_key_action_sessions_options( Conversion_Events_Provider::CATEGORY_ECOMMERCE ); |
There was a problem hiding this comment.
When the section is split by plugin, Site_Goals_Section_Builder only reads the split sessions report, so this site-wide one is requested but never used. That's an extra Analytics request in every email for split sites. Before this PR the engagement report sat in an else for the same reason, we can do the same here, and assert in the split test that the key isn't requested. Same for the lead section at L255
| * @param {Object} [breakdownFilter] Optional dimension filter scoping the report to a breakdown tab. | ||
| * @return {Object|undefined} The Analytics 4 `getReport` options, or `undefined` when there is no primary event. | ||
| */ | ||
| export function buildKeyActionSessionsReportOptions( |
There was a problem hiding this comment.
Just a thought on the approach. GA4 gives the same number when sessions is a second metric on the existing Key action report. On a real property, one request with eventCount and sessions for a single event gave 634 events and 234 sessions, and the separate report this PR adds gave the same 234. With that we wouldn't need the extra report. Each Site Goals widget would stay at 2 requests per load instead of 3, the KM "Total sales" and "Sales rate" tiles would share one request again, and the Site Goals PDF stays at 4 requests per section instead of 6.
The catch is the lead report. It has the eventName dimension, and summing sessions over its rows counts a session with two lead events twice: on the same property, 243 sessions had either of two events, but the rows add up to 264. So the lead report would need to drop that dimension and read its counts from the totals.
I know the IB asks for a separate report, WDYT?
There was a problem hiding this comment.
Thanks for testing this on a real property, it's a good find. I'd still keep the separate report in this PR, though:
- For the lead report, dropping
eventNameand reading the totals only works without a breakdown. On a form tab, and in the PDF and email groups, the report is split by form andeventName, and the totals are site-wide, so we'd still count a session twice within a form. The lead report would need to dropeventNameeverywhere, and the email reads thoseeventNamerows (filter_rows_by_event(),find_primary_event()) through options it shares with the store report. So lead would need its own options and readers. - The report options are also the cache keys in the tests and stories, so every mock of the Key action report would change too.
That would reshape the lead report in the same places this PR already changes, while the numbers are already right. The cost now is one extra request per widget load, and the PDF and email already batch theirs.
I'll open a follow-up issue for it, starting with a check that sessions stays deduplicated per form once eventName is dropped. WDYT?
| } ); | ||
| } ); | ||
|
|
||
| it( 'never returns a rate above 1', () => { |
There was a problem hiding this comment.
New and changed test titles should start with "should" (
site-kit-wp/docs/context/js/tests.md
Line 350 in 8202077
reports.test.ts: L59, L73, L83, L93, L110, L132OnlineStorePerformanceWidget.test.tsxL2022,LeadGenerationPerformanceWidget.test.tsxL2054shapeSiteGoalsPDFData.test.tsL160,fetchSiteGoalsPDFReports.test.tsL78, L86key-metrics-widgets.test.jsL543, L622
| * The date range is the only dimension of the totals. A totals row without | ||
| * one counts as the current period. | ||
| * | ||
| * @since n.e.x.t |
There was a problem hiding this comment.
This is getTotalsPair moved from the PDF code, which had @since 1.187.0. We usually keep the original version and add the change:
| * @since n.e.x.t | |
| * @since 1.187.0 | |
| * @since n.e.x.t Renamed from `getTotalsPair` and moved from `shapeSiteGoalsPDFData`. |
| groupedKeyActionSessionsReport: { | ||
| rows: [ | ||
| ...buildBreakdownReportRows( '12', [ '36' ], [ '17' ] ), | ||
| ...buildBreakdownReportRows( '34', [ '18' ], [ '17' ] ), |
There was a problem hiding this comment.
Form 34 has 12 form completions in the current period and 9 in the previous one (L116), but 18 and 17 sessions with one, which GA4 can't return. The comment above says the opposite too. Something like [ '10' ], [ '8' ] would match
| return array( | ||
| 'conversions' => $conversions, | ||
| 'conversion_rate' => $sessions > 0 ? round( $conversions / $sessions, 4 ) : 0.0, | ||
| 'conversion_rate' => $sessions > 0 ? round( (int) $key_action_sessions / $sessions, 4 ) : 0.0, |
There was a problem hiding this comment.
test_build__sends_a_conversion_rate_of_0_when_a_period_has_no_sessions has no key_action_sessions rows, so the rate there is 0 even without this $sessions > 0 check. Changing the check to $key_action_sessions > 0 still passes. Let's add a few sessions with a key action to that test so the 0 can only come from the missing site sessions
| * Internal dependencies | ||
| */ | ||
| import { getDimensionFiltersForEvents } from '@/js/modules/analytics-4/components/site-goals/goal-drivers/utils'; | ||
| import { getDimensionFiltersForEvents } from '@/js/modules/analytics-4/components/site-goals/utils/getDimensionFiltersForEvents'; |
There was a problem hiding this comment.
This is the same folder, so we can use ./getDimensionFiltersForEvents (
getSiteGoalsEventCountReportOptions.ts L23
…ls-key-action-rate.
…on that is not split.
… and error states.
…ls-key-action-rate. # Conflicts: # tests/phpunit/integration/Modules/Analytics_4/Site_Goals/Insight_Payload_BuilderTest.php # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/gathering-breakdown-data/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/gathering-breakdown-data/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/gathering-breakdown-data/small.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/ready/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/ready/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/ready/small.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/tabbed-breakdown-deactivated-plugin/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/tabbed-breakdown-deactivated-plugin/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/lead-generation-performance-widget/tabbed-breakdown-deactivated-plugin/small.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/gathering-breakdown-data/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/gathering-breakdown-data/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/gathering-breakdown-data/small.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/ready-purchase/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/ready-purchase/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/ready-purchase/small.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/tabbed-breakdown-deactivated-plugin/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/tabbed-breakdown-deactivated-plugin/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/tabbed-breakdown-deactivated-plugin/small.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/tabbed-breakdown-other-sources/large.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/tabbed-breakdown-other-sources/medium.png # tests/vrt/__screenshots__/modules/analytics-4/components/site-goals/online-store-performance-widget/tabbed-breakdown-other-sources/small.png
… on a breakdown tab.
Summary
Related issue(s):
Relevant technical choices
Where this differs from the IB:
processReports()into a newgetKeyActionRates(), which requires the Key action sessions report, so no caller can keep the old formula.conversion_rateuse the same calculation. They all build the report with a sharedbuildKeyActionSessionsReportOptions(). The insight now makes 4 requests in its batch call, under GA4's limit of 5.get_key_action_sessions_options()takes the goal type, likeget_key_action_options(), not the event names.$custom_dimensionparameter ofget_engagement_options(), are removed, since nothing uses them anymore.headlineMetrics.ts(with itsHeadlineMetricReportDatestype) andgetDimensionFiltersForEvents()moved fromgoal-drivers/tosite-goals/utils/, as the Site Goals widgets and Key Metrics tiles use them, not the goal drivers. These moves are in their own commits and change no behaviour.Changes by file
Every Key action rate is now sessions with at least one Key action ÷ all site sessions. The sessions with a Key action come from a new report, the
sessionsmetric filtered by event name. The site's sessions come from the engagement report, which no longer takes the tab filter.Paths starting with
site-goals/are underassets/js/modules/analytics-4/components/site-goals/.Shared JS helpers
site-goals/utils/headlineMetrics.ts(moved fromgoal-drivers/report-utils/)buildKeyActionSessionsReportOptions( dates, primaryEvent, breakdownFilter ):sessionswith no dimensions, filtered by the Key action event(s) and the tab filter.getPrimaryEventDimensionFilters(), shared withbuildPrimaryEventReportOptions(), whose behaviour is unchanged.HeadlineMetricReportDatestype, moved fromgoal-drivers/report-utils/types.ts.site-goals/utils/getDimensionFiltersForEvents.ts(new):getDimensionFiltersForEvents(), moved unchanged fromgoal-drivers/utils.ts, with a new doc block.site-goals/utils/reports.tsgetKeyActionRates( keyActionSessionsReport, engagementReport ), returningcurrentRate,previousRateandcurrentSessions, with a rate of 0 when there are no sessions.processReports()no longer returns the rates, only the counts, current sessions and engagement rates.getTotalsRows()(moved from the PDF code), privategetTotalsMetric(), andgetReportsToCheck( ...options )(moved fromOnlineStorePerformanceWidget.tsx).goal-drivers/utils.ts,goal-drivers/report-utils/reportOptionsHelpers.ts,site-goals/utils/getSiteGoalsEventCountReportOptions.ts,site-goals/components/getKeyActionChartReportOptions.ts, and the Total sales, Total form completions, Sales engagement rate and Form completion engagement rate tiles and their tests.Site Goals dashboard widgets
OnlineStorePerformanceWidget.tsxandLeadGenerationPerformanceWidget.tsxprocessReports(), while the rates come fromgetKeyActionRates().getReportsToCheck().Key Metrics tiles
SalesRateWidget.tsxandFormCompletionRateWidget.tsx: request the Key action sessions report instead of the event count report, and usegetKeyActionRates().key-metrics-pdf-tiles.js: the same for the PDF tiles of Sales rate and Form completion rate. A tile is hidden when the Key action sessions report has no rows.useAnalyticsReportsData.ts: doc comment wording only.Dashboard PDF
pdf/reportOptions.ts: addskeyActionSessionsReportOptions,sessionsfiltered byeventName, with the breakdown dimension when there is one.pdf/fetchSiteGoalsPDFReports.ts: requests it in the grouped and the aggregated sets, so 6 reports with a breakdown and 3 without.pdf/shapeSiteGoalsPDFData.tssessionsis the site total, and itsengagementRatestill comes from the grouped engagement report.getTotalsPairis replaced by the sharedgetTotalsRows.Email report and Site Goals insight (PHP)
Site_Goals/Report_Options.phpget_key_action_sessions_options( $goal_type, $custom_dimension = '' ).get_engagement_options()loses$custom_dimension, so it always covers the whole site.get_key_action_event_filter(), shared withget_key_action_options().Email_Reporting/Report_Options.php: passes the new method through, andget_engagement_options()loses$custom_dimension.Report_Request_Assembler.phpSITE_GOALS_{ONLINE_STORE|LEAD}_KEY_ACTION_SESSIONS[_BY_PROVIDER|_BY_FORM]_KEY.SITE_GOALS_ENGAGEMENT_BY_PROVIDER_KEYandSITE_GOALS_ENGAGEMENT_BY_FORM_KEY.SITE_GOALS_ENGAGEMENT_KEY.Site_Goals_Section_Builder.phpget_site_sessions().sum_sessions()now takes any report with asessionsmetric.Insight_Payload_Builder.phpconversion_rateis the sessions with a Key action divided by the site's sessions.conversionsstill counts events.Tests, stories and VRT
reports.test.ts(new): coversgetKeyActionRates,processReportsandgetReportsToCheck.headlineMetrics.test.ts(moved): adds cases forbuildKeyActionSessionsReportOptions.SalesRateWidget,FormCompletionRateWidgetandkey-metrics-widgetstests: each session counts once.pdf/test-utils.tsandpdf/__fixtures__/index.tscover the new report and the new expected rates.widgets/siteGoalsWidgetStoryReports.tswith helpers shared by both widgets' stories, using fixed site totals of 1,250 and 1,100 sessions.Report_Options,Report_Request_AssemblerandSite_Goals_Section_Buildertests cover the new request and the new rate, with and without the plugin or form split.Insight_Payload_Buildertests cover the 4-report batch and the newconversion_rate.Email_Reporting_Data_RequestsTestchecks the new payload key.PR Author Checklist
Do not alter or remove anything below. The following sections will be managed by moderators only.
Code Reviewer Checklist
Merge Reviewer Checklist