diff --git a/projects/packages/premium-analytics/AGENTS.md b/projects/packages/premium-analytics/AGENTS.md index d7115adea223..b2445893a18e 100644 --- a/projects/packages/premium-analytics/AGENTS.md +++ b/projects/packages/premium-analytics/AGENTS.md @@ -465,13 +465,17 @@ module has a special failure mode. Prefer adding those shapes to the widget's ex over creating one-off state stories unless the state needs direct review. To review a widget's loading / error / empty state directly, force it with -`setReportMockState( '', 'loading' | 'error' | 'empty' )` in the story's `beforeEach`, -clearing it in the returned cleanup. Keep such stories off the shared autodocs page -(`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise force the -sibling stories into the same state) and give each one a date preset distinct from the other -stories so it hits the mock fresh instead of reading their cached success. See +`setReportMockState( '', 'loading' | 'error' | 'error-retryable' | 'empty' )` in the +story's `beforeEach`, clearing it in the returned cleanup. Keep such stories off the shared +autodocs page (`tags: [ '!autodocs' ]`, since the override is keyed by path and would otherwise +force the sibling stories into the same state) and give each one a date preset distinct from the +other stories so it hits the mock fresh instead of reading their cached success. See `widgets/search-terms/stories/` for the reference. +`error` mocks a permission-gated 403 and `error-retryable` the proxy's `no_connection` 403. A +widget that maps its error through `describeError` renders a Retry action only for the latter, so +give it a story for each; both mocks are 403s, so neither waits out the query's retry backoff. + ### Widget pitfalls - Putting new widgets under `packages/widgets-toolkit/src/widgets/*` — that path is for the @@ -544,7 +548,11 @@ default. `widgets/subscribers-list/render.tsx` is the current example: its Render these states through `` from `@jetpack-premium-analytics/widgets-toolkit` rather than hand-rolling `if ( isError )` / empty branches or a `WidgetLoadingOverlay`. Map the -data/view hook's result to its four signals and pass generic descriptors: +data/view hook's result to its four signals. For Stats API errors, pass the raw `error` to the +shared `describeError()` mapper so 403 access failures have neutral copy and no retry action, +while other failures — including the proxy's `no_connection` 403, which can heal after +reconnecting — offer Retry. Pass the retryable copy as a full sentence (not a fragment +interpolated into a shared frame) so translators see the whole sentence: ```tsx @@ -567,6 +575,9 @@ data/view hook's result to its four signals and pass generic descriptors: `isFetching` and data are shown) and swaps only the content area. Notes: - Expose `refetch` from the data/view hook so the error state's Retry can re-run the query. +- When a view hook masks `isError` (e.g. `rows.length === 0 && isError` to keep placeholder + rows), gate `error` with the same predicate (`error: showError ? error : null`) so the two + fields can't disagree. - Give `empty.icon` a neutral glyph distinct from the error icon — the widget's own glyph from `@jetpack-premium-analytics/icons` (e.g. `search`, `customer`); omit it for no icon. Don't use a caution glyph: empty is not an error. @@ -578,8 +589,8 @@ data/view hook's result to its four signals and pass generic descriptors: > Many Stats widgets predate this and still hand-roll loading/empty via ``, > `isLoading && data.length === 0`, and `LeaderboardChart`'s `emptyStateText`. They are being > migrated to `` — follow the contract above, not those widgets. -> `widgets/search-terms/render.tsx` is the reference. (A `describeError` mapper and a -> `ReportWidget` wrapper that remove the per-widget error/retry boilerplate are planned follow-ups.) +> `widgets/search-terms/render.tsx` is the reference. (A `ReportWidget` wrapper that removes the +> remaining per-widget state boilerplate is a planned follow-up.) **Comparison data** diff --git a/projects/packages/premium-analytics/changelog/fix-stats-api-error-status b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status new file mode 100644 index 000000000000..4c29fc876993 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/fix-stats-api-error-status @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +Stats: Stop retrying unavailable reports and show authentication and server errors correctly. diff --git a/projects/packages/premium-analytics/changelog/wooa7s-1649 b/projects/packages/premium-analytics/changelog/wooa7s-1649 new file mode 100644 index 000000000000..0e9700489ed6 --- /dev/null +++ b/projects/packages/premium-analytics/changelog/wooa7s-1649 @@ -0,0 +1,4 @@ +Significance: patch +Type: changed + +Use consistent access and retry error states across Stats widgets. diff --git a/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts new file mode 100644 index 000000000000..2d95d58d8707 --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/api/__tests__/error-status-middleware.test.ts @@ -0,0 +1,235 @@ +/** + * The middleware branches on `instanceof Response`, so it needs the real + * WHATWG `Response`. The shared jsdom environment does not provide one. + * + * @jest-environment node + */ + +/** + * External dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +/** + * Internal dependencies + */ +import { + apiErrorStatusMiddleware, + registerApiErrorStatusMiddleware, +} from '../error-status-middleware'; + +function jsonResponse( body: unknown, status: number ): Response { + return new Response( JSON.stringify( body ), { + status, + headers: { 'Content-Type': 'application/json' }, + } ); +} + +/** + * A `next` that behaves like apiFetch's own chain under `parse: false`: it + * resolves the raw `Response` for a 2xx and rejects with the raw `Response` + * for a non-2xx (see `parseAndThrowError` in `@wordpress/api-fetch`). Error + * tests that resolve a failed response instead would exercise a branch the + * real chain never reaches. + */ +function runResponse( response: Response, options: Record< string, unknown > = {} ) { + const next = jest.fn( () => + response.ok ? Promise.resolve( response ) : Promise.reject( response ) + ); + return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; +} + +function runResolved( value: unknown, options: Record< string, unknown > = {} ) { + const next = jest.fn().mockResolvedValue( value ); + return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; +} + +function runRejected( value: unknown, options: Record< string, unknown > = {} ) { + const next = jest.fn().mockRejectedValue( value ); + return { next, result: apiErrorStatusMiddleware( { path: '/x', ...options }, next ) }; +} + +describe( 'apiErrorStatusMiddleware', () => { + it( 'attaches the HTTP status to a rejected non-2xx error body', async () => { + const { result } = runResponse( + jsonResponse( { error: 'unauthorized', message: 'Nope.' }, 401 ) + ); + + await expect( result ).rejects.toEqual( { + error: 'unauthorized', + message: 'Nope.', + status: 401, + } ); + } ); + + it.each( [ 502, 503, 504 ] )( 'attaches a %d server status', async status => { + const { result } = runResponse( + jsonResponse( { error: 'api_error', message: 'Upstream.' }, status ) + ); + + await expect( result ).rejects.toMatchObject( { status } ); + } ); + + it( 'keeps the status when a non-2xx body is not JSON (gateway HTML/text)', async () => { + // A 502/503/504 page is commonly HTML; parsing throws invalid_json, but + // the status must still reach the server-error UI and the retry guard. + const { result } = runResponse( + new Response( '502 Bad Gateway', { status: 502 } ) + ); + + await expect( result ).rejects.toEqual( { + code: 'invalid_json', + message: 'The response is not a valid JSON response.', + status: 502, + } ); + } ); + + it( 'does not overwrite a status the body already provides at the top level', async () => { + const { result } = runResponse( jsonResponse( { code: 'rest_forbidden', status: 403 }, 500 ) ); + + await expect( result ).rejects.toEqual( { code: 'rest_forbidden', status: 403 } ); + } ); + + it( 'leaves a WP_Error data.status alone while adding the top-level status', async () => { + const { result } = runResponse( + jsonResponse( { code: 'rest_forbidden', message: 'Sorry.', data: { status: 403 } }, 403 ) + ); + + await expect( result ).rejects.toEqual( { + code: 'rest_forbidden', + message: 'Sorry.', + data: { status: 403 }, + status: 403, + } ); + } ); + + it( 'throws a non-object JSON error body as-is without attaching status', async () => { + // `isPlainErrorBody` exists so `status` is never spread into arrays, + // strings, or null — spreading an array would mangle it into an object. + const { result } = runResponse( jsonResponse( [ 'boom' ], 500 ) ); + + await expect( result ).rejects.toEqual( [ 'boom' ] ); + } ); + + it( 'throws a JSON string error body as-is', async () => { + const { result } = runResponse( jsonResponse( 'boom', 502 ) ); + + await expect( result ).rejects.toBe( 'boom' ); + } ); + + it( 'rethrows a non-Response rejection untouched (offline / fetch / abort)', async () => { + // apiFetch rejects offline and network failures with a bare + // `{ code, message }` and no Response; there is no status to add. + const offline = { code: 'offline_error', message: 'Unable to connect.' }; + const { result } = runRejected( offline ); + + await expect( result ).rejects.toBe( offline ); + } ); + + it( 'returns null for a 204 response', async () => { + const { result } = runResponse( new Response( null, { status: 204 } ) ); + + await expect( result ).resolves.toBeNull(); + } ); + + it( 'parses a successful JSON response', async () => { + const { result } = runResponse( jsonResponse( { ok: true }, 200 ) ); + + await expect( result ).resolves.toEqual( { ok: true } ); + } ); + + it( 'throws the invalid_json shape when a successful body is not JSON', async () => { + const { result } = runResponse( new Response( 'not json', { status: 200 } ) ); + + await expect( result ).rejects.toEqual( { + code: 'invalid_json', + message: 'The response is not a valid JSON response.', + } ); + } ); + + it( 'passes the raw Response through untouched when the caller set parse: false', async () => { + const response = jsonResponse( { error: 'nope' }, 500 ); + const { next, result } = runResolved( response, { parse: false } ); + + await expect( result ).resolves.toBe( response ); + expect( next ).toHaveBeenCalledWith( { path: '/x', parse: false } ); + } ); + + it( 'returns a non-Response value from next() unchanged', async () => { + const mocked = { data: [ 1, 2, 3 ] }; + const { result } = runResolved( mocked ); + + await expect( result ).resolves.toBe( mocked ); + } ); + + it( 'leaves unbounded per_page=-1 queries to apiFetch so fetchAllMiddleware still paginates', async () => { + const mocked = [ { id: 1 } ]; + const { next, result } = runResolved( mocked, { path: '/wp/v2/thing?per_page=-1' } ); + + await expect( result ).resolves.toBe( mocked ); + expect( next ).toHaveBeenCalledWith( { path: '/wp/v2/thing?per_page=-1' } ); + } ); + + it( 'leaves unbounded per_page=-1 url-based queries to apiFetch as well', async () => { + const url = 'https://example.com/wp-json/wp/v2/thing?per_page=-1'; + const mocked = [ { id: 1 } ]; + const { next, result } = runResolved( mocked, { url } ); + + await expect( result ).resolves.toBe( mocked ); + expect( next ).toHaveBeenCalledWith( { path: '/x', url } ); + } ); + + it( 'forces parse: false on the request it forwards', async () => { + const { next } = runResponse( jsonResponse( { ok: true }, 200 ), { method: 'POST' } ); + + await Promise.resolve(); + expect( next ).toHaveBeenCalledWith( { path: '/x', method: 'POST', parse: false } ); + } ); +} ); + +describe( 'registerApiErrorStatusMiddleware', () => { + it( 'registers with apiFetch only once across repeated calls', () => { + const use = jest.spyOn( apiFetch, 'use' ).mockImplementation( () => {} ); + + try { + registerApiErrorStatusMiddleware(); + registerApiErrorStatusMiddleware(); + + expect( use ).toHaveBeenCalledTimes( 1 ); + expect( use ).toHaveBeenCalledWith( apiErrorStatusMiddleware ); + } finally { + use.mockRestore(); + } + } ); + + it( 'skips registration when the apiFetch instance exposes no use()', async () => { + // Suites that mock `@wordpress/api-fetch` with a bare function get such an + // instance, and this runs at module scope in the data package. + await jest.isolateModulesAsync( async () => { + const isolatedApiFetch = ( await import( '@wordpress/api-fetch' ) ).default as unknown as + | Record< string, unknown > + | undefined; + const original = isolatedApiFetch?.use; + delete isolatedApiFetch?.use; + + try { + const middleware = await import( '../error-status-middleware' ); + + expect( isolatedApiFetch?.use ).toBeUndefined(); + expect( () => middleware.registerApiErrorStatusMiddleware() ).not.toThrow(); + + // Skipping must not latch: a later call on a usable instance still registers. + const use = jest.fn(); + if ( isolatedApiFetch ) { + isolatedApiFetch.use = use; + } + middleware.registerApiErrorStatusMiddleware(); + + expect( use ).toHaveBeenCalledWith( middleware.apiErrorStatusMiddleware ); + } finally { + if ( isolatedApiFetch ) { + isolatedApiFetch.use = original; + } + } + } ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts new file mode 100644 index 000000000000..f0ef142a8605 --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/api/error-status-middleware.ts @@ -0,0 +1,132 @@ +/** + * External dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +import { __ } from '@wordpress/i18n'; +import type { APIFetchMiddleware } from '@wordpress/api-fetch'; + +/** + * apiFetch's own parse step throws the parsed JSON body and drops the `Response`, + * so the HTTP status is lost. Most Premium Analytics failures are WPCOM + * pass-throughs shaped `{ error, message }` with no status in the body, which + * leaves the data layer unable to tell a 401 from a 502. This middleware takes + * over parsing to keep the status on the thrown error. + * + * The parse semantics below intentionally mirror `parseResponseAndNormalizeError` + * / `parseAndThrowError` in `@wordpress/api-fetch`. + */ + +async function parseJsonAndNormalizeError( response: Response ): Promise< unknown > { + try { + return await response.json(); + } catch { + // Same shape apiFetch throws. The string is core's — translating it under + // this package's domain would hand non-English users a different message + // for the identical failure, so it stays on the `default` domain. + throw { + code: 'invalid_json', + // eslint-disable-next-line @wordpress/i18n-text-domain + message: __( 'The response is not a valid JSON response.', 'default' ), + }; + } +} + +function isPlainErrorBody( body: unknown ): body is Record< string, unknown > { + return typeof body === 'object' && body !== null && ! Array.isArray( body ); +} + +/** + * Turn a rejected error `Response` into the thrown error the caller expects, + * with the HTTP status attached. + * + * The body of a gateway failure (502/503/504) is often HTML or plain text, so + * parsing can itself fail. Either way the status must survive: it is what the + * server-error UI and the retry guard key off. On a parse failure we keep + * apiFetch's own `invalid_json` shape and still attach the status. + */ +async function normalizeErrorResponse( response: Response ): Promise< unknown > { + const { status } = response; + + let body: unknown; + try { + body = await parseJsonAndNormalizeError( response ); + } catch ( parseError ) { + body = parseError; + } + + // Our own `WP_Error` responses carry `data.status`; adding a top-level + // `status` is fine, but never overwrite one the body already provides. + if ( isPlainErrorBody( body ) && ! ( 'status' in body ) ) { + return { ...body, status }; + } + + return body; +} + +function containsUnboundedQuery( options: { path?: string; url?: string } ): boolean { + return !! options.path?.includes( 'per_page=-1' ) || !! options.url?.includes( 'per_page=-1' ); +} + +export const apiErrorStatusMiddleware: APIFetchMiddleware = async ( options, next ) => { + // The caller wants the raw `Response` (e.g. the CSV export download), so + // apiFetch's own pass-through behavior is already what they get. + if ( options.parse === false ) { + return next( options ); + } + + // apiFetch always keeps its built-in middlewares innermost, so this one + // necessarily wraps `fetchAllMiddleware` — and that middleware bails out on + // `parse: false`. Forcing parse off here would silently disable `per_page=-1` + // pagination (which the dashboard uses to enumerate widget modules), so leave + // unbounded queries to apiFetch's own handling. + if ( containsUnboundedQuery( options ) ) { + return next( options ); + } + + let result: unknown; + try { + result = await next( { ...options, parse: false } ); + } catch ( thrown ) { + // With `parse: false`, apiFetch throws the raw `Response` for a non-2xx + // reply rather than returning it (see `parseAndThrowError`). This catch + // is where every real API error lands. Anything that is not a + // `Response` — an offline/fetch error, an `AbortError`, a mock's own + // rejection — has no HTTP status to add, so rethrow it untouched. + if ( thrown instanceof Response ) { + throw await normalizeErrorResponse( thrown ); + } + throw thrown; + } + + // A resolved value that is not a `Response` means a middleware outside this + // one short-circuited with already-parsed data — Storybook's report mocks + // do exactly that. A resolved `Response` is always 2xx: apiFetch only + // throws (never resolves) a non-ok one. + if ( ! ( result instanceof Response ) ) { + return result; + } + + if ( result.status === 204 ) { + return null; + } + + return parseJsonAndNormalizeError( result ); +}; + +// apiFetch middleware registers onto a shared, process-wide chain, so guard +// against a second registration from a re-mount or HMR. +let registered = false; + +export function registerApiErrorStatusMiddleware(): void { + if ( registered ) { + return; + } + // Unit tests replace the whole apiFetch module with a bare `jest.fn()`, which + // has no `use()`. This is called at module scope, so without the check every + // suite that renders a widget would fail to load. + if ( typeof apiFetch.use !== 'function' ) { + return; + } + registered = true; + apiFetch.use( apiErrorStatusMiddleware ); +} diff --git a/projects/packages/premium-analytics/packages/data/src/api/index.ts b/projects/packages/premium-analytics/packages/data/src/api/index.ts index 08dae2352ba7..82c7eca328c8 100644 --- a/projects/packages/premium-analytics/packages/data/src/api/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/api/index.ts @@ -41,6 +41,10 @@ export { fetchReportVisitors } from './report-visitors-fetch'; export { fetchReportVisitorsByLocation } from './report-visitors-by-location-fetch'; export { fetchReportBookings } from './report-bookings-fetch'; export { fetchReportSessionsByDevice } from './report-sessions-by-device-fetch'; +export { + apiErrorStatusMiddleware, + registerApiErrorStatusMiddleware, +} from './error-status-middleware'; export { downloadReport, exportReport } from './report-export-fetch'; export type { DownloadReportParams, diff --git a/projects/packages/premium-analytics/packages/data/src/index.ts b/projects/packages/premium-analytics/packages/data/src/index.ts index 7890e3341267..d5e0b3822b40 100644 --- a/projects/packages/premium-analytics/packages/data/src/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/index.ts @@ -241,13 +241,11 @@ export { computeDateRangeFromPreset, getApiErrorCode, getApiErrorStatus, - getStatsPlanErrorReason, saveBlob, shouldRetryApiError, toPostId, useSiteHomeUrl, } from './utils'; -export type { StatsPlanErrorReason } from './utils'; export type { ReportDataMap } from './types'; export type { ReportQueryParams } from './api'; export type { FilterCondition } from './types/filter-condition'; diff --git a/projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts b/projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts new file mode 100644 index 000000000000..54e36c64a009 --- /dev/null +++ b/projects/packages/premium-analytics/packages/data/src/providers/__tests__/query-client-provider.test.ts @@ -0,0 +1,21 @@ +/** + * External dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +/** + * Internal dependencies + */ +import { apiErrorStatusMiddleware } from '../../api/error-status-middleware'; + +jest.mock( '@wordpress/api-fetch', () => Object.assign( jest.fn(), { use: jest.fn() } ) ); + +describe( 'query-client-provider module', () => { + it( 'installs the error-status middleware when the data package loads', async () => { + // The app's `init()` module is not involved: WP 7.0's Core `boot` ignores + // the `initModules` argument to `initSinglePage()`, so anything registered + // only from `init()` never runs there. + await import( '../query-client-provider' ); + + expect( apiFetch.use ).toHaveBeenCalledWith( apiErrorStatusMiddleware ); + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx b/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx index 98e8b61a6d36..54002314e438 100644 --- a/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx +++ b/projects/packages/premium-analytics/packages/data/src/providers/query-client-provider.tsx @@ -6,9 +6,19 @@ import { ReactNode } from 'react'; /** * Internal dependencies */ +import { registerApiErrorStatusMiddleware } from '../api/error-status-middleware'; import { getApiErrorStatus, shouldRetryApiError } from '../utils'; import { globalErrorManager } from './global-error-manager'; +// Both the retry policy and the global error detection below read the HTTP +// status, which apiFetch drops unless this middleware is installed. Registering +// it here, next to the policy that needs it, rather than from the app's `init()` +// module: WP 7.0's Core `boot` module ignores the `initModules` argument to +// `initSinglePage()`, so on those sites `init()` never runs and the status was +// lost again (Core-side fix in #50309). Every widget and route mounts this +// provider, so loading the data package is enough to install the middleware. +registerApiErrorStatusMiddleware(); + const DEFAULT_STALE_TIME = 5 * 60 * 1000; const DEFAULT_GC_TIME = 10 * 60 * 1000; diff --git a/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts b/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts index 4723bd9a3dfc..318bf7347faf 100644 --- a/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts +++ b/projects/packages/premium-analytics/packages/data/src/utils/__tests__/api-error.test.ts @@ -1,17 +1,16 @@ -import { - getApiErrorCode, - getApiErrorStatus, - getStatsPlanErrorReason, - shouldRetryApiError, -} from '../api-error'; +import { getApiErrorCode, getApiErrorStatus, shouldRetryApiError } from '../api-error'; + +// Two envelopes reach the client: our own `WP_Error` responses +// (`{ code, message, data: { status } }`) and WPCOM pass-through errors +// (`{ error, message }`, with the status attached separately by the fetch layer). describe( 'getApiErrorStatus', () => { it( 'returns status from a top-level status property', () => { - expect( getApiErrorStatus( { status: 403 } ) ).toBe( 403 ); + expect( getApiErrorStatus( { error: 'unauthorized', status: 403 } ) ).toBe( 403 ); } ); it( 'returns status from WordPress REST error data', () => { - expect( getApiErrorStatus( { data: { status: 401 } } ) ).toBe( 401 ); + expect( getApiErrorStatus( { code: 'no_connection', data: { status: 401 } } ) ).toBe( 401 ); } ); it( 'returns status from a nested response object', () => { @@ -20,13 +19,24 @@ describe( 'getApiErrorStatus', () => { it( 'returns null when no numeric status is available', () => { expect( getApiErrorStatus( { data: { status: '403' } } ) ).toBeNull(); + expect( + getApiErrorStatus( { error: 'unauthorized', message: 'user cannot view stats' } ) + ).toBeNull(); expect( getApiErrorStatus( null ) ).toBeNull(); } ); } ); describe( 'getApiErrorCode', () => { - it( 'returns a top-level WordPress REST error code', () => { - expect( getApiErrorCode( { code: 'no_connection' } ) ).toBe( 'no_connection' ); + it( 'returns the code from a WP_Error envelope', () => { + expect( getApiErrorCode( { code: 'no_connection', data: { status: 403 } } ) ).toBe( + 'no_connection' + ); + } ); + + it( 'returns the code from a WPCOM pass-through envelope', () => { + expect( getApiErrorCode( { error: 'unauthorized', message: 'user cannot view stats' } ) ).toBe( + 'unauthorized' + ); } ); it( 'returns a nested data error code', () => { @@ -35,14 +45,30 @@ describe( 'getApiErrorCode', () => { it( 'returns null when no string code is available', () => { expect( getApiErrorCode( { code: 403 } ) ).toBeNull(); + expect( getApiErrorCode( { error: 403 } ) ).toBeNull(); expect( getApiErrorCode( null ) ).toBeNull(); } ); } ); describe( 'shouldRetryApiError', () => { - it( 'does not retry authentication or authorization errors', () => { - expect( shouldRetryApiError( 0, { status: 401 } ) ).toBe( false ); - expect( shouldRetryApiError( 0, { data: { status: 403 } } ) ).toBe( false ); + it( 'does not retry deterministic failures', () => { + expect( shouldRetryApiError( 0, { code: 'rest_forbidden', data: { status: 401 } } ) ).toBe( + false + ); + expect( + shouldRetryApiError( 0, { + error: 'unauthorized', + message: 'user cannot view stats', + status: 403, + } ) + ).toBe( false ); + expect( + shouldRetryApiError( 0, { + error: 'not_found', + message: 'The requested resource was not found.', + status: 404, + } ) + ).toBe( false ); } ); it( 'retries other errors up to three failures', () => { @@ -51,19 +77,3 @@ describe( 'shouldRetryApiError', () => { expect( shouldRetryApiError( 3, { status: 500 } ) ).toBe( false ); } ); } ); - -describe( 'getStatsPlanErrorReason', () => { - it( 'returns upgrade-required for plan-gated authorization errors', () => { - expect( getStatsPlanErrorReason( { data: { status: 403, code: 'rest_forbidden' } } ) ).toBe( - 'upgrade-required' - ); - } ); - - it( 'returns null for non-plan authorization errors', () => { - expect( getStatsPlanErrorReason( { status: 403, code: 'no_connection' } ) ).toBeNull(); - } ); - - it( 'returns null for non-authorization errors', () => { - expect( getStatsPlanErrorReason( { status: 500 } ) ).toBeNull(); - } ); -} ); diff --git a/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts b/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts index 5070d9dd0341..b2247d5e7481 100644 --- a/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts +++ b/projects/packages/premium-analytics/packages/data/src/utils/api-error.ts @@ -38,6 +38,9 @@ export function getApiErrorStatus( error: unknown ): number | null { /** * Extract an API error code from common WordPress REST error shapes. * + * WPCOM pass-through errors (every real Stats failure) put the code in `error`, + * while our own `WP_Error` responses use `code`. + * * @param error - Unknown thrown error. * @return Error code, or null when unavailable. */ @@ -52,6 +55,10 @@ export function getApiErrorCode( error: unknown ): string | null { return err.code; } + if ( typeof err.error === 'string' ) { + return err.error; + } + if ( err.data && typeof err.data === 'object' ) { const data = err.data as Record< string, unknown >; if ( typeof data.code === 'string' ) { @@ -62,30 +69,11 @@ export function getApiErrorCode( error: unknown ): string | null { return null; } -export type StatsPlanErrorReason = 'upgrade-required' | null; - -const NON_PLAN_FORBIDDEN_ERROR_CODES = new Set( [ 'no_connection' ] ); - -/** - * Maps Stats API errors to widget-level plan error reasons. - * - * @param error - Unknown thrown error. - * @return The plan error reason when the response is plan-gated. - */ -export function getStatsPlanErrorReason( error: unknown ): StatsPlanErrorReason { - const errorCode = getApiErrorCode( error ); - - return getApiErrorStatus( error ) === 403 && - ! NON_PLAN_FORBIDDEN_ERROR_CODES.has( errorCode ?? '' ) - ? 'upgrade-required' - : null; -} - /** * Determine whether a failed API query should be retried. * - * Authentication and authorization failures are deterministic for the current - * user/session, so retrying only delays the widget-specific error UI. + * Authentication, authorization and not-found failures are deterministic for the + * current user/session, so retrying only delays the widget-specific error UI. * * @param failureCount - Number of failed attempts so far. * @param error - Unknown thrown error. @@ -94,7 +82,7 @@ export function getStatsPlanErrorReason( error: unknown ): StatsPlanErrorReason export function shouldRetryApiError( failureCount: number, error: unknown ): boolean { const status = getApiErrorStatus( error ); - if ( status === 401 || status === 403 ) { + if ( status === 401 || status === 403 || status === 404 ) { return false; } diff --git a/projects/packages/premium-analytics/packages/data/src/utils/index.ts b/projects/packages/premium-analytics/packages/data/src/utils/index.ts index 21ef175b2222..238ddedcb00f 100644 --- a/projects/packages/premium-analytics/packages/data/src/utils/index.ts +++ b/projects/packages/premium-analytics/packages/data/src/utils/index.ts @@ -5,13 +5,7 @@ export { getSiteTimezone, getSiteGmtOffset, } from './date'; -export { - getApiErrorCode, - getApiErrorStatus, - getStatsPlanErrorReason, - shouldRetryApiError, -} from './api-error'; -export type { StatsPlanErrorReason } from './api-error'; +export { getApiErrorCode, getApiErrorStatus, shouldRetryApiError } from './api-error'; export { ensureCoreSettingsReady } from './ensure-core-settings'; export { getDefaultIntervalForPeriod } from './interval'; export { safeParseInt, safeParseFloat } from './parsing'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts new file mode 100644 index 000000000000..538b9fceeb48 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/__tests__/describe-error.test.ts @@ -0,0 +1,66 @@ +/** + * Internal dependencies + */ +import { describeError } from '../describe-error'; + +const RETRY_DESCRIPTION = "We couldn't load device data. Please try again in a moment."; + +describe( 'describeError', () => { + it( 'describes a 403 as a neutral error without actions', () => { + const descriptor = describeError( + { error: 'unauthorized', status: 403 }, + { retryDescription: RETRY_DESCRIPTION, onRetry: jest.fn() } + ); + + expect( descriptor ).toEqual( { + description: "You don't have access to this data.", + } ); + expect( descriptor ).not.toHaveProperty( 'actions' ); + } ); + + it( 'keeps a no_connection 403 retryable — a broken connection can heal', () => { + const onRetry = jest.fn(); + const descriptor = describeError( + { error: 'no_connection', status: 403 }, + { retryDescription: RETRY_DESCRIPTION, onRetry } + ); + + expect( descriptor.description ).toBe( RETRY_DESCRIPTION ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); + + it( 'describes a generic failure with the retryable copy and a retry action', () => { + const onRetry = jest.fn(); + const descriptor = describeError( + { status: 500 }, + { retryDescription: RETRY_DESCRIPTION, onRetry } + ); + + expect( descriptor.description ).toBe( RETRY_DESCRIPTION ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); + + it( 'keeps an unexpected 404 retryable', () => { + const onRetry = jest.fn(); + const descriptor = describeError( + { status: 404 }, + { retryDescription: RETRY_DESCRIPTION, onRetry } + ); + + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } ); + + it( 'returns the retryable descriptor when there is no error — widgets call it on every render', () => { + const onRetry = jest.fn(); + + for ( const noError of [ null, undefined ] ) { + const descriptor = describeError( noError, { + retryDescription: RETRY_DESCRIPTION, + onRetry, + } ); + + expect( descriptor.description ).toBe( RETRY_DESCRIPTION ); + expect( descriptor.actions ).toEqual( [ { label: 'Retry', onClick: onRetry } ] ); + } + } ); +} ); diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts new file mode 100644 index 000000000000..bc949f4ef762 --- /dev/null +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/describe-error.ts @@ -0,0 +1,51 @@ +/** + * External dependencies + */ +import { getApiErrorCode, getApiErrorStatus } from '@jetpack-premium-analytics/data'; +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; +/** + * Types + */ +import type { WidgetStateError } from '../components/widget-state'; + +interface DescribeErrorOptions { + retryDescription: string; + onRetry: () => void; +} + +/** + * Map an API error to a Stats widget error descriptor. + * + * A 403 is a deterministic access failure, so it gets neutral copy and no retry + * action — except the proxy's `no_connection` 403, which flags a broken Jetpack + * connection that can heal, so it stays retryable like any other failure. + * + * @param error - The failed query error. + * @param options - Error-state copy and retry options. + * @param options.retryDescription - The full-sentence copy for the retryable error state. + * @param options.onRetry - Callback used by the retry action. + * @return The widget error descriptor. + */ +export function describeError( + error: unknown, + { retryDescription, onRetry }: DescribeErrorOptions +): WidgetStateError { + if ( getApiErrorStatus( error ) === 403 && getApiErrorCode( error ) !== 'no_connection' ) { + return { + description: __( "You don't have access to this data.", 'jetpack-premium-analytics' ), + }; + } + + return { + description: retryDescription, + actions: [ + { + label: __( 'Retry', 'jetpack-premium-analytics' ), + onClick: onRetry, + }, + ], + }; +} diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts index cee8d40b53ed..2658bf5d8486 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/helpers/index.ts @@ -57,6 +57,7 @@ export { sharePercentage } from './share-percentage'; export { getCombinedPeriodMax } from './get-combined-period-max'; export { getVideoKey, getVideoLabel } from './video-plays'; export { toMaxRows } from './to-max-rows'; +export { describeError } from './describe-error'; export { summaryCount } from './summary-count'; export { toDay } from './to-day'; export { defaultPeriodForInterval } from './default-period-for-interval'; diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts index e82297b2a3b4..b2c88eeb6043 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/index.ts @@ -138,6 +138,7 @@ export { getVideoKey, getVideoLabel, toMaxRows, + describeError, summaryCount, toDay, defaultPeriodForInterval, diff --git a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts index 109b9adc0649..e87106fe6f2e 100644 --- a/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts +++ b/projects/packages/premium-analytics/packages/widgets-toolkit/src/stories/mocks/register-report-mocks.ts @@ -156,11 +156,13 @@ const requestCounters: Record< string, number > = {}; /** * Forced response state for a request path fragment, so stories can exercise a - * widget's loading, error, and empty UI. `error` rejects the request; `loading` - * returns a promise that never settles; `empty` resolves with a valid response - * that has no rows. + * widget's loading, error, and empty UI. `error` rejects the request with a + * permission-gated 403; `error-retryable` rejects it with the proxy's + * `no_connection` 403, which widgets on `describeError` render with a Retry + * action; `loading` returns a promise that never settles; `empty` resolves with + * a valid response that has no rows. */ -type ReportMockState = 'error' | 'loading' | 'empty'; +type ReportMockState = 'error' | 'error-retryable' | 'loading' | 'empty'; const mockStateOverrides = new Map< string, ReportMockState >(); @@ -1282,12 +1284,24 @@ const reportMocksMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio // (`summary` / `days` / `data`), so the widget resolves to its empty state. return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] }; } - // A 403 is not retried by `shouldRetryApiError`, so the error UI shows at - // once instead of after the query's retry backoff. + if ( state === 'error-retryable' ) { + // The local proxy's `no_connection` shape. Still a 403, so the error UI + // shows at once, but `describeError` keeps it retryable: a broken Jetpack + // connection can heal, unlike a permission gate. + return Promise.reject( { + code: 'no_connection', + message: 'Mocked connection failure for Storybook.', + data: { status: 403 }, + } ); + } + // The WPCOM pass-through error envelope, with the status attached the way + // the fetch layer attaches it. A 403 is not retried by `shouldRetryApiError`, + // so the error UI shows at once instead of after the query's retry backoff. + // Widgets on `describeError` read it as a permission gate and drop Retry. return Promise.reject( { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response for Storybook.', - data: { status: 403 }, + status: 403, } ); } diff --git a/projects/packages/premium-analytics/widgets/devices/render.tsx b/projects/packages/premium-analytics/widgets/devices/render.tsx index 20d0373b75ba..96d3295de328 100644 --- a/projects/packages/premium-analytics/widgets/devices/render.tsx +++ b/projects/packages/premium-analytics/widgets/devices/render.tsx @@ -9,6 +9,7 @@ import { device } from '@jetpack-premium-analytics/icons'; import { __ } from '@wordpress/i18n'; import { Legend, + describeError, SemiCircleChart, WidgetRoot, WidgetState, @@ -56,12 +57,11 @@ type DevicesInnerProps = { */ function DevicesInner( { max }: DevicesInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, errorReason, refetch } = - useDeviceViews( { - reportParams, - max, - deviceProperty: 'screensize', - } ); + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = useDeviceViews( { + reportParams, + max, + deviceProperty: 'screensize', + } ); const chartData: SemiCircleChartData = data.map( item => ( { label: item.displayLabel, @@ -88,10 +88,6 @@ function DevicesInner( { max }: DevicesInnerProps ) { color: segmentStyles[ index ]?.color, } ) ); - // A plan error can't be fixed by retrying, so the Retry action is only - // offered for regular fetch failures. - const isPlanError = errorReason === 'upgrade-required'; - return (
= { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: StoryObj< DevicesStoryControls > = { render: () => renderDevicesOnPreset( 'last-7-days' ), @@ -132,6 +133,21 @@ export const Error: StoryObj< DevicesStoryControls > = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: StoryObj< DevicesStoryControls > = { + render: () => renderDevicesOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices/screensize', 'error-retryable' ); + return () => forceStatsMockState( 'stats/devices/screensize', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral device * glyph and "No device data in this period."). diff --git a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts index a4f5d4ecefd5..c93cb8887b60 100644 --- a/projects/packages/premium-analytics/widgets/devices/use-device-views.ts +++ b/projects/packages/premium-analytics/widgets/devices/use-device-views.ts @@ -5,7 +5,7 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { getStatsPlanErrorReason, useStatsDevices } from '@jetpack-premium-analytics/data'; +import { useStatsDevices } from '@jetpack-premium-analytics/data'; import { formatDisplayLabel } from '@jetpack-premium-analytics/widgets-toolkit'; import type { ReportParams, @@ -41,7 +41,7 @@ interface DeviceViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; - errorReason: 'upgrade-required' | null; + error: unknown; refetch: () => void; } @@ -91,21 +91,23 @@ export default function useDeviceViews( { const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = useStatsDevices( statsParams, { maxRows: max } ); - const errorReason = getStatsPlanErrorReason( error ); const items = ( comparisonRows?.rows ?? [] ).map( toDeviceView ); + // The Stats queries carry `placeholderData: previousData => previousData`, so a + // failed range change keeps the prior period's rows in `data` while `isError` + // flips true. Only surface the error when there's nothing to show, so a transient + // refetch failure doesn't replace populated rows with the error state. `error` is + // gated by the same predicate so it is populated iff `isError` is true. + const showError = items.length === 0 && isError; + return { data: items, hasComparison, isLoading, isFetching, - // The Stats queries carry `placeholderData: previousData => previousData`, so a - // failed range change keeps the prior period's rows in `data` while `isError` - // flips true. Only surface the error when there's nothing to show, so a transient - // refetch failure doesn't replace populated rows with the error state. - isError: items.length === 0 && isError, - errorReason, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx b/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx index 5f9f999bc53c..c544078dfad9 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/__tests__/search-terms.test.tsx @@ -21,6 +21,7 @@ describe( 'SearchTermsWidget', () => { isLoading: false, isFetching: false, isError: false, + error: null, hasComparison: false, refetch: jest.fn(), } ); diff --git a/projects/packages/premium-analytics/widgets/search-terms/render.tsx b/projects/packages/premium-analytics/widgets/search-terms/render.tsx index c61a6670993b..629000adfa2b 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/render.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/render.tsx @@ -3,6 +3,7 @@ */ import { calculateDelta, + describeError, getCombinedPeriodMax, LeaderboardChart, ReportLink, @@ -38,10 +39,11 @@ type SearchTermsWidgetProps = WidgetRenderProps< SearchTermsRenderAttributes >; function SearchTermsInner( { max = 10 }: SearchTermsAttributes ) { const { reportParams } = useWidgetRootContext(); - const { data, isLoading, isFetching, isError, hasComparison, refetch } = useSearchTermViews( { - reportParams, - max, - } ); + const { data, isLoading, isFetching, isError, error, hasComparison, refetch } = + useSearchTermViews( { + reportParams, + max, + } ); const leaderboardData = useMemo< LeaderboardChartData >( () => { const maxValue = getCombinedPeriodMax( @@ -82,13 +84,13 @@ function SearchTermsInner( { max = 10 }: SearchTermsAttributes ) { isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load search terms. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: search, description: __( 'No search terms in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx b/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx index 22a2eac86518..e376fc167642 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/search-terms/stories/search-terms-widget.stories.tsx @@ -101,8 +101,9 @@ export const Loading: Story = { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: Story = { render: () => renderSearchTermsOnPreset( 'last-7-days' ), @@ -114,6 +115,21 @@ export const Error: Story = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: Story = { + render: () => renderSearchTermsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas, withStoryRouter ], + beforeEach: () => { + setReportMockState( 'stats/search-terms', 'error-retryable' ); + return () => setReportMockState( 'stats/search-terms', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral search * glyph and "No search terms in this period."). diff --git a/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts b/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts index bf1c3f5d89fd..74dc55f75a80 100644 --- a/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts +++ b/projects/packages/premium-analytics/widgets/search-terms/use-search-term-views.ts @@ -26,6 +26,7 @@ interface SearchTermViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; hasComparison: boolean; refetch: () => void; } @@ -51,6 +52,7 @@ export default function useSearchTermViews( { isLoading, isFetching, isError: hasError, + error, refetch, } = useStatsSearchTerms( reportParams as Parameters< typeof useStatsSearchTerms >[ 0 ], { maxRows: max, @@ -63,15 +65,19 @@ export default function useSearchTermViews( { previousViews: comparisonUsable ? item.previousViews : undefined, } ) ); + // The Stats queries carry `placeholderData: previousData => previousData`, so a + // failed range change keeps the prior period's rows in `data` while `isError` + // flips true. Only surface the error when there's nothing to show, so a transient + // refetch failure doesn't replace populated rows with the error state. `error` is + // gated by the same predicate so it is populated iff `isError` is true. + const showError = items.length === 0 && hasError; + return { data: items, isLoading, isFetching, - // The Stats queries carry `placeholderData: previousData => previousData`, so a - // failed range change keeps the prior period's rows in `data` while `isError` - // flips true. Only surface the error when there's nothing to show, so a transient - // refetch failure doesn't replace populated rows with the error state. - isError: items.length === 0 && hasError, + isError: showError, + error: showError ? error : null, hasComparison: comparisonUsable, refetch, }; diff --git a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts index 791d76bf864f..2cdca51ce2fc 100644 --- a/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts +++ b/projects/packages/premium-analytics/widgets/stories/force-stats-mock-state.ts @@ -4,7 +4,7 @@ import apiFetch from '@wordpress/api-fetch'; import type { APIFetchMiddleware, APIFetchOptions } from '@wordpress/api-fetch'; -type ForcedMockState = 'error' | 'loading' | 'empty'; +type ForcedMockState = 'error' | 'error-retryable' | 'loading' | 'empty'; const stateOverrides = new Map< string, ForcedMockState >(); @@ -24,12 +24,24 @@ const forcedStateMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio // (`summary` / `days` / `data`), so the widget resolves to its empty state. return { date: '2026-01-01', period: 'day', summary: {}, days: {}, data: [] }; } - // A 403 is not retried by `shouldRetryApiError`, so the error UI shows at - // once instead of after the query's retry backoff. + if ( state === 'error-retryable' ) { + // The local proxy's `no_connection` shape. Still a 403, so the error UI + // shows at once, but `describeError` keeps it retryable: a broken Jetpack + // connection can heal, unlike a permission gate. + return Promise.reject( { + code: 'no_connection', + message: 'Mocked connection failure for Storybook.', + data: { status: 403 }, + } ); + } + // The WPCOM pass-through envelope, with the status attached the way the fetch + // layer attaches it. A 403 is not retried by `shouldRetryApiError`, so the + // error UI shows at once instead of after the query's retry backoff. Widgets + // on `describeError` read this as a permission gate and drop their Retry action. return Promise.reject( { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response for Storybook.', - data: { status: 403 }, + status: 403, } ); } @@ -64,6 +76,9 @@ const forcedStateMiddleware: APIFetchMiddleware = async ( options: APIFetchOptio * key carries no date params, a distinct preset can't isolate it — evict the * query from the shared client on enter and cleanup instead (see the * `latest-post` stories). + * - `'error'` mocks a permission-gated 403 and `'error-retryable'` the proxy's + * `no_connection` 403. Widgets on `describeError` render a Retry action only + * for the latter, so give those widgets a story for each. * * @param pathFragment - Substring matched against the request path (e.g. `stats/clicks`). * @param state - The forced state, or `null` to clear. diff --git a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx index 24c46931e232..8a5c326b58ff 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/render.tsx +++ b/projects/packages/premium-analytics/widgets/top-platforms/render.tsx @@ -9,6 +9,7 @@ import { __ } from '@wordpress/i18n'; import { Stack, Text } from '@wordpress/ui'; import { calculateDelta, + describeError, getCombinedPeriodMax, LeaderboardChart, sharePercentage, @@ -56,12 +57,13 @@ type TopPlatformsInnerProps = { function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) { const { reportParams } = useWidgetRootContext(); - const { data, hasComparison, isLoading, isFetching, isError, errorReason, refetch } = - usePlatformViews( { + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = usePlatformViews( + { reportParams, max, deviceProperty: platformDimension, - } ); + } + ); const maxViews = getCombinedPeriodMax( data.map( item => item.views ), @@ -91,10 +93,6 @@ function TopPlatformsInner( { max, platformDimension }: TopPlatformsInnerProps ) }; } ); - // A plan error can't be fixed by retrying, so the Retry action is only - // offered for regular fetch failures. - const isPlanError = errorReason === 'upgrade-required'; - return (
= { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: StoryObj< TopPlatformsStoryControls > = { render: () => renderTopPlatformsOnPreset( 'last-7-days' ), @@ -163,6 +164,21 @@ export const Error: StoryObj< TopPlatformsStoryControls > = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: StoryObj< TopPlatformsStoryControls > = { + render: () => renderTopPlatformsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas ], + beforeEach: () => { + forceStatsMockState( 'stats/devices', 'error-retryable' ); + return () => forceStatsMockState( 'stats/devices', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral device * glyph and "No platform data in this period."). diff --git a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts index daa909026fe6..94c8472f5c1b 100644 --- a/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts +++ b/projects/packages/premium-analytics/widgets/top-platforms/use-platform-views.ts @@ -5,7 +5,7 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { getStatsPlanErrorReason, useStatsDevices } from '@jetpack-premium-analytics/data'; +import { useStatsDevices } from '@jetpack-premium-analytics/data'; import { formatDisplayLabel } from '@jetpack-premium-analytics/widgets-toolkit'; import type { ReportParams, StatsDevicesComparisonItem } from '@jetpack-premium-analytics/data'; @@ -37,7 +37,7 @@ interface PlatformViewsState { isLoading: boolean; isFetching: boolean; isError: boolean; - errorReason: 'upgrade-required' | null; + error: unknown; refetch: () => void; } @@ -102,21 +102,23 @@ export default function usePlatformViews( { const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = useStatsDevices( statsParams, { maxRows: max } ); - const errorReason = getStatsPlanErrorReason( error ); const rows = ( comparisonRows?.rows ?? [] ).map( item => toPlatformView( item, deviceProperty ) ); + // The Stats queries carry `placeholderData: previousData => previousData`, so a + // failed range change keeps the prior period's rows in `data` while `isError` + // flips true. Only surface the error when there's nothing to show, so a transient + // refetch failure doesn't replace populated rows with the error state. `error` is + // gated by the same predicate so it is populated iff `isError` is true. + const showError = rows.length === 0 && isError; + return { data: rows, hasComparison, isLoading, isFetching, - // The Stats queries carry `placeholderData: previousData => previousData`, so a - // failed range change keeps the prior period's rows in `data` while `isError` - // flips true. Only surface the error when there's nothing to show, so a transient - // refetch failure doesn't replace populated rows with the error state. - isError: rows.length === 0 && isError, - errorReason, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx index ba24cdb2912d..53409fa3c81d 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/render.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/render.tsx @@ -6,6 +6,7 @@ import { __, sprintf } from '@wordpress/i18n'; import { Stack, Text } from '@wordpress/ui'; import { calculateDelta, + describeError, getCombinedPeriodMax, LeaderboardChart, ReportLink, @@ -97,7 +98,7 @@ function UtmInsightsInner( { utmDimension, max, showReportLink }: UtmInsightsInn clearSelectedUtm(); }, [ clearSelectedUtm, utmDimension ] ); - const { data, hasComparison, isLoading, isFetching, isError, refetch } = useUtmInsights( { + const { data, hasComparison, isLoading, isFetching, isError, error, refetch } = useUtmInsights( { reportParams, utmParam: utmDimension, max, @@ -184,13 +185,13 @@ function UtmInsightsInner( { utmDimension, max, showReportLink }: UtmInsightsInn isFetching={ isFetching } isError={ isError } isEmpty={ data.length === 0 } - error={ { - description: __( + error={ describeError( error, { + retryDescription: __( "We couldn't load UTM data. Please try again in a moment.", 'jetpack-premium-analytics' ), - actions: [ { label: __( 'Retry', 'jetpack-premium-analytics' ), onClick: refetch } ], - } } + onRetry: refetch, + } ) } empty={ { icon: megaphone, description: __( 'No UTM data in this period.', 'jetpack-premium-analytics' ), diff --git a/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx b/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx index 4ef94b27f16a..92d9ef4b46ef 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx +++ b/projects/packages/premium-analytics/widgets/utm-insights/stories/utm-insights-widget.stories.tsx @@ -116,8 +116,9 @@ export const Loading: Story = { }; /** - * The fetch failed: the widget shows its error state with a Retry action (which - * re-runs the query — still mocked as failing while this story is active). + * The fetch failed with a permission-gated 403: the widget shows the neutral + * "You don't have access to this data." copy and no Retry action, since a + * permission gate is deterministic and retrying cannot clear it. */ export const Error: Story = { render: () => renderUtmInsightsOnPreset( 'last-7-days' ), @@ -129,6 +130,21 @@ export const Error: Story = { }, }; +/** + * The fetch failed in a way that can heal — the proxy's `no_connection` 403: the + * widget shows its retryable copy with a Retry action, which re-runs the query + * (still mocked as failing while this story is active). + */ +export const ErrorRetryable: Story = { + render: () => renderUtmInsightsOnPreset( 'last-12-months' ), + tags: [ '!autodocs' ], + decorators: [ withWidgetCanvas, withStoryRouter ], + beforeEach: () => { + forceStatsMockState( 'stats/utm', 'error-retryable' ); + return () => forceStatsMockState( 'stats/utm', null ); + }, +}; + /** * Resolved with no rows: the widget shows its empty state (the neutral megaphone * glyph and "No UTM data in this period."). diff --git a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts index 8c998b3282a3..d5b932d68b61 100644 --- a/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts +++ b/projects/packages/premium-analytics/widgets/utm-insights/use-utm-insights.ts @@ -45,6 +45,7 @@ interface UtmInsightsState { isLoading: boolean; isFetching: boolean; isError: boolean; + error: unknown; refetch: () => void; } @@ -83,20 +84,22 @@ export default function useUtmInsights( { max, }: UseUtmInsightsArgs ): UtmInsightsState { const params = { ...reportParams, utmParam, max } as Parameters< typeof useStatsUtm >[ 0 ]; - const { comparisonRows, hasComparison, isLoading, isFetching, isError, refetch } = useStatsUtm( - params, - { maxRows: max } - ); + const { comparisonRows, hasComparison, isLoading, isFetching, isError, error, refetch } = + useStatsUtm( params, { maxRows: max } ); const rows = ( comparisonRows?.rows ?? [] ).map( toUtmRow ); + // Stats queries keep previous data via `placeholderData`, so a failed + // range refetch should not replace populated rows with the error state. + // `error` is gated by the same predicate so it is populated iff `isError` is true. + const showError = rows.length === 0 && isError; + return { data: rows, hasComparison, isLoading, isFetching, - // Stats queries keep previous data via `placeholderData`, so a failed - // range refetch should not replace populated rows with the error state. - isError: rows.length === 0 && isError, + isError: showError, + error: showError ? error : null, refetch, }; } diff --git a/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx b/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx index 99b5258e7825..05789133b583 100644 --- a/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx +++ b/projects/packages/premium-analytics/widgets/video-detail-embeds/__tests__/video-detail-embeds.test.tsx @@ -23,12 +23,14 @@ const SINGLE_VIDEO_RESPONSE = { pages: [ 'https://example.com/getting-started/', 'https://example.com/blog/weekly-recap/' ], }; -// A 403 is not retried by the data layer's `shouldRetryApiError`, so the error -// state shows at once instead of after the query's retry backoff. +// The WPCOM pass-through error envelope, with the status attached the way the +// fetch layer attaches it. A 403 is not retried by the data layer's +// `shouldRetryApiError`, so the error state shows at once instead of after the +// query's retry backoff. const MOCK_API_ERROR = { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response.', - data: { status: 403 }, + status: 403, }; function renderWidget( postId?: number ) { diff --git a/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx b/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx index f49be6b6fe84..dec363c9b076 100644 --- a/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx +++ b/projects/packages/premium-analytics/widgets/video-detail-highlights/__tests__/video-detail-highlights.test.tsx @@ -46,10 +46,12 @@ function responseForPath( path: string ) { return VIEWS_RESPONSE; } +// The WPCOM pass-through error envelope, with the status attached the way the +// fetch layer attaches it. const MOCK_API_ERROR = { - code: 'stats_mock_error', + error: 'unauthorized', message: 'Mocked error response.', - data: { status: 403 }, + status: 403, }; function renderWidget( postId?: number, withComparison = false ) {