Repository navigation
Revenue Analytics Feature - #2074
Conversation
Adds the /analytics/top-products route + fetch_top_products handler, mirroring fetch_top_videos: forwards page/limit/site_url/sort_by/order (+ date range) to the microservice /dashboard/top-products/, POSTing a product_ids include-filter resolved from a product-name search (resolve_top_products_id_filter, WP-side) or a plain GET otherwise. Each returned row is hydrated with the product's current name, permalink and thumbnail from product_id via wc_get_product (display fields are not stored in the service, so renames/reprices reflect immediately); missing products come back exists:false. Registered in the range-routes list so start_date/end_date apply. Gated to upload_files like top-videos. PHPCS clean.
fetchTopProducts query (siteUrl/page/limit/search/sort/range) added to the dashboard RTK api, and a TopProductsTable component cloned from TopVideosTable: one row per product with the WooCommerce name/image/link, a Source-chips column, Product Views with its click-through rate, the direct/assisted Add-to-Cart split (count + rate, with the split as a sub-line and a tooltip), and a Revenue column marked Phase 2. Reuses the shared search (debounced), date-range picker, pagination, skeleton, empty-state, and CSV export. data-test-ids throughout. ESLint clean.
Adds a segmented Top Videos / Top Products switcher above the table, shown only when
WooCommerce is active (new videoData.isWoo flag = class_exists('WooCommerce')). Non-Woo
sites keep the plain Top Videos table with no switcher. ESLint + PHPCS clean; the JS
bundle builds without errors.
Minimal styling for the new .godam-top-tabs switcher (segmented control, active tab uses the WP admin accent) and the .godam-source-chips / .godam-chip pills in Top Products, plus a muted pill variant. Reuses --wp-admin-theme-color. Stylelint clean; JS+SCSS bundle builds without errors.
There was a problem hiding this comment.
Pull request overview
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Adds a WooCommerce-gated Top Products view to the dashboard analytics, backed by a new REST proxy endpoint that forwards queries to the analytics microservice and hydrates rows with WooCommerce product display data.
Changes:
- Added RTK Query endpoint/hooks and a new
TopProductsTablecomponent with search, date range, pagination, and CSV export. - Introduced a Woo-only segmented switcher between Top Videos and Top Products on the dashboard.
- Implemented a new WP REST proxy route (
/analytics/top-products) that forwards requests to the microservice and hydrates products viawc_get_product.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| pages/dashboard/redux/api/dashboardAnalyticsApi.js | Adds fetchTopProducts RTK Query endpoint and hooks used by the dashboard UI. |
| pages/dashboard/index.scss | Adds styling for the Top Videos/Top Products switcher and source “chip” UI. |
| pages/dashboard/components/TopProductsTable.js | New table component for Top Products including search, date range filtering, pagination, and CSV export. |
| pages/dashboard/Dashboard.js | Adds WooCommerce-gated segmented tab switcher and renders TopProductsTable. |
| inc/classes/rest-api/class-analytics.php | Adds /top-products REST route and proxy handler that hydrates rows with WooCommerce product data. |
| inc/classes/class-pages.php | Exposes window.videoData.isWoo to gate the tab UI to WooCommerce sites. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| const handleExportCSV = async () => { | ||
| setIsExporting( true ); | ||
|
|
||
| const pageCount = Math.max( 1, Math.ceil( ( totalItems || products.length ) / EXPORT_PAGE_SIZE ) ); | ||
| const results = await Promise.all( | ||
| Array.from( { length: pageCount }, ( _, i ) => | ||
| fetchForExport( { | ||
| siteUrl, | ||
| page: i + 1, | ||
| limit: EXPORT_PAGE_SIZE, | ||
| search, | ||
| startDate: dateRange.startDate, | ||
| endDate: dateRange.endDate, | ||
| } ).unwrap().catch( () => ( { products: [] } ) ), | ||
| ), | ||
| ); | ||
| const fetched = results.flatMap( ( result ) => result?.products || [] ); | ||
| const exportProducts = fetched.length ? fetched : products; |
There was a problem hiding this comment.
Already handled at the current head, no change needed. handleExportCSV pages with a fixed pool of 4 workers (CONCURRENCY = 4) pulling from a shared cursor, so at most 4 /top-products requests are in flight regardless of catalog size, and failed pages are counted and surfaced to the user.
| const handleExportCSV = async () => { | ||
| setIsExporting( true ); | ||
|
|
||
| const pageCount = Math.max( 1, Math.ceil( ( totalItems || products.length ) / EXPORT_PAGE_SIZE ) ); | ||
| const results = await Promise.all( | ||
| Array.from( { length: pageCount }, ( _, i ) => | ||
| fetchForExport( { | ||
| siteUrl, | ||
| page: i + 1, | ||
| limit: EXPORT_PAGE_SIZE, | ||
| search, | ||
| startDate: dateRange.startDate, | ||
| endDate: dateRange.endDate, | ||
| } ).unwrap().catch( () => ( { products: [] } ) ), | ||
| ), | ||
| ); |
There was a problem hiding this comment.
Already handled, no change needed. handleExportCSV wraps the whole flow (fetches, Blob/URL creation, DOM ops) in try/finally with setIsExporting(false) in the finally, so the button recovers on any throw.
| <div className="godam-top-tabs__nav" role="tablist" aria-label={ __( 'Top content', 'godam' ) }> | ||
| <button | ||
| type="button" | ||
| role="tab" | ||
| aria-selected={ topTab === 'videos' } | ||
| className={ `godam-top-tabs__tab${ topTab === 'videos' ? ' is-active' : '' }` } | ||
| data-test-id="godam-top-tab-videos" | ||
| onClick={ () => setTopTab( 'videos' ) } | ||
| > | ||
| { __( 'Top Videos', 'godam' ) } | ||
| </button> | ||
| <button | ||
| type="button" | ||
| role="tab" | ||
| aria-selected={ topTab === 'products' } | ||
| className={ `godam-top-tabs__tab${ topTab === 'products' ? ' is-active' : '' }` } | ||
| data-test-id="godam-top-tab-products" | ||
| onClick={ () => setTopTab( 'products' ) } | ||
| > | ||
| { __( 'Top Products', 'godam' ) } | ||
| </button> | ||
| </div> | ||
| { topTab === 'videos' | ||
| ? <TopVideosTable siteUrl={ siteUrl } skip={ shouldSkipSecondaryQueries } /> | ||
| : <TopProductsTable siteUrl={ siteUrl } skip={ shouldSkipSecondaryQueries } /> } |
There was a problem hiding this comment.
Fixed in b7aec61 (same change as the line-190 thread). The switcher is now plain buttons with aria-pressed instead of a tablist/tab with no tabpanel.
| if ( is_wp_error( $response ) ) { | ||
| return new WP_REST_Response( | ||
| array( | ||
| 'status' => 'error', | ||
| 'message' => $response->get_error_message(), | ||
| ), | ||
| 500 | ||
| ); | ||
| } | ||
|
|
||
| $body = json_decode( wp_remote_retrieve_body( $response ), true ); | ||
| $top_products = $body['top_products'] ?? array(); |
There was a problem hiding this comment.
Fixed in b4122ad. The JSON-validity half is now handled in both fetch_top_videos and fetch_top_products: the guard is 200 !== $http_code || ! is_array( $body ), matching fetch_placement_funnels, so a 200 with an HTML or unparseable body returns status:error instead of an empty success. See the two line-specific threads.
| if ( ! empty( $sort_by ) ) { | ||
| $query['sort_by'] = $sort_by; | ||
| } | ||
| if ( ! empty( $order ) ) { | ||
| $query['order'] = $order; | ||
| } |
There was a problem hiding this comment.
Already handled, no change needed. The top-products route registers sort_by and order with an enum plus rest_validate_request_arg (sort_by in product_views|add_to_cart|impressions|ctr, order in asc|desc), so an out-of-set value 400s at the proxy before the callback runs.
…Revenue/Phase-2 column Visual review of the rendered dashboard found three issues, all fixed: - The tab switcher now renders inside the active table's head (passed as tabSwitcher), so there is no longer a second 'Top Products' heading below the tabs. - Removed the Revenue column and its 'Phase 2' badge from the UI entirely; 'Phase 2' is a planning label and must never appear on screen. Revenue lands when Phase 2 does. - Non-Woo sites still fall back to the plain Top Videos heading (tabSwitcher null). ESLint + Stylelint clean; bundle builds.
…ent blue) Active tab is now a white pill with dark #1e1e1e text (was the admin accent, which rendered blue/pink), inactive is grey; larger padding/size to match the design.
🔍 WordPress Plugin Check Report
📊 Report
|
| 📍 Line | 🔖 Check | 💬 Message |
|---|---|---|
0 |
missing_composer_json_file | The "/vendor" directory using composer exists, but "composer.json" file is missing. |
📁 readme.txt (2 warnings)
| 📍 Line | 🔖 Check | 💬 Message |
|---|---|---|
0 |
mismatched_plugin_name | Plugin name "GoDAM - Organize WordPress Media Library & File Manager with Unlimited Folders for Images, Videos & more" is different from the name declared in plugin header "GoDAM". |
0 |
trademarked_term | The plugin name includes a restricted term. Your chosen plugin name - "GoDAM - Organize WordPress Media Library & File Manager with Unlimited Folders for Images, Videos & more" - contains the restricted term "wordpress" which cannot be used at all in your plugin name. |
📁 assets/build/blocks/godam-gallery-v2/render.php (2 warnings)
| 📍 Line | 🔖 Check | 💬 Message |
|---|---|---|
15 |
WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound | Global variables defined by a theme/plugin should start with the theme/plugin prefix. Found: "$inner_block_video_ids". |
23 |
WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound | Global variables defined by a theme/plugin should start with the theme/plugin prefix. Found: "$inner_block_video_ids". |
📁 assets/build/css/main.css (1 warning)
| 📍 Line | 🔖 Check | 💬 Message |
|---|---|---|
0 |
EnqueuedStylesScope | This style is being loaded in all contexts. |
📁 assets/src/libs/analytics.min.js (5 warnings)
| 📍 Line | 🔖 Check | 💬 Message |
|---|---|---|
0 |
EnqueuedScriptsScope | This script is being loaded in all frontend contexts. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880 (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880/2026/09/24/hello-world/ (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880/sample-page/ (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880/demo-attachment-post/ (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead. |
📁 assets/build/js/main.min.js (5 warnings)
| 📍 Line | 🔖 Check | 💬 Message |
|---|---|---|
0 |
EnqueuedScriptsScope | This script is being loaded in all frontend contexts. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880 (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880/2026/09/24/hello-world/ (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880/sample-page/ (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead. |
0 |
NonBlockingScripts.NoStrategy | This script on http://localhost:8880/demo-attachment-post/ (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead. |
🤖 Generated by WordPress Plugin Check Action • Learn more about Plugin Check
Per review: keep both Add to Cart and Revenue columns. Add to Cart shows the in-video (Direct) count now from backfill, with the Assisted split filling in when Mayank's type=6 capture ships. Revenue is a placeholder column until Phase 2, with no 'Phase 2' label in the UI (that is a planning term, not for the screen).
The product-name cell fell back to a hardcoded English `Product ID: N` when a product had no resolved title. Wrap it in sprintf( __() ) with a translator comment, matching every other string in the component.
… added in-video Per review: variable, grouped and external products can't be added to cart from inside a video (Store API only supports simple products), so their in-video (Direct) count is structurally 0. Rather than a bare 0 that reads as 'no adds', the proxy now returns supports_direct_add_to_cart and the table greys the in-video figure with a hover helper explaining it converts on the product page (Assisted). Nothing is greyed for simple or deleted products.
Adds a Video to Cart KPI card to the dashboard Insights row: the count of distinct
people who played a video then added a product leads, the rate (share of viewers)
and the Direct/Assisted split ('N in-video · M via product page') support it,
mirroring the Top Products Add-to-Cart column. Reads dashboard_metrics.video_to_cart
(godam-analytics#248), which passes through the WP metrics proxy unchanged.
Verified on the dev site: shows 1 cart, 25.0% of viewers, 1 in-video / 0 via product
page (1 of 4 players added in-video).
Adds the Video to Cart card to the single-video Insights row (Analytics.js), reading rangedAnalyticsData.video_to_cart from the per-video analytics endpoint (godam-analytics#248), which the WP proxy passes through unchanged. Moves VideoToCartCard into pages/analytics/ so the dashboard and per-video surfaces share one component, matching how SingleMetrics is shared. Verified live on the dev site (video id 327): card shows 1 cart, 25.0% of viewers, 1 in-video / 0 via product page, matching the endpoint and RTK store.
Adds godam-video-to-cart-card / -label / -value hooks so end-to-end tests can locate the card and read its value, matching the data-test-id convention used across the dashboard analytics tables.
…available Review follow-up (#2074): the Video-to-Cart card was unconditional and collapsed an absent payload to zeros, so a non-WooCommerce site (and a Woo site pointed at an analytics service that predates the video_to_cart roll-up) showed a permanent, misleading 'Video to Cart: 0'. - Gate the dashboard card on hasWooProducts (window.videoData.isWoo), matching the Top Products tab, and the per-video card on the same flag (now localized for the analytics page too). - VideoToCartCard renders nothing when videoToCart is null/undefined, so it never asserts '0 carts' for 'metric unavailable'. A present payload with zero carts is a real value and still renders. Verified on the dev site (Woo, data present): card renders 1 / 25.0% of viewers / 1 in-video / 0 via product page; hidden when the payload is absent.
…t a fixed 7-day trend
On the per-video Insights row the metric cards showed a fixed 'vs prev 7 days'
trend badge that ignored the range picker, while the Video-to-Cart card showed the
active range ('All time'), so the row disagreed with itself and with the picker.
Drop the client-side 7-day trend badge from the per-video SingleMetrics and
PlaysVsViewers and show the active range label instead, matching the Video-to-Cart
card and the range picker. Dashboard mode is unchanged: it still shows the
range-aware server period-over-period delta for a bounded range and the range
label at All Time. Removes the now-unused 7-day-history trend helpers from both
components.
…ISO-date validation - TopProductsTable.test.js: escapeCsvCell quotes a leading =,+,-,@ or tab/CR/newline so product names cannot execute as spreadsheet formulas; ordinary values unchanged. Exports escapeCsvCell for the test (no behavior change; default export intact). - VideoToCartCard.test.js: the M1 guard - renders nothing for a null/undefined video_to_cart payload (metric unavailable), still renders for a real zero-carts payload (0 is a measured value). Rendered via renderToString, no new dependency. - AnalyticsValidateIsoDateTest.php: validate_iso_date accepts strict Y-m-d (incl. valid leap day), rejects non-calendar/malformed dates; empty is allowed (the date params are optional). Wires class-analytics.php into the existing PHP test bootstrap. JS: 19 passed. PHP: 75 passed / 151 assertions.
…two lines The combined 'N in-video · M via product page' line was whitespace-nowrap, so in the narrow dashboard Insights card (5 cards on a laptop-width row) it overflowed and clipped at the right edge. Split it into two short stacked lines that fit at any card width.
Design feedback (Figma): - Drop Engagement Rate from the dashboard Insights row so it is four cards on WooCommerce sites (three on non-Woo, where Video-to-Cart is hidden), matching the design and giving each card room. Average Engagement stays on the per-video page. - Delta badge uses diagonal arrows (up-right / down-right) and keeps the arrow with its percentage on one line instead of wrapping the arrow onto its own row. - Video-to-Cart card gets a 'Woo' badge on its title, so it reads as a WooCommerce metric. - The rightmost card's info tooltip grew rightward and ran off the screen edge; it now anchors to the icon's right and grows inward, so it stays on-screen.
…e line With the dashboard row down to four cards there is width for it, and the card's extra height was leaving the sibling cards with dead space. Put '% of viewers' beside the count and restore the in-video/via-product-page split to a single line, so the card is about as short as the others. It wraps rather than clips if the window gets very narrow.
Mirror the thumbnail link: the product name now links to the product permalink (new tab), and stays plain text when a product has no permalink (missing product), exactly as the thumbnail already behaves.
Adds a unit test for sourceLabel: woo-layer/shoppable-video (+ the placeholder reel-pop / wc-product-gallery / godam-image labels) map to their display strings, and an unknown block_source falls back to the raw value. Exports sourceLabel for the test (no behavior change).
…split The card counts distinct people (deduped per person), so a buyer who added both in-video and via the product page would make the split read higher than the headline count and confuse the reader. The split lives in the Top Products table, where the numbers sum cleanly. Also drop the em-dash from the grey-out title in Top Products.
…oCommerce
Both are paid GoDAM for Woo add-on features, but the dashboard/analytics
videoData localized isWoo on class_exists('WooCommerce'), so any WooCommerce
store saw the Top Products tab and the Video to Cart card even without the paid
add-on. Gate them on the add-on's own premium check,
godam_woo_should_show_premium_blocks() (guarded by function_exists so it is
false when the add-on is inactive). This is the exact gate the add-on uses for
its own Pro blocks (Elementor/WPBakery Shoppable Video), so these features now
appear under identical conditions: add-on active and a valid GoDAM license.
* feat(top-products): render real Revenue once the analytics service reports it TopProductsTable's Revenue column was shipped as an empty placeholder (no 'Phase 2' label). The microservice's /dashboard/top-products/ response can now include revenue_minor/orders/currency per product; the REST proxy (fetch_top_products) and the RTK Query transformResponse already forward unknown fields through untouched, so no PHP or redux change was needed. Format revenue_minor/currency with Intl.NumberFormat and show the orders count as secondary text, matching the product_views/CTR pattern. Rows from an older service build that omit revenue_minor keep the existing "-" placeholder instead of showing a misleading value. Also carries the new columns into the CSV export. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * Format Top Products revenue by currency fraction digits; make CSV numeric Scale revenue_minor by the currency's own ISO 4217 fraction digits (from Intl) instead of a hardcoded /100 and toFixed(2), so JPY (0 digits) and KWD (3 digits) render correctly. Export revenue in the CSV as a plain dot-decimal number in major units with the currency code in its own column, rather than a locale currency string. --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Subodh Rajpopat <subodh.rajpopat@rtcamp.com>
GoDAM commits to a single store currency (no cross-currency conversion).
- WP proxy (class-analytics.php): pass base_currency = get_option('woocommerce_currency')
to /dashboard/metrics/fetch/ and /dashboard/top-products/, so the service returns
base-currency revenue and a count of orders in other currencies. The `revenue`
object already forwards through the dashboard-metrics array_merge.
- RevenueCard.js: a WooCommerce-only Insights KPI card showing total video-attributed
revenue via the existing formatRevenue(minor, currency), with an
"excluding N orders in other currencies" sub-line when that count is > 0 (and
nothing when 0, i.e. a single-currency store). Renders nothing if the payload is
absent, so it never shows a misleading 0.
- Dashboard.js: render RevenueCard in the Insights row, gated on hasWooProducts.
Base branch: feat/top-products (where #2086 shipped the Top Products revenue UI +
formatRevenue). Pairs with godam-analytics#257.
Sub-task C (core). Consumes the per-hotspot revenue the layer-analytics endpoint
now returns.
- useVideoLayerData: map revenue_minor/orders/currency onto each sub-hotspot; the
parent carries the sum of its hotspots' revenue (currency from any child).
- SubHotspotRail: a small secondary line per hotspot, "<amount> · N orders",
shown only when that hotspot has orders (Woo layers only).
- LayerDetailPanel: a headline "This hotspot/layer drove <amount> across N orders"
above the funnel, with an InfoTooltip that it is the Direct in-video contribution
only, not the product's total (Assisted purchases are excluded). Reuses the
shipped formatRevenue (correct ISO fraction digits), full numbers.
- WP proxy: pass base_currency = get_option('woocommerce_currency') to
/processed-layer-analytics/.
Base branch feat/top-products (#2086). Pairs with godam-analytics#259.
Each Woo composite row carries revenue_minor/orders/currency from the endpoint; assert groupRows maps them onto the sub, sums them onto the parent (currency from a base-currency child), and a non-base order that the server excluded (revenue_minor 0) is never blended in. Also assert the fields default to 0/empty when the endpoint sends none.
… per-PR) Main godam regenerates languages/godam.pot only at release. Committing per-PR POT regens turns this generated file into a recurring merge-conflict source against a fast-moving develop. Reset it to develop's exact version so this branch no longer modifies it; the 'POT matches a fresh build' check is expected red until release.
Revenue Analytics for WooCommerce release prep on feat/top-products. - Stable tag 2.2.3 -> 2.3.0 in readme.txt and README.md - v2.3.0 changelog entry (September 23, 2026) in readme.txt and CHANGELOG.md; drop the now-oldest v2.2.1 entry from readme.txt so it keeps three - Version 2.2.3 -> 2.3.0 in the godam.php header and RTGODAM_VERSION - Version 2.2.3 -> 2.3.0 in package.json and package-lock.json - Project-Id-Version header in languages/godam.pot No @SInCE n.e.x.t placeholders remained in this repo.
…k, full titles on hover - Purchase Funnel: every bar segment now explains itself on hover (WP Tooltip + aria-label): the tier, its count and its share of that stage, e.g. "Assisted only (clicked out): 37 of 64 added to cart (57.8%)"; the grey remainder reads "Did not reach this stage: N of M players". - Purchase Funnel: the Purchased bar was painted entirely Direct blue, hiding Assisted buyers. Draw its Direct / Assisted split from the new purchased.direct / purchased.assisted the service sends (godam-analytics fix/funnel-purchased-tier-split); an older service without the split still gets a single segment rather than a guessed tier. - Dashboard head: "Analytics docs ↗" link to https://godam.io/docs/godam-analytics/ next to the Reel Pop link. - Top Videos / Top Products: the truncated title cell carries the full name as a hover title.
…oltip on hover The truncated title cell now uses the same @wordpress/components Tooltip as the funnel segments (portalled, styled, keyboard-reachable) instead of a native title attribute, so the full name is readable and consistent.
… Top Products names The WP Tooltip does not reliably open on the table title cells (the tables re-render periodically, which resets its show delay), so the truncated cell carries the full name as a native title attribute instead: no timers, no clipping, works with keyboard focus on the link.
The proxy returns texturized titles (e.g. "–"), which the tables and their new title tooltips rendered literally. Decode with @wordpress/html-entities (a WP core script, added as a dependency) for both the cell text and the title attribute.
Review follow-ups (#2134): - TopVideosTable: the two <img alt> still received the raw title, so a screen reader read "Swimming Lesson – 3" while the visible text and title attribute were decoded. Wrap both in decodeEntities(), same as the rest. - PurchaseFunnelCard: a zero-count tier rendered a width:0% segment that was still tabIndex=0 with an aria-label, so keyboard users tabbed onto invisible targets announcing "0 of N". Filter segments to frac > 0 before the map. Test added (verified to fail against the unfiltered code): a funnel with a zero-count Direct and a zero-count Assisted renders neither phantom segment, while the nonzero tiers still render. Suite 15 pass, lint clean.
…k, full titles on hover (#2134) * fix(analytics): funnel hover tooltips, Purchased tier split, docs link, full titles on hover - Purchase Funnel: every bar segment now explains itself on hover (WP Tooltip + aria-label): the tier, its count and its share of that stage, e.g. "Assisted only (clicked out): 37 of 64 added to cart (57.8%)"; the grey remainder reads "Did not reach this stage: N of M players". - Purchase Funnel: the Purchased bar was painted entirely Direct blue, hiding Assisted buyers. Draw its Direct / Assisted split from the new purchased.direct / purchased.assisted the service sends (godam-analytics fix/funnel-purchased-tier-split); an older service without the split still gets a single segment rather than a guessed tier. - Dashboard head: "Analytics docs ↗" link to https://godam.io/docs/godam-analytics/ next to the Reel Pop link. - Top Videos / Top Products: the truncated title cell carries the full name as a hover title. * fix(dashboard): show full Top Videos / Top Products titles in a WP Tooltip on hover The truncated title cell now uses the same @wordpress/components Tooltip as the funnel segments (portalled, styled, keyboard-reachable) instead of a native title attribute, so the full name is readable and consistent. * fix(dashboard): use a native title tooltip for truncated Top Videos / Top Products names The WP Tooltip does not reliably open on the table title cells (the tables re-render periodically, which resets its show delay), so the truncated cell carries the full name as a native title attribute instead: no timers, no clipping, works with keyboard focus on the link. * fix(dashboard): decode HTML entities in Top Videos / Top Products titles The proxy returns texturized titles (e.g. "–"), which the tables and their new title tooltips rendered literally. Decode with @wordpress/html-entities (a WP core script, added as a dependency) for both the cell text and the title attribute. * fix(analytics): decode img alt entities; drop zero-count funnel segments Review follow-ups (#2134): - TopVideosTable: the two <img alt> still received the raw title, so a screen reader read "Swimming Lesson – 3" while the visible text and title attribute were decoded. Wrap both in decodeEntities(), same as the rest. - PurchaseFunnelCard: a zero-count tier rendered a width:0% segment that was still tabIndex=0 with an aria-label, so keyboard users tabbed onto invisible targets announcing "0 of N". Filter segments to frac > 0 before the map. Test added (verified to fail against the unfiltered code): a funnel with a zero-count Direct and a zero-count Assisted renders neither phantom segment, while the nonzero tiers still render. Suite 15 pass, lint clean.
On a page whose only GoDAM content is an Image block, nothing created
window.analytics: only the video-player bundle does. The layer-analytics
runtime and godam-for-woo's in-image add-to-cart both read
window.analytics.user().anonymousId, so every image-page event carried an
empty user_token, and the add-on refused to stamp Direct attribution on the
cart line, so the sale's revenue was lost.
The runtime now creates a minimal instance when none exists: the same
analytics library the player bundles, the same app name
('analytics-cdp-plugin') and no plugins. It reads or stores the visitor id
under the key the player reads (__anon_id), so a visitor keeps one id
across image and video pages. It never replaces an existing
window.analytics, and the player's own assignment still takes over when its
bundle runs later on the page. With no plugins it has nowhere to send
anything, and nothing calls page() or track() on it.
The library is bundled rather than taken from the global analytics.min.js.
In a block theme the Image block renders before wp_enqueue_scripts, so the
runtime prints before that global and would need a new script dependency,
and the bundled copy is the exact version the player ships. Cost:
godam-layer-analytics.min.js grows from 8 KB to 40 KB (3.5 KB to 14 KB
gzipped); the player bundle is unchanged.
fetch_top_products fired rtgodam_before_attachment_lookup before its whole hydration loop, so wc_get_product(), get_permalink(), the product's type/name/image id and wc_placeholder_img_src() all ran inside the pair. A media-centralizing plugin (e.g. wp-dam on multisite) switches to the media site there, so on such networks the products were looked up on the wrong site and came back as deleted rows with no permalink. The product fields are now read first, on the shop site, and each product's image id is kept. Only the wp_get_attachment_image_url() calls for those ids run inside the pair, still wrapped once around the loop rather than per product. Rows hydrate exactly as before on a single site. Tests stub a network that switches site inside the pair and assert where each lookup ran and what each row contains.
- Define Direct and Assisted as the code counts them. Assisted needs a click on the product before the product-page add; watching alone earns no credit. - Describe per-hotspot revenue as in-video (Direct) revenue, which is what the layer panel shows once godam-analytics#334 is deployed. - Say what the GA4 widget shows: GoDAM for Woo events pushed to the dataLayer, not a GA4 connection. - Use the UI names "Video to Cart" and "Video to Purchase", and say Top Products shows where each product appeared. - Date v2.3.0 for the release day, September 24, 2026. - Restore the v2.2.4 entry that shipped on main on September 21. The readme keeps three entries, so v2.2.2 drops out of readme.txt. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
elifvish
left a comment
There was a problem hiding this comment.
Review: approved content. I reviewed 674beb6 and re-checked the merge on b96faa2 (#2140 only changed the changelog), and the same 8 files conflict. Before merge, #2074 needs the develop merge resolved and three CI fixes.
I merged develop into this branch locally both ways, and both give the same 8 conflicting files:
- (a) as is
- (b) in the planned order: #2137 into develop, #2139 into feat/top-products, then develop into feat/top-products
Conflict resolution:
| # | File | Resolution |
|---|---|---|
| 1 | class-analytics.php /analytics/fetch |
take develop's array( $this, 'check_analytics_read_permission' ) |
| 2 | class-analytics.php /analytics/dashboard-metrics |
take develop's |
| 3 | class-analytics.php /analytics/layer-analytics |
take develop's; drop the stale "locking down should be uniform" comments |
| 4 | godam.php header and RTGODAM_VERSION |
keep 2.3.0 |
| 5 | package.json / package-lock.json |
keep 2.3.0; keep develop's #2131 Dependabot overrides (they auto-merge) |
| 6 | README.md / readme.txt stable tag |
keep 2.3.0 |
| 7 | CHANGELOG.md / readme.txt changelog |
keep this branch's side: after #2140 it already lists v2.3.0, v2.2.4 and v2.2.3 |
| 8 | languages/godam.pot |
keep 2.3.0, then regenerate the whole file (item 3 below) |
The history and dashboard-history routes are __return_true on feat, and they pick up #2138's check without a conflict.
The merge doesn't flag the four new routes. They merge cleanly and keep their own closures (see inline). After resolving everything, including those four:
- 0
__return_trueremain. - Exactly one
current_user_can( 'upload_files' )remains, insidecheck_analytics_read_permission(). - All 10 routes use the shared check.
Checks on the merged result:
php -land PHPCS are clean.- The permission and Top Products tests pass (9 tests, 104 assertions), and the permission test covers all 10 routes.
- Mutation check: setting
top-productsback to__return_truemakesAnalyticsRoutePermissionTestfail. - Jest (en_US): 442/442.
build:prodandlint:godam-hooksare clean.
CI will go red once this stops conflicting. PHP Unit and the POT check only run for PRs into develop, so they haven't run on this branch yet.
- PHPUnit: 4 failures in
AnalyticsProxyBodyGuardTest(see inline ontests/bootstrap.php). They also fail on feat/top-products today. - Jest depends on the locale.
TopProductsTable.test.js:171expects£12.34, but under en_AU it getsGBP 12.34, andDateRangePicker/index.test.js:111fails the same way outside en_US. Pin the locale in the Jest setup. languages/godam.potis stale. A freshnpm run build:prod && composer potadds about 1,400 lines and removes about 490: new Revenue and Top Products strings, plus moved references. Regenerate it after the resolution commit, from a checkout directory namedgodam.
Order: merge #2137 first. If develop goes in while it still has #2130, #2130's +75 lines in class-godam-player.php ship in 2.3.0 untested and without a changelog entry. With #2137 merged first, that file doesn't change.
| // Admin-dashboard read, gated like top-videos (authors and above); | ||
| // the search path resolves an uncached WP_Query, so this also | ||
| // closes the unauthenticated DB-amplification vector. | ||
| 'permission_callback' => function () { |
There was a problem hiding this comment.
Major (fix in the merge): the four new routes don't use #2138's shared check, and the merge won't flag them.
top-products (here), placement-funnels (L349), revenue-summary (L369) and video-funnel (L388) are in parts of the file develop never touched. So they merge cleanly and keep their own current_user_can( 'upload_files' ) closures.
It's the same capability, so nothing is bypassed today. But if check_analytics_read_permission() is tightened later, the revenue routes would silently stay on upload_files. test_no_route_is_public only asserts "callable and not __return_true", so it wouldn't catch that.
Fix: in the develop-merge commit, set 'permission_callback' => array( $this, 'check_analytics_read_permission' ), on all four. Optionally, have the test assert that every analytics route's callback is exactly that method. With that assertion, reverting top-products to a closure or __return_true fails the test.
| 'callback' => array( $this, 'fetch_revenue_summary' ), | ||
| // Admin-dashboard read; gated like the sibling analytics routes | ||
| // (revenue must not be readable without auth). | ||
| 'permission_callback' => function () { |
There was a problem hiding this comment.
Minor (access policy, not blocking): upload_files includes the Author role. isWoo only hides the Revenue and Top Products tabs in the UI; this route still answers any Author with a REST nonce. The same applies to top-products, the funnels and dashboard-metrics. For comparison, WooCommerce limits its own reports to view_woocommerce_reports.
Scenario: a guest author calls /wp-json/godam/v1/analytics/revenue-summary from the browser console and sees store revenue.
#2138 chose upload_files on purpose, so this is a policy call. Two options:
- Add a revenue-only check (
upload_filesplusview_woocommerce_reports) as a follow-up. - Or record the decision.
| */ | ||
| require_once __DIR__ . '/stubs/hooks.php'; | ||
| require_once __DIR__ . '/stubs/i18n.php'; | ||
| // HTTP / REST stubs for the Analytics microservice-proxy tests (fetch_top_videos |
There was a problem hiding this comment.
Major (CI): this require is silently a no-op for the HTTP stubs, and 4 AnalyticsProxyBodyGuardTest tests fail.
bootstrap.php L262-297 (from #2127) already defines wp_remote_get, wp_remote_retrieve_response_code and wp_remote_retrieve_body. Those read $GLOBALS['rtgodam_stub']['remote_code' | 'remote_body']. The versions in stubs/wp-http-functions.php read ['http'], but their function_exists guards skip them.
AnalyticsProxyBodyGuardTest sets ['http'], so these fail:
test_fetch_top_videos_accepts_a_valid_json_bodytest_fetch_placement_funnels_treats_non_2xx_as_error- the two
…_sets_bad_request_error_type_on_400tests
They fail on feat/top-products today and will fail in develop's PHP Unit workflow.
Fix: use one stub convention. Either make the test set remote_code / remote_body, or make the bootstrap stubs fall back to ['http'].
* fix: correct 2.3.0 copy and two broken godam.io links - Influenced tooltip and box text: describe what the analytics service computes. Influenced is a subset of Direct/Assisted sales where the same shopper also played a video on the product page, so it overlaps the headline and is never added to it. - Finish the Conversion to Interaction rename in the hotspot rail tooltips and the Media Editor Layer CTR tooltip. - Onboarding terms link: /terms/ returns 404; the page is /tos/. - Help page: /docs/dam/how-tos/ returns 404; point it and the Interface link at the current Media Library Manager docs. - readme.txt and README.md: the free trial is 60 days (as the onboarding screen says), and the viewer retention curve replaced heatmaps in 2.1.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * revert: keep the original Influenced tooltip rtCamp/godam-for-woo#213 and rtCamp/godam-analytics#337 redefine Influenced as its own type=8 order lines: a shopper-started play on the product page, then an add there, with no Direct or Assisted credit. The original tooltip and box text describe that behaviour, so the rewrite in the previous commit would contradict it. Leave RevenueCard.js as it was on feat/top-products. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up on #2139: previews and admin pages send nothing, so the fallback analytics instance is created only when shouldSkipAnalytics() is false.
… revenue; Top Products outside the media-site switch (#2139) * fix(analytics): create window.analytics on image-only pages On a page whose only GoDAM content is an Image block, nothing created window.analytics: only the video-player bundle does. The layer-analytics runtime and godam-for-woo's in-image add-to-cart both read window.analytics.user().anonymousId, so every image-page event carried an empty user_token, and the add-on refused to stamp Direct attribution on the cart line, so the sale's revenue was lost. The runtime now creates a minimal instance when none exists: the same analytics library the player bundles, the same app name ('analytics-cdp-plugin') and no plugins. It reads or stores the visitor id under the key the player reads (__anon_id), so a visitor keeps one id across image and video pages. It never replaces an existing window.analytics, and the player's own assignment still takes over when its bundle runs later on the page. With no plugins it has nowhere to send anything, and nothing calls page() or track() on it. The library is bundled rather than taken from the global analytics.min.js. In a block theme the Image block renders before wp_enqueue_scripts, so the runtime prints before that global and would need a new script dependency, and the bundled copy is the exact version the player ships. Cost: godam-layer-analytics.min.js grows from 8 KB to 40 KB (3.5 KB to 14 KB gzipped); the player bundle is unchanged. * fix(analytics): look up Top Products outside the media-site switch fetch_top_products fired rtgodam_before_attachment_lookup before its whole hydration loop, so wc_get_product(), get_permalink(), the product's type/name/image id and wc_placeholder_img_src() all ran inside the pair. A media-centralizing plugin (e.g. wp-dam on multisite) switches to the media site there, so on such networks the products were looked up on the wrong site and came back as deleted rows with no permalink. The product fields are now read first, on the shop site, and each product's image id is kept. Only the wp_get_attachment_image_url() calls for those ids run inside the pair, still wrapped once around the loop rather than per product. Rows hydrate exactly as before on a single site. Tests stub a network that switches site inside the pair and assert where each lookup ran and what each row contains. * fix(analytics): create no visitor id on pages that send no analytics Review follow-up on #2139: previews and admin pages send nothing, so the fallback analytics instance is created only when shouldSkipAnalytics() is false.
|
Follow-up check (head 1b3ead3) #2137 is merged into develop, and #2139 is merged here, so the next step is merging develop into this branch. I re-ran that merge locally on the current heads. It gives the same 8 conflicting files as before: My three points from that review have no replies yet, so here they are for the merge commit:
Author access to revenue (the |
Brings in develop since 2.2.4, including the WP Bakery revert (#2137) and the shared analytics read check (#2138). Conflicts resolved: - inc/classes/rest-api/class-analytics.php: every analytics route uses check_analytics_read_permission(). That includes top-products, placement-funnels, revenue-summary and video-funnel, which merged without a conflict and still had their own closures. - godam.php, package.json, package-lock.json, README.md, readme.txt: keep 2.3.0, and keep develop's dependency overrides (#2131). - CHANGELOG.md and the readme.txt changelog: keep this branch's v2.3.0, v2.2.4 and v2.2.3 entries. - languages/godam.pot: keep 2.3.0; regenerated in a later commit. Committed without the pre-commit hook: its PHPCS run fails only on develop's unchanged test stubs in tests/bootstrap.php (the same 7 errors as on develop). The next commit fixes them.
- tests/bootstrap.php defines wp_remote_get(), the two wp_remote_retrieve_*() helpers and is_wp_error() first, so the copies in tests/stubs/wp-http-functions.php never loaded and 4 AnalyticsProxyBodyGuardTest tests failed. The bootstrap stubs now also read a whole fake response from $GLOBALS['rtgodam_stub']['http'], and the unused copies are removed. PHPUnit: 124 pass. - The test:unit script sets LC_ALL and LANG to en_US.UTF-8. formatRevenue() and the date-range labels format with the machine's locale, so the TopProductsTable and DateRangePicker tests failed on other locales (6 failures under en_AU). Jest: 443 pass under en_AU. - The WP_Error, WP_REST_Response and WP_REST_Server test stubs pass PHPCS.
A fresh production build plus composer pot, from a checkout named godam: 269 strings added and 126 removed (the Revenue and Top Products screens, the 2.3.0 copy changes and moved references).
|
Develop is merged in (
The rest follows your resolution table: 2.3.0 everywhere, develop's #2131 overrides kept, and this branch's changelog entries kept. |
Summary
Adds the dashboard UI for WooCommerce Phase 2 revenue analytics (issue rtCamp/godam-plugin-wp#26): Video-Attributed Revenue, Top Products, and the shopping funnels. This is the frontend counterpart to the analytics-service work in rtCamp/godam-analytics#248; together they surface, per store, the order value traced back to the video that earned it.
What is included
add_to_cart/purchaseevents sent for video-driven sales, and flags when an existing GA4 integration on the store already covers those events.{error:true}marker and hard RTK errors both handled) instead of collapsing the whole Insights section, matching the service'sunavailable_sectionsresponse.Companion PRs
Revenue only works end to end with all three. The analytics service (rtCamp/godam-analytics#248) is already merged and live in production, so only this UI and the Woo emitter (rtCamp/godam-for-woo#194) remain to ship. Without the service this UI shows the commerce sections with no data (and degrades gracefully).
How to test
Automation impact
New data-test-ids on the added components (revenue card, funnels, Top Products table rows/notes/pagination/export) for E2E selection. No existing test-ids removed or renamed.
Notes
woocommerce_currency); other-currency orders are excluded and counted separately. Non-Woo installs omit the currency and the revenue sections stay empty by design./dashboard/metrics/fetch/, an empty date range now returns a zeroed metrics object instead ofnull, andunique_viewersdefaults to0(notnull) when a section is unavailable, with the failed section named inunavailable_sections.Release prep (v2.3.0)
This branch now carries the v2.3.0 release prep (
067bbf1f5), so merging it ships the version bump too:Stable tag2.2.3 -> 2.3.0 inreadme.txtandREADME.mdreadme.txtandCHANGELOG.md; the oldest entry (v2.2.1) drops out ofreadme.txtso it keeps threeVersionheader andRTGODAM_VERSIONingodam.phppackage.json/package-lock.jsonProject-Id-Versionheader inlanguages/godam.potNo
@since n.e.x.tplaceholders remained in this repo. Tracking ticket: rtCamp/godam-plugin-wp#41.Develop merged in (24 Sep)
4a2da3630merges develop (2.2.4, #2131, #2137, #2138) into this branch, following the review's resolution table. Every analytics route usescheck_analytics_read_permission(), including the four new ones (top-products,placement-funnels,revenue-summary,video-funnel). Two follow-up commits:644f20bc7(one set ofwp_remote_*test stubs, Jest locale pinned to en_US) and6327b73e7(regenerated POT). Locally: PHPUnit 124 pass, Jest 443 pass (also under en_AU), POT check passes, hook integrity clean.