Commit 1ebe18a340d for woocommerce
commit 1ebe18a340d85d5a3e92dd865cfef315bbe16663
Author: Abdalsalaam Halawa <abdalsalaamnafez@gmail.com>
Date: Thu Nov 26 13:42:36 2026 +0200
[Order Fulfillments] Add the chunked import loop and the import step (#70965)
* Add the chunked import loop and the import step
useChunkedImport sends the mapped file to /run one chunk at a time and
follows the offset the server reports. It sends a chunk again only when
the server refused it without running it (429, or chunk_in_progress),
because any other failure may have written the chunk already. The import
step shows progress and the counters, and offers Retry and Start over.
* Check every count, keep the confirmed offset and the unknown outcome
A chunk response now needs all five counts as non-negative integers.
A response behind the confirmed offset, or one that does not move it
before the import is done, stops the loop without changing the offset.
Only a valid response clears the flag that a lost response set, and an
unexpected response sets it, since the server may have written the chunk.
* Treat a rejected progress response as an unknown outcome
The server answered, so it may have written the chunk. A later ended
session now gets the warning to check orders, as after a malformed
response.
* Test that a chunk response needs a boolean done flag
* Keep the import progress announcements outside a busy region
* Type the importer counters with RunChunkCounts
* Read the import chunk size only from the localized settings
* Inline the one-use constants in the chunked import hook
* Resend a chunk only when /run reports it still in progress
* Announce import progress only through the status line
* Speak only the error text in the import step notice
* Round the import progress down
* Word the may-have-finished message for every path that shows it
* Split the no-resend tests by whether the outcome is known
* Test the default chunk size when the setting is missing or negative
* Start the import loop from the progress already confirmed
* Inline the last one-use constants in the chunked import hook
* Isolate the spoken error test from the shared a11y region
* Word the may-have-finished message in plain terms
* Document the processed argument of the chunked import hook
* Wait for Retry when the import step mounts over an error
* Keep the may-have-finished warning when the import step mounts again
* Document that the import step must stay mounted during a request
* Import the importer action type on its own line
* Move focus to the import heading when Retry clears the error
* Format expected counts with the runtime locale in the import step tests
* Accept the final summary only when its five counts are valid
* Keep the run ref comment next to the run ref
---------
Co-authored-by: Ayush Pahwa <ayush.pahwa@automattic.com>
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/importer-counters.tsx b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/importer-counters.tsx
new file mode 100644
index 00000000000..4cb2460883d
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/importer-counters.tsx
@@ -0,0 +1,90 @@
+/**
+ * External dependencies
+ */
+import React from 'react';
+import { _n } from '@wordpress/i18n';
+
+/**
+ * Internal dependencies
+ */
+import type { RunChunkCounts } from '../data/types';
+
+interface Props {
+ counts: RunChunkCounts;
+}
+
+/**
+ * The five result counters, shared by the import and summary steps so the
+ * numbers settle in place instead of the layout changing between the two
+ * screens. Zeros are shown deliberately; a zero count is meaningful.
+ */
+const ImporterCounters: React.FC< Props > = ( { counts } ) => {
+ const items: Array< { key: string; value: number; label: string } > = [
+ {
+ key: 'created',
+ value: counts.created,
+ label: _n(
+ 'Fulfillment created',
+ 'Fulfillments created',
+ counts.created,
+ 'woocommerce'
+ ),
+ },
+ {
+ key: 'updated',
+ value: counts.updated,
+ label: _n(
+ 'Fulfillment updated',
+ 'Fulfillments updated',
+ counts.updated,
+ 'woocommerce'
+ ),
+ },
+ {
+ key: 'skipped',
+ value: counts.skipped,
+ label: _n(
+ 'Row skipped',
+ 'Rows skipped',
+ counts.skipped,
+ 'woocommerce'
+ ),
+ },
+ {
+ key: 'failed',
+ value: counts.failed,
+ label: _n(
+ 'Row failed',
+ 'Rows failed',
+ counts.failed,
+ 'woocommerce'
+ ),
+ },
+ {
+ key: 'notified',
+ value: counts.notified,
+ label: _n(
+ 'Customer notified',
+ 'Customers notified',
+ counts.notified,
+ 'woocommerce'
+ ),
+ },
+ ];
+
+ return (
+ <dl className="woocommerce-fulfillment-importer-counts">
+ { items.map( ( item ) => (
+ <div
+ key={ item.key }
+ className="woocommerce-fulfillment-importer-counts__item"
+ >
+ <dt>{ item.label }</dt>
+ <dd>{ item.value.toLocaleString() }</dd>
+ </div>
+ ) ) }
+ </dl>
+ );
+};
+
+export default ImporterCounters;
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/import-step.tsx b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/import-step.tsx
new file mode 100644
index 00000000000..883214705a7
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/import-step.tsx
@@ -0,0 +1,160 @@
+/**
+ * External dependencies
+ */
+import React, { useEffect, useRef } from 'react';
+import { _n, __, sprintf } from '@wordpress/i18n';
+import { Button, Notice, ProgressBar } from '@wordpress/components';
+import { Card, Stack, Text } from '@wordpress/ui';
+
+/**
+ * Internal dependencies
+ */
+import ImporterCounters from '../importer-counters';
+import { useChunkedImport } from '../../hooks/use-chunked-import';
+import type { StepComponentProps } from './types';
+
+const ImportStep: React.FC< StepComponentProps > = ( { state, dispatch } ) => {
+ const { run, isRunning } = useChunkedImport( {
+ token: state.token,
+ total: state.total,
+ processed: state.processed,
+ // An error left on screen may hide a chunk the server wrote, so a step
+ // that mounts over one stays on the careful side.
+ outcomeUnknown: state.error !== null,
+ mapping: state.mapping,
+ notifyCustomer: state.notifyCustomer,
+ updateExisting: state.updateExisting,
+ onChunk: ( response ) => {
+ dispatch( { type: 'CHUNK_OK', payload: response } );
+ },
+ onFinish: ( summary ) => {
+ dispatch( { type: 'FINISH', summary } );
+ },
+ onError: ( message, sessionEnded ) => {
+ dispatch( { type: 'ERROR', message, sessionEnded } );
+ },
+ } );
+
+ const headingRef = useRef< HTMLHeadingElement >( null );
+
+ // Start the loop once when the step mounts. Restarting it on identity
+ // changes could rerun an import that stopped with an error, so the latest
+ // run is kept in a ref instead.
+ const runRef = useRef( run );
+ runRef.current = run;
+ // A step that mounts again over an error waits for Retry, like the loop
+ // itself never resends a failed chunk on its own.
+ const mountedWithErrorRef = useRef( state.error !== null );
+ useEffect( () => {
+ if ( ! mountedWithErrorRef.current ) {
+ void runRef.current();
+ }
+ }, [] );
+
+ const percent =
+ state.total > 0
+ ? Math.min(
+ 100,
+ // Round down so the bar is full only once every row is processed.
+ Math.floor( ( state.processed / state.total ) * 100 )
+ )
+ : 0;
+
+ // Processed, not imported: the count includes failed and skipped rows.
+ const statusLabel = sprintf(
+ /* translators: 1: processed rows, 2: total rows. */
+ _n(
+ 'Processed %1$s of %2$s row',
+ 'Processed %1$s of %2$s rows',
+ state.total,
+ 'woocommerce'
+ ),
+ state.processed.toLocaleString(),
+ state.total.toLocaleString()
+ );
+
+ return (
+ <div className="woocommerce-fulfillment-importer-step woocommerce-fulfillment-importer-step--import">
+ <Card.Root className="woocommerce-fulfillment-importer-step__card">
+ <Card.Content>
+ <Stack
+ direction="column"
+ gap="lg"
+ className="woocommerce-fulfillment-importer-step__card-body"
+ >
+ <Text
+ variant="heading-md"
+ render={ <h2 ref={ headingRef } tabIndex={ -1 } /> }
+ >
+ { __( 'Importing fulfillments', 'woocommerce' ) }
+ </Text>
+
+ <ProgressBar
+ className="woocommerce-fulfillment-importer-progress"
+ value={ percent }
+ aria-label={ __(
+ 'Import progress',
+ 'woocommerce'
+ ) }
+ />
+
+ <Text
+ render={ <p /> }
+ role="status"
+ className="woocommerce-fulfillment-importer-step__status"
+ >
+ { statusLabel }
+ </Text>
+
+ <ImporterCounters counts={ state.counts } />
+
+ { state.error ? (
+ <Notice
+ status="error"
+ isDismissible={ false }
+ spokenMessage={ state.error }
+ >
+ <p>{ state.error }</p>
+ <Stack direction="row" gap="sm">
+ { state.sessionEnded ? null : (
+ <Button
+ variant="secondary"
+ onClick={ () => {
+ // The notice and this button go away, so keep focus in the step.
+ headingRef.current?.focus();
+ dispatch( {
+ type: 'CLEAR_ERROR',
+ } );
+ void run();
+ } }
+ isBusy={ isRunning }
+ disabled={ isRunning }
+ >
+ { __( 'Retry', 'woocommerce' ) }
+ </Button>
+ ) }
+ { /* Also offered next to Retry, for an error that repeats on every retry. */ }
+ <Button
+ variant={
+ state.sessionEnded
+ ? 'secondary'
+ : 'tertiary'
+ }
+ onClick={ () =>
+ dispatch( { type: 'RESET' } )
+ }
+ disabled={ isRunning }
+ >
+ { __( 'Start over', 'woocommerce' ) }
+ </Button>
+ </Stack>
+ </Notice>
+ ) : null }
+ </Stack>
+ </Card.Content>
+ </Card.Root>
+ </div>
+ );
+};
+
+export default ImportStep;
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/test/import-step-remount.test.tsx b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/test/import-step-remount.test.tsx
new file mode 100644
index 00000000000..48e4948e85e
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/test/import-step-remount.test.tsx
@@ -0,0 +1,229 @@
+/**
+ * External dependencies
+ */
+import React from 'react';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+jest.mock( '../../../data/api', () => ( {
+ runChunk: jest.fn(),
+} ) );
+
+/**
+ * Internal dependencies
+ */
+import ImportStep from '../import-step';
+import { runChunk } from '../../../data/api';
+import { useImporterState } from '../../../hooks/use-importer-state';
+import type { ImporterAction } from '../../../hooks/use-importer-state';
+import type { RunChunkResponse } from '../../../data/types';
+
+const mockedRunChunk = runChunk as jest.MockedFunction< typeof runChunk >;
+
+const TOKEN_INVALID = {
+ code: 'woocommerce_fulfillments_import_token_invalid',
+ message: 'Import session is missing or has expired.',
+ data: { status: 400 },
+};
+
+// The a11y speak regions repeat the text, so only the notice paragraph counts.
+const IN_NOTICE = { selector: '.components-notice p' };
+
+const MAY_HAVE_FINISHED =
+ 'The import session ended before the last batch of rows was confirmed, so the import may have finished. Check your orders before you upload the file again.';
+
+function chunk( processed: number ): RunChunkResponse {
+ return {
+ processed,
+ total: 6,
+ done: false,
+ counts: {
+ created: processed,
+ updated: 0,
+ skipped: 0,
+ failed: 0,
+ notified: 0,
+ },
+ rows: [],
+ errors: [],
+ };
+}
+
+/**
+ * Keeps the wizard state while the import step is unmounted and mounted
+ * again, the way the wizard modal does.
+ */
+function Harness( {
+ stepKey,
+ showStep,
+ dispatchRef,
+}: {
+ stepKey: number;
+ showStep: boolean;
+ dispatchRef: { current: React.Dispatch< ImporterAction > | null };
+} ) {
+ const [ state, dispatch ] = useImporterState();
+ dispatchRef.current = dispatch;
+ return showStep && state.step === 'import' ? (
+ <ImportStep
+ key={ stepKey }
+ state={ state }
+ dispatch={ dispatch }
+ onClose={ jest.fn() }
+ />
+ ) : null;
+}
+
+function setUp() {
+ const dispatchRef: {
+ current: React.Dispatch< ImporterAction > | null;
+ } = { current: null };
+ const utils = render(
+ <Harness stepKey={ 1 } showStep dispatchRef={ dispatchRef } />
+ );
+ const startImport = () =>
+ act( async () => {
+ dispatchRef.current?.( {
+ type: 'PREPARE_OK',
+ payload: {
+ token: 'tok',
+ headers: [ 'Order', 'Tracking', 'Provider' ],
+ sample: [],
+ total: 6,
+ detected_mapping: {
+ 0: 'order_number',
+ 1: 'tracking_number',
+ 2: 'shipment_provider',
+ },
+ delimiter: ',',
+ },
+ } );
+ dispatchRef.current?.( { type: 'GO_IMPORT' } );
+ } );
+ const remount = () => {
+ utils.rerender(
+ <Harness
+ stepKey={ 1 }
+ showStep={ false }
+ dispatchRef={ dispatchRef }
+ />
+ );
+ utils.rerender(
+ <Harness stepKey={ 2 } showStep dispatchRef={ dispatchRef } />
+ );
+ };
+ return { startImport, remount };
+}
+
+describe( 'ImportStep mounted again with the wizard state', () => {
+ beforeEach( () => {
+ mockedRunChunk.mockReset();
+ window.wcFulfillmentsImporterSettings = {
+ importRoute: '/wc/v3/fulfillments/import',
+ chunkSize: '2',
+ maxRows: '5000',
+ providers: [],
+ };
+ } );
+
+ afterEach( () => {
+ delete window.wcFulfillmentsImporterSettings;
+ } );
+
+ it( 'waits for Retry instead of resending a failed chunk on its own', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( chunk( 2 ) )
+ .mockRejectedValueOnce( new Error( 'Failed to fetch' ) );
+ const { startImport, remount } = setUp();
+
+ await startImport();
+ await screen.findByText( 'Failed to fetch', IN_NOTICE );
+
+ remount();
+
+ expect(
+ screen.getByText( 'Failed to fetch', IN_NOTICE )
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole( 'button', { name: 'Retry' } )
+ ).toBeInTheDocument();
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 2 );
+ } );
+
+ it( 'still warns that the import may have finished after a lost response', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( chunk( 2 ) )
+ .mockRejectedValueOnce( new Error( 'Failed to fetch' ) )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+ const { startImport, remount } = setUp();
+
+ await startImport();
+ await screen.findByText( 'Failed to fetch', IN_NOTICE );
+ remount();
+
+ await act( async () => {
+ screen.getByRole( 'button', { name: 'Retry' } ).click();
+ } );
+
+ await screen.findByText( MAY_HAVE_FINISHED, IN_NOTICE );
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 3 );
+ expect( mockedRunChunk.mock.calls[ 2 ][ 0 ].offset ).toBe( 2 );
+ } );
+
+ it( 'keeps keyboard focus in the step when Retry removes the notice', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( chunk( 2 ) )
+ .mockRejectedValueOnce( new Error( 'Failed to fetch' ) )
+ .mockImplementationOnce( () => new Promise( () => {} ) );
+ const { startImport } = setUp();
+
+ await startImport();
+ await screen.findByText( 'Failed to fetch', IN_NOTICE );
+
+ screen.getByRole( 'button', { name: 'Retry' } ).focus();
+ await userEvent.keyboard( '{Enter}' );
+
+ await waitFor( () =>
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 3 )
+ );
+ expect(
+ screen.queryByText( 'Failed to fetch', IN_NOTICE )
+ ).not.toBeInTheDocument();
+ const heading = screen.getByRole( 'heading', {
+ name: 'Importing fulfillments',
+ } );
+ expect( heading.ownerDocument.activeElement ).toBe( heading );
+ } );
+
+ it( 'shows the expired session as is on a fresh import', async () => {
+ mockedRunChunk.mockRejectedValueOnce( TOKEN_INVALID );
+ const { startImport } = setUp();
+
+ await startImport();
+
+ await screen.findByText( TOKEN_INVALID.message, IN_NOTICE );
+ expect(
+ screen.queryByText( MAY_HAVE_FINISHED, IN_NOTICE )
+ ).not.toBeInTheDocument();
+ } );
+
+ it( 'forgets the lost response after Start over', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( chunk( 2 ) )
+ .mockRejectedValueOnce( new Error( 'Failed to fetch' ) )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+ const { startImport, remount } = setUp();
+
+ await startImport();
+ await screen.findByText( 'Failed to fetch', IN_NOTICE );
+ remount();
+
+ await act( async () => {
+ screen.getByRole( 'button', { name: 'Start over' } ).click();
+ } );
+ await startImport();
+
+ await screen.findByText( TOKEN_INVALID.message, IN_NOTICE );
+ expect( mockedRunChunk.mock.calls[ 2 ][ 0 ].offset ).toBe( 0 );
+ } );
+} );
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/test/import-step.test.tsx b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/test/import-step.test.tsx
new file mode 100644
index 00000000000..df11b9a8698
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/components/steps/test/import-step.test.tsx
@@ -0,0 +1,310 @@
+/**
+ * External dependencies
+ */
+import React from 'react';
+import { render, screen, waitFor } from '@testing-library/react';
+
+const mockRun = jest.fn();
+let mockIsRunning = true;
+
+jest.mock( '../../../hooks/use-chunked-import', () => ( {
+ useChunkedImport: jest.fn( () => ( {
+ run: mockRun,
+ isRunning: mockIsRunning,
+ } ) ),
+} ) );
+
+/**
+ * Internal dependencies
+ */
+import ImportStep from '../import-step';
+import { useChunkedImport } from '../../../hooks/use-chunked-import';
+import type { UseChunkedImportArgs } from '../../../hooks/use-chunked-import';
+import { createInitialState } from '../../../hooks/use-importer-state';
+import type { RunChunkResponse } from '../../../data/types';
+
+const mockedUseChunkedImport = useChunkedImport as jest.MockedFunction<
+ typeof useChunkedImport
+>;
+
+function importState( overrides = {} ) {
+ return {
+ ...createInitialState(),
+ step: 'import' as const,
+ token: 'tok',
+ total: 100,
+ ...overrides,
+ };
+}
+
+function renderStep( overrides = {}, dispatch = jest.fn() ) {
+ const utils = render(
+ <ImportStep
+ state={ importState( overrides ) }
+ dispatch={ dispatch }
+ onClose={ jest.fn() }
+ />
+ );
+ const hookArgs = mockedUseChunkedImport.mock.calls[
+ mockedUseChunkedImport.mock.calls.length - 1
+ ][ 0 ] as UseChunkedImportArgs;
+ return { ...utils, dispatch, hookArgs };
+}
+
+describe( 'ImportStep', () => {
+ beforeEach( () => {
+ // The a11y live regions are shared by every test in this file.
+ document
+ .querySelectorAll( '[id^="a11y-speak-"]' )
+ .forEach( ( region ) => region.replaceChildren() );
+ mockRun.mockClear();
+ mockedUseChunkedImport.mockClear();
+ mockIsRunning = true;
+ } );
+
+ it( 'invokes run exactly once on mount', async () => {
+ const { rerender } = renderStep();
+
+ await waitFor( () => {
+ expect( mockRun ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ // Re-render with updated state should not re-trigger run.
+ rerender(
+ <ImportStep
+ state={ importState( { processed: 10 } ) }
+ dispatch={ jest.fn() }
+ onClose={ jest.fn() }
+ />
+ );
+ expect( mockRun ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it( 'does not start the loop when it mounts with an error showing', () => {
+ mockIsRunning = false;
+ renderStep( { processed: 2, error: 'Failed to fetch' } );
+
+ expect( mockRun ).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole( 'button', { name: /retry/i } )
+ ).toBeInTheDocument();
+ } );
+
+ it.each( [
+ [ 'an error', 'Failed to fetch', true ],
+ [ 'no error', null, false ],
+ ] )(
+ 'treats the last outcome as unknown when it mounts with %s',
+ ( _label, error, expected ) => {
+ mockIsRunning = false;
+ const { hookArgs } = renderStep( { error } );
+
+ expect( hookArgs.outcomeUnknown ).toBe( expected );
+ }
+ );
+
+ it( 'passes the session and run settings to the import loop', () => {
+ const { hookArgs } = renderStep( {
+ processed: 40,
+ mapping: { 0: 'order_number' },
+ notifyCustomer: true,
+ updateExisting: false,
+ } );
+
+ expect( hookArgs ).toEqual(
+ expect.objectContaining( {
+ token: 'tok',
+ total: 100,
+ processed: 40,
+ mapping: { 0: 'order_number' },
+ notifyCustomer: true,
+ updateExisting: false,
+ } )
+ );
+ } );
+
+ it( 'dispatches the loop callbacks to the reducer', () => {
+ const { hookArgs, dispatch } = renderStep();
+ const response = { processed: 1 } as RunChunkResponse;
+ const summary = {
+ created: 1,
+ updated: 0,
+ skipped: 0,
+ failed: 0,
+ notified: 0,
+ rows: [],
+ };
+
+ hookArgs.onChunk?.( response );
+ hookArgs.onFinish?.( summary );
+ hookArgs.onError?.( 'Session expired.', true );
+
+ expect( dispatch.mock.calls ).toEqual( [
+ [ { type: 'CHUNK_OK', payload: response } ],
+ [ { type: 'FINISH', summary } ],
+ [
+ {
+ type: 'ERROR',
+ message: 'Session expired.',
+ sessionEnded: true,
+ },
+ ],
+ ] );
+ } );
+
+ it.each( [
+ [ 25, 100, '25' ],
+ [ 995, 1000, '99' ],
+ [ 120, 100, '100' ],
+ [ 0, 0, '0' ],
+ ] )(
+ 'shows %d of %d rows as a progress value of %s',
+ ( processed, total, expected ) => {
+ renderStep( { processed, total } );
+
+ // The design system ProgressBar renders a native <progress> element,
+ // which exposes its position through the value attribute.
+ const bar = screen.getByRole( 'progressbar', {
+ name: /import progress/i,
+ } );
+ expect( bar.getAttribute( 'value' ) ).toBe( expected );
+ }
+ );
+
+ it( 'announces the processed count with a plural form', () => {
+ const { rerender } = renderStep( { processed: 0, total: 1 } );
+ expect( screen.getByRole( 'status' ) ).toHaveTextContent(
+ /^Processed 0 of 1 row$/
+ );
+
+ rerender(
+ <ImportStep
+ state={ importState( { processed: 1200, total: 5000 } ) }
+ dispatch={ jest.fn() }
+ onClose={ jest.fn() }
+ />
+ );
+ // Formatted the way the step formats them, so any default locale passes.
+ expect( screen.getByRole( 'status' ).textContent ).toBe(
+ `Processed ${ ( 1200 ).toLocaleString() } of ${ ( 5000 ).toLocaleString() } rows`
+ );
+ } );
+
+ it( 'keeps the live progress regions outside a busy region while the loop runs', () => {
+ // Screen readers may hold back announcements inside a busy region.
+ renderStep( { processed: 10 } );
+
+ expect(
+ screen.getByRole( 'status' ).closest( '[aria-busy="true"]' )
+ ).toBeNull();
+ expect(
+ document
+ .querySelector( '.woocommerce-fulfillment-importer-counts' )
+ ?.closest( '[aria-busy="true"]' )
+ ).toBeNull();
+ } );
+
+ it( 'announces progress only through the status line', () => {
+ // Bare counter numbers spoken after each chunk would have no labels.
+ const { container } = renderStep( { processed: 10 } );
+
+ const regions = container.querySelectorAll(
+ '[aria-live], [role="status"], [role="alert"], [role="log"]'
+ );
+ expect( regions ).toHaveLength( 1 );
+ expect( regions[ 0 ] ).toBe( screen.getByRole( 'status' ) );
+ } );
+
+ it( 'shows all five counters, zeros included', () => {
+ renderStep( {
+ counts: {
+ created: 1,
+ updated: 2,
+ skipped: 0,
+ failed: 4,
+ notified: 1500,
+ },
+ } );
+
+ const values = Object.fromEntries(
+ screen
+ .getAllByRole( 'term' )
+ .map( ( term ) => [
+ term.textContent,
+ term.nextElementSibling?.textContent,
+ ] )
+ );
+ expect( values ).toEqual( {
+ 'Fulfillment created': '1',
+ 'Fulfillments updated': '2',
+ 'Rows skipped': '0',
+ 'Rows failed': '4',
+ 'Customers notified': ( 1500 ).toLocaleString(),
+ } );
+ } );
+
+ it( 'Retry clears the error and resumes the loop', () => {
+ mockIsRunning = false;
+ const { dispatch } = renderStep( {
+ processed: 10,
+ error: 'Network blew up',
+ } );
+ mockRun.mockClear();
+
+ screen.getByRole( 'button', { name: /retry/i } ).click();
+
+ expect( dispatch ).toHaveBeenCalledWith( { type: 'CLEAR_ERROR' } );
+ expect( mockRun ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it( 'disables Retry and Start over while the loop runs', () => {
+ renderStep( { error: 'Network blew up' } );
+
+ expect(
+ screen.getByRole( 'button', { name: /retry/i } )
+ ).toBeDisabled();
+ expect(
+ screen.getByRole( 'button', { name: /start over/i } )
+ ).toBeDisabled();
+ } );
+
+ it( 'offers Start over next to Retry for an error that may repeat', () => {
+ mockIsRunning = false;
+ const { dispatch } = renderStep( {
+ error: 'The offset does not match.',
+ } );
+
+ expect(
+ screen.getByRole( 'button', { name: /retry/i } )
+ ).toBeInTheDocument();
+ screen.getByRole( 'button', { name: /start over/i } ).click();
+ expect( dispatch ).toHaveBeenCalledWith( { type: 'RESET' } );
+ } );
+
+ it( 'speaks only the error text, not the button labels', () => {
+ mockIsRunning = false;
+ // A text no other test speaks: @wordpress/a11y marks a repeated message.
+ renderStep( { error: 'Only this test shows this error.' } );
+
+ // Notice speaks through the shared assertive region of @wordpress/a11y.
+ expect(
+ document.getElementById( 'a11y-speak-assertive' )?.textContent
+ ).toBe( 'Only this test shows this error.' );
+ } );
+
+ it( 'offers only Start over once the session has ended', () => {
+ mockIsRunning = false;
+ const { dispatch } = renderStep( {
+ processed: 10,
+ error: 'Import session is missing or has expired.',
+ sessionEnded: true,
+ } );
+
+ expect(
+ screen.queryByRole( 'button', { name: /retry/i } )
+ ).not.toBeInTheDocument();
+
+ screen.getByRole( 'button', { name: /start over/i } ).click();
+ expect( dispatch ).toHaveBeenCalledWith( { type: 'RESET' } );
+ } );
+} );
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/data/errors.ts b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/data/errors.ts
new file mode 100644
index 00000000000..60742dbcf6f
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/data/errors.ts
@@ -0,0 +1,60 @@
+/**
+ * External dependencies
+ */
+import { __ } from '@wordpress/i18n';
+
+/**
+ * Returns the HTTP status of an apiFetch error, or null when there is none.
+ * Only a WordPress REST error body carries `data.status`; apiFetch reports a
+ * body that is not JSON as `{ code: 'invalid_json' }` without a status.
+ */
+export function errorStatus( error: unknown ): number | null {
+ if ( ! error || typeof error !== 'object' || ! ( 'data' in error ) ) {
+ return null;
+ }
+ const data = ( error as { data?: unknown } ).data;
+ if (
+ data &&
+ typeof data === 'object' &&
+ typeof ( data as { status?: unknown } ).status === 'number'
+ ) {
+ return ( data as { status: number } ).status;
+ }
+ return null;
+}
+
+/**
+ * Returns the REST error code of an apiFetch error, or null when there is none.
+ */
+export function errorCode( error: unknown ): string | null {
+ if (
+ error &&
+ typeof error === 'object' &&
+ 'code' in error &&
+ typeof ( error as { code?: unknown } ).code === 'string'
+ ) {
+ return ( error as { code: string } ).code;
+ }
+ return null;
+}
+
+/**
+ * Returns a message to show for an Error, an apiFetch rejection or a string.
+ * Falls back to a generic message when there is no text to show.
+ */
+export function errorMessage( error: unknown ): string {
+ let message = '';
+ if ( typeof error === 'string' ) {
+ message = error;
+ } else if (
+ error &&
+ typeof error === 'object' &&
+ 'message' in error &&
+ typeof ( error as { message?: unknown } ).message === 'string'
+ ) {
+ message = ( error as { message: string } ).message;
+ }
+ return message.trim() !== ''
+ ? message
+ : __( 'Something went wrong. Please try again.', 'woocommerce' );
+}
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/data/test/errors.test.ts b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/data/test/errors.test.ts
new file mode 100644
index 00000000000..93577052b18
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/data/test/errors.test.ts
@@ -0,0 +1,50 @@
+/**
+ * Internal dependencies
+ */
+import { errorCode, errorMessage, errorStatus } from '../errors';
+
+const GENERIC = 'Something went wrong. Please try again.';
+
+describe( 'errorMessage', () => {
+ it.each( [
+ [ 'an Error', new Error( 'Failed to fetch' ), 'Failed to fetch' ],
+ [
+ 'an apiFetch rejection',
+ { code: 'x', message: 'Bad mapping.', data: { status: 400 } },
+ 'Bad mapping.',
+ ],
+ [ 'a string', 'Plain text', 'Plain text' ],
+ [ 'an Error with no message', new Error(), GENERIC ],
+ [ 'a blank message', { message: ' ' }, GENERIC ],
+ [ 'a non-string message', { message: 42 }, GENERIC ],
+ [ 'null', null, GENERIC ],
+ [ 'undefined', undefined, GENERIC ],
+ ] )( 'returns the text to show for %s', ( _label, error, expected ) => {
+ expect( errorMessage( error ) ).toBe( expected );
+ } );
+} );
+
+describe( 'errorStatus', () => {
+ it.each( [
+ [ { data: { status: 409 } }, 409 ],
+ [ { data: { status: '409' } }, null ],
+ [ { data: null }, null ],
+ [ { code: 'x' }, null ],
+ [ { code: 'invalid_json', message: 'Not JSON.' }, null ],
+ [ new Error( 'x' ), null ],
+ [ null, null ],
+ ] )( 'reads %p as %p', ( error, expected ) => {
+ expect( errorStatus( error ) ).toBe( expected );
+ } );
+} );
+
+describe( 'errorCode', () => {
+ it.each( [
+ [ { code: 'rest_forbidden' }, 'rest_forbidden' ],
+ [ { code: 403 }, null ],
+ [ 'rest_forbidden', null ],
+ [ null, null ],
+ ] )( 'reads %p as %p', ( error, expected ) => {
+ expect( errorCode( error ) ).toBe( expected );
+ } );
+} );
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/hooks/test/use-chunked-import.test.ts b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/hooks/test/use-chunked-import.test.ts
new file mode 100644
index 00000000000..e142c9a4bac
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/hooks/test/use-chunked-import.test.ts
@@ -0,0 +1,907 @@
+/**
+ * External dependencies
+ */
+import { StrictMode, useEffect } from 'react';
+import { act, renderHook, waitFor } from '@testing-library/react';
+
+jest.mock( '../../data/api', () => ( {
+ runChunk: jest.fn(),
+} ) );
+
+/**
+ * Internal dependencies
+ */
+import { runChunk } from '../../data/api';
+import { useChunkedImport } from '../use-chunked-import';
+import type { UseChunkedImportArgs } from '../use-chunked-import';
+import type { RunChunkResponse } from '../../data/types';
+
+const mockedRunChunk = runChunk as jest.MockedFunction< typeof runChunk >;
+
+const MAPPING = {
+ 0: 'order_number',
+ 1: 'tracking_number',
+ 2: 'shipment_provider',
+} as const;
+
+const CHUNK_IN_PROGRESS = {
+ code: 'woocommerce_fulfillments_import_chunk_in_progress',
+ message: 'Another chunk of this import is still being processed.',
+ data: { status: 409 },
+};
+
+const TOKEN_INVALID = {
+ code: 'woocommerce_fulfillments_import_token_invalid',
+ message: 'Import session is missing or has expired.',
+ data: { status: 400 },
+};
+
+const MAY_HAVE_FINISHED =
+ 'The import session ended before the last batch of rows was confirmed, so the import may have finished. Check your orders before you upload the file again.';
+
+function buildResponse(
+ processed: number,
+ total: number,
+ done: boolean,
+ withSummary = true
+): RunChunkResponse {
+ return {
+ processed,
+ total,
+ done,
+ counts: {
+ created: processed,
+ updated: 0,
+ skipped: 0,
+ failed: 0,
+ notified: 0,
+ },
+ rows: [],
+ errors: [],
+ ...( done && withSummary
+ ? {
+ summary: {
+ created: processed,
+ updated: 0,
+ skipped: 0,
+ failed: 0,
+ notified: 0,
+ rows: [],
+ },
+ }
+ : {} ),
+ };
+}
+
+function renderImport( overrides: Partial< UseChunkedImportArgs > = {} ) {
+ const onChunk = jest.fn();
+ const onFinish = jest.fn();
+ const onError = jest.fn();
+ const hook = renderHook( () =>
+ useChunkedImport( {
+ token: 'tok',
+ total: 4,
+ processed: 0,
+ outcomeUnknown: false,
+ mapping: MAPPING,
+ notifyCustomer: false,
+ updateExisting: true,
+ onChunk,
+ onFinish,
+ onError,
+ ...overrides,
+ } )
+ );
+ return { ...hook, onChunk, onFinish, onError };
+}
+
+/**
+ * Queue a runChunk call that stays pending until resolved here, and rejects
+ * with an AbortError when its signal is aborted, like apiFetch does.
+ */
+function deferredChunk() {
+ let resolve!: ( response: RunChunkResponse ) => void;
+ let signal: AbortSignal | undefined;
+ const promise = new Promise< RunChunkResponse >( ( res, rej ) => {
+ resolve = res;
+ mockedRunChunk.mockImplementationOnce( ( args ) => {
+ signal = args.signal;
+ args.signal?.addEventListener( 'abort', () =>
+ rej( new DOMException( 'Aborted', 'AbortError' ) )
+ );
+ return promise;
+ } );
+ } );
+ return { resolve, signal: () => signal };
+}
+
+async function runToEnd( result: { current: { run: () => Promise< void > } } ) {
+ await act( async () => {
+ const running = result.current.run();
+ await jest.runAllTimersAsync();
+ await running;
+ } );
+}
+
+describe( 'useChunkedImport', () => {
+ beforeEach( () => {
+ mockedRunChunk.mockReset();
+ window.wcFulfillmentsImporterSettings = {
+ importRoute: '/wc/v3/fulfillments/import',
+ chunkSize: '2',
+ maxRows: '5000',
+ providers: [],
+ };
+ } );
+
+ afterEach( () => {
+ delete window.wcFulfillmentsImporterSettings;
+ jest.useRealTimers();
+ } );
+
+ it( 'loops chunks from the server-reported offset until done and invokes onFinish', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 3, 4, false ) )
+ .mockResolvedValueOnce( buildResponse( 4, 4, true ) );
+
+ const { result, onChunk, onFinish, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 2 );
+ expect( mockedRunChunk.mock.calls[ 0 ][ 0 ] ).toEqual(
+ expect.objectContaining( {
+ token: 'tok',
+ offset: 0,
+ limit: 2,
+ mapping: MAPPING,
+ notifyCustomer: false,
+ updateExisting: true,
+ } )
+ );
+ // The server processed 3 rows, not a whole chunk of 2.
+ expect( mockedRunChunk.mock.calls[ 1 ][ 0 ].offset ).toBe( 3 );
+ expect( onChunk ).toHaveBeenCalledTimes( 2 );
+ expect( onFinish ).toHaveBeenCalledWith(
+ expect.objectContaining( { created: 4 } )
+ );
+ expect( onError ).not.toHaveBeenCalled();
+ expect( result.current.isRunning ).toBe( false );
+ } );
+
+ it.each( [
+ [ 'no processed count', { processed: undefined } ],
+ [ 'a negative processed count', { processed: -1 } ],
+ [ 'a fractional processed count', { processed: 2.5 } ],
+ [ 'no done flag', { done: undefined } ],
+ [ 'a done flag that is not a boolean', { done: 'true' } ],
+ [ 'no counts', { counts: null } ],
+ [ 'empty counts', { counts: {} } ],
+ [
+ 'a negative count',
+ {
+ counts: {
+ created: 1,
+ updated: 0,
+ skipped: 0,
+ failed: -1,
+ notified: 0,
+ },
+ },
+ ],
+ ] )(
+ 'stops without advancing on a response with %s',
+ async ( _label, patch ) => {
+ mockedRunChunk.mockResolvedValueOnce( {
+ ...buildResponse( 2, 4, false ),
+ ...patch,
+ } as unknown as RunChunkResponse );
+
+ const { result, onChunk, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onChunk ).not.toHaveBeenCalled();
+ expect( onError ).toHaveBeenCalledWith(
+ 'The server sent an unexpected response. Please try again.',
+ false
+ );
+ }
+ );
+
+ it( 'stops on an empty response body', async () => {
+ mockedRunChunk.mockResolvedValueOnce(
+ null as unknown as RunChunkResponse
+ );
+
+ const { result, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).toHaveBeenCalledWith(
+ 'The server sent an unexpected response. Please try again.',
+ false
+ );
+ } );
+
+ it.each( [
+ [ '500', 'chunk size from the settings', 500 ],
+ [ '5000', 'clamped to the /run maximum', 1000 ],
+ [ '12.7', 'rounded down', 12 ],
+ [ undefined, 'replaced by the default', 200 ],
+ [ '0', 'replaced by the default', 200 ],
+ [ '-5', 'replaced by the default', 200 ],
+ [ 'abc', 'replaced by the default', 200 ],
+ ] )(
+ 'sends a localized chunk size of %s as the %s',
+ async ( setting, _label, expected ) => {
+ // wp_localize_script casts scalars to strings.
+ window.wcFulfillmentsImporterSettings = {
+ importRoute: '/wc/v3/fulfillments/import',
+ chunkSize: setting,
+ maxRows: '5000',
+ providers: [],
+ };
+ mockedRunChunk.mockResolvedValueOnce( buildResponse( 2, 2, true ) );
+
+ const { result } = renderImport( { total: 2 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledWith(
+ expect.objectContaining( { limit: expected } )
+ );
+ }
+ );
+
+ it( 'sends the default chunk size when the settings are not on the page', async () => {
+ delete window.wcFulfillmentsImporterSettings;
+ mockedRunChunk.mockResolvedValueOnce( buildResponse( 2, 2, true ) );
+
+ const { result } = renderImport( { total: 2 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledWith(
+ expect.objectContaining( { limit: 200 } )
+ );
+ } );
+
+ it( 'does nothing without a session token', async () => {
+ const { result } = renderImport( { token: null } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).not.toHaveBeenCalled();
+ expect( result.current.isRunning ).toBe( false );
+ } );
+
+ it( 'waits for the backoff before resending a chunk the server is still running', async () => {
+ jest.useFakeTimers();
+ mockedRunChunk
+ .mockRejectedValueOnce( CHUNK_IN_PROGRESS )
+ .mockResolvedValueOnce( buildResponse( 2, 2, true ) );
+
+ const { result, onError, onFinish } = renderImport( { total: 2 } );
+
+ let running!: Promise< void >;
+ await act( async () => {
+ running = result.current.run();
+ await jest.advanceTimersByTimeAsync( 999 );
+ } );
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+
+ await act( async () => {
+ await jest.advanceTimersByTimeAsync( 1 );
+ await running;
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 2 );
+ expect( mockedRunChunk.mock.calls[ 1 ][ 0 ].offset ).toBe( 0 );
+ expect( onError ).not.toHaveBeenCalled();
+ expect( onFinish ).toHaveBeenCalled();
+ } );
+
+ it( 'gives up after three waits while the chunk stays in progress', async () => {
+ jest.useFakeTimers();
+ mockedRunChunk.mockRejectedValue( CHUNK_IN_PROGRESS );
+
+ const { result, onError } = renderImport( { total: 2 } );
+
+ await runToEnd( result );
+
+ // One attempt plus one per backoff step.
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 4 );
+ expect( onError ).toHaveBeenCalledWith(
+ CHUNK_IN_PROGRESS.message,
+ false
+ );
+ expect( result.current.isRunning ).toBe( false );
+ } );
+
+ /**
+ * Fails one chunk with the given error, then answers Retry with an ended
+ * session, so the second message shows whether the outcome was unknown.
+ */
+ async function failThenEndSession( error: unknown ) {
+ jest.useFakeTimers();
+ mockedRunChunk
+ .mockRejectedValueOnce( error )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport( { total: 2 } );
+
+ await runToEnd( result );
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onError ).toHaveBeenLastCalledWith(
+ ( error as { message: string } ).message,
+ false
+ );
+
+ await runToEnd( result );
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 2 );
+ return onError;
+ }
+
+ it.each( [
+ [ 'a network failure', new Error( 'Failed to fetch' ) ],
+ [
+ // apiFetch reports a body that is not JSON without its status.
+ 'an HTML 429 from a proxy',
+ {
+ code: 'invalid_json',
+ message: 'The response is not a valid JSON response.',
+ },
+ ],
+ [
+ 'a 500',
+ {
+ code: 'woocommerce_fulfillments_import_progress_failed',
+ message: 'Could not save the import progress.',
+ data: { status: 500 },
+ },
+ ],
+ [
+ 'a 503',
+ { code: 'unavailable', message: 'Down.', data: { status: 503 } },
+ ],
+ ] )(
+ 'does not resend the chunk after %s, whose outcome is unknown',
+ async ( _label, error ) => {
+ const onError = await failThenEndSession( error );
+
+ expect( onError ).toHaveBeenLastCalledWith(
+ MAY_HAVE_FINISHED,
+ true
+ );
+ }
+ );
+
+ it.each( [
+ [
+ 'a JSON 429',
+ {
+ code: 'rest_too_many_requests',
+ message: 'Too many requests.',
+ data: { status: 429 },
+ },
+ ],
+ [
+ 'a 409 that is not chunk-in-progress',
+ {
+ code: 'woocommerce_fulfillments_import_offset_mismatch',
+ message: 'The offset does not match.',
+ data: { status: 409 },
+ },
+ ],
+ [
+ 'a 400',
+ {
+ code: 'woocommerce_fulfillments_import_mapping_invalid',
+ message: 'Mapping is missing required column(s).',
+ data: { status: 400 },
+ },
+ ],
+ ] )(
+ 'does not resend the chunk after %s, which is a clear refusal',
+ async ( _label, error ) => {
+ const onError = await failThenEndSession( error );
+
+ expect( onError ).toHaveBeenLastCalledWith(
+ TOKEN_INVALID.message,
+ true
+ );
+ }
+ );
+
+ it.each( [
+ TOKEN_INVALID,
+ {
+ code: 'woocommerce_fulfillments_import_file_changed',
+ message: 'The uploaded file changed since it was prepared.',
+ data: { status: 409 },
+ },
+ ] )( 'flags $code as a session end', async ( error ) => {
+ mockedRunChunk.mockRejectedValue( error );
+
+ const { result, onError } = renderImport( { total: 2 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onError ).toHaveBeenCalledWith( error.message, true );
+ } );
+
+ it( 'starts from the progress already confirmed when the step mounts again', async () => {
+ mockedRunChunk.mockResolvedValueOnce( buildResponse( 4, 4, true ) );
+
+ const { result, onFinish } = renderImport( { processed: 2 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( mockedRunChunk.mock.calls[ 0 ][ 0 ].offset ).toBe( 2 );
+ expect( onFinish ).toHaveBeenCalled();
+ } );
+
+ it( 'warns that the import may have finished when it mounts after an unknown outcome', async () => {
+ mockedRunChunk.mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport( {
+ processed: 2,
+ outcomeUnknown: true,
+ } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk.mock.calls[ 0 ][ 0 ].offset ).toBe( 2 );
+ expect( onError ).toHaveBeenCalledWith( MAY_HAVE_FINISHED, true );
+ } );
+
+ it( 'resumes from the last confirmed offset when run again after an error', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 2, 4, false ) )
+ .mockRejectedValueOnce( new Error( 'Failed to fetch' ) )
+ .mockResolvedValueOnce( buildResponse( 4, 4, true ) );
+
+ const { result, onError, onFinish } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ expect( onError ).toHaveBeenCalledWith( 'Failed to fetch', false );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect(
+ mockedRunChunk.mock.calls.map( ( c ) => c[ 0 ].offset )
+ ).toEqual( [ 0, 2, 2 ] );
+ expect( onFinish ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it( 'says the import may have finished when the session is gone after a lost response', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 2, 4, false ) )
+ .mockRejectedValueOnce( {
+ code: 'gateway_timeout',
+ message: 'Gateway timeout.',
+ data: { status: 504 },
+ } )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).toHaveBeenLastCalledWith( MAY_HAVE_FINISHED, true );
+ } );
+
+ it( 'reports an expired session normally once a later chunk succeeded', async () => {
+ mockedRunChunk
+ .mockRejectedValueOnce( new Error( 'Failed to fetch' ) )
+ .mockResolvedValueOnce( buildResponse( 2, 4, false ) )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).toHaveBeenLastCalledWith(
+ TOKEN_INVALID.message,
+ true
+ );
+ } );
+
+ it( 'reports an expired session normally when the last request had a clear answer', async () => {
+ mockedRunChunk
+ .mockRejectedValueOnce( {
+ code: 'woocommerce_fulfillments_import_mapping_invalid',
+ message: 'Mapping is missing required column(s).',
+ data: { status: 400 },
+ } )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).toHaveBeenLastCalledWith(
+ TOKEN_INVALID.message,
+ true
+ );
+ } );
+
+ it( 'keeps the confirmed offset when a response goes backwards', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 3, 6, false ) )
+ .mockResolvedValueOnce( buildResponse( 1, 6, false ) )
+ .mockResolvedValueOnce( buildResponse( 6, 6, true ) );
+
+ const { result, onChunk, onError } = renderImport( { total: 6 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ expect( onChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onError ).toHaveBeenCalledWith(
+ 'The import stopped making progress. Please try again.',
+ false
+ );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ expect(
+ mockedRunChunk.mock.calls.map( ( c ) => c[ 0 ].offset )
+ ).toEqual( [ 0, 3, 3 ] );
+ } );
+
+ it( 'finishes when the last chunk is done without moving the offset', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 4, 6, false ) )
+ .mockResolvedValueOnce( buildResponse( 4, 6, true ) );
+
+ const { result, onError, onFinish } = renderImport( { total: 6 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).not.toHaveBeenCalled();
+ expect( onFinish ).toHaveBeenCalledTimes( 1 );
+ } );
+
+ it.each( [
+ [ 'a refused resend', CHUNK_IN_PROGRESS, 4 ],
+ [
+ 'a 400',
+ {
+ code: 'woocommerce_fulfillments_import_mapping_invalid',
+ message: 'Mapping is missing required column(s).',
+ data: { status: 400 },
+ },
+ 1,
+ ],
+ ] )(
+ 'keeps the may-have-finished warning after %s',
+ async ( _label, error, attempts ) => {
+ jest.useFakeTimers();
+ mockedRunChunk.mockRejectedValueOnce(
+ new Error( 'Failed to fetch' )
+ );
+ for ( let i = 0; i < attempts; i++ ) {
+ mockedRunChunk.mockRejectedValueOnce( error );
+ }
+ mockedRunChunk.mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport();
+
+ // Lost response, then the error, then the ended session.
+ await runToEnd( result );
+ await runToEnd( result );
+ await runToEnd( result );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( attempts + 2 );
+ expect( onError ).toHaveBeenLastCalledWith(
+ MAY_HAVE_FINISHED,
+ true
+ );
+ }
+ );
+
+ it( 'warns that the import may have finished after a response behind the confirmed offset', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 3, 6, false ) )
+ .mockResolvedValueOnce( buildResponse( 1, 6, true ) )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport( { total: 6 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).toHaveBeenLastCalledWith( MAY_HAVE_FINISHED, true );
+ } );
+
+ it( 'warns that the import may have finished after an unexpected response', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( {
+ processed: 'x',
+ } as unknown as RunChunkResponse )
+ .mockRejectedValueOnce( TOKEN_INVALID );
+
+ const { result, onError } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onError ).toHaveBeenLastCalledWith( MAY_HAVE_FINISHED, true );
+ } );
+
+ it( 'stops when a chunk reports no progress instead of looping', async () => {
+ mockedRunChunk.mockResolvedValue( buildResponse( 0, 4, false ) );
+
+ const { result, onError, onFinish } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onError ).toHaveBeenCalledWith(
+ 'The import stopped making progress. Please try again.',
+ false
+ );
+ expect( onFinish ).not.toHaveBeenCalled();
+ } );
+
+ it( 'stops when the offset reaches the total without a done flag', async () => {
+ mockedRunChunk.mockResolvedValue( buildResponse( 4, 4, false ) );
+
+ const { result, onError, onFinish } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onError ).toHaveBeenCalledWith(
+ 'The import did not finish. Please try again.',
+ false
+ );
+ expect( onFinish ).not.toHaveBeenCalled();
+ } );
+
+ it( 'keeps going past the total when the total is unknown', async () => {
+ mockedRunChunk
+ .mockResolvedValueOnce( buildResponse( 2, 0, false ) )
+ .mockResolvedValueOnce( buildResponse( 3, 0, true ) );
+
+ const { result, onError, onFinish } = renderImport( { total: 0 } );
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 2 );
+ expect( onError ).not.toHaveBeenCalled();
+ expect( onFinish ).toHaveBeenCalled();
+ } );
+
+ it.each( [
+ [ 'an empty summary', {} ],
+ [
+ 'a summary with a missing count',
+ { created: 4, updated: 0, skipped: 0, failed: 0, rows: [] },
+ ],
+ [
+ 'a summary with a negative count',
+ {
+ created: 4,
+ updated: 0,
+ skipped: -1,
+ failed: 0,
+ notified: 0,
+ rows: [],
+ },
+ ],
+ ] )(
+ 'treats a done response with %s as a finished session without a summary',
+ async ( _label, summary ) => {
+ mockedRunChunk.mockResolvedValue( {
+ ...buildResponse( 4, 4, true ),
+ summary,
+ } as unknown as RunChunkResponse );
+
+ const { result, onError, onFinish } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onFinish ).not.toHaveBeenCalled();
+ expect( onError ).toHaveBeenCalledWith(
+ 'The import finished, but its summary could not be loaded. Check your orders to see what was imported.',
+ true
+ );
+ }
+ );
+
+ it( 'treats a done response without a summary as a finished session', async () => {
+ mockedRunChunk.mockResolvedValue( buildResponse( 4, 4, true, false ) );
+
+ const { result, onError, onFinish } = renderImport();
+
+ await act( async () => {
+ await result.current.run();
+ } );
+
+ expect( onFinish ).not.toHaveBeenCalled();
+ expect( onError ).toHaveBeenCalledWith(
+ 'The import finished, but its summary could not be loaded. Check your orders to see what was imported.',
+ true
+ );
+ } );
+
+ it( 'aborts the request on unmount and reports nothing', async () => {
+ const chunk = deferredChunk();
+ const { result, unmount, onError, onChunk } = renderImport();
+
+ let running!: Promise< void >;
+ act( () => {
+ running = result.current.run();
+ } );
+ unmount();
+ await act( async () => {
+ await running;
+ } );
+
+ expect( chunk.signal()?.aborted ).toBe( true );
+ expect( onChunk ).not.toHaveBeenCalled();
+ expect( onError ).not.toHaveBeenCalled();
+ } );
+
+ it( 'sends nothing more when unmounted during a backoff wait', async () => {
+ jest.useFakeTimers();
+ mockedRunChunk.mockRejectedValue( CHUNK_IN_PROGRESS );
+ const { result, unmount, onError } = renderImport();
+
+ let running!: Promise< void >;
+ await act( async () => {
+ running = result.current.run();
+ await jest.advanceTimersByTimeAsync( 10 );
+ } );
+ unmount();
+ await act( async () => {
+ await jest.runAllTimersAsync();
+ await running;
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onError ).not.toHaveBeenCalled();
+ } );
+
+ it( 'ignores a response that lands after unmount', async () => {
+ // Unlike deferredChunk this does not reject on abort: the request has
+ // already left and its response arrives after the unmount.
+ let resolve!: ( response: RunChunkResponse ) => void;
+ mockedRunChunk.mockImplementationOnce(
+ () =>
+ new Promise< RunChunkResponse >( ( res ) => {
+ resolve = res;
+ } )
+ );
+ const { result, unmount, onChunk, onFinish, onError } = renderImport();
+
+ let running!: Promise< void >;
+ act( () => {
+ running = result.current.run();
+ } );
+ unmount();
+ await act( async () => {
+ resolve( buildResponse( 4, 4, true ) );
+ await running;
+ } );
+
+ expect( onChunk ).not.toHaveBeenCalled();
+ expect( onFinish ).not.toHaveBeenCalled();
+ expect( onError ).not.toHaveBeenCalled();
+ } );
+
+ it( 'starts again after a StrictMode remount aborts the first loop', async () => {
+ const first = deferredChunk();
+ mockedRunChunk.mockResolvedValueOnce( buildResponse( 4, 4, true ) );
+ const onFinish = jest.fn();
+ const onError = jest.fn();
+
+ // Starts the loop on mount, the way the import step does.
+ renderHook(
+ () => {
+ const { run } = useChunkedImport( {
+ token: 'tok',
+ total: 4,
+ processed: 0,
+ outcomeUnknown: false,
+ mapping: MAPPING,
+ notifyCustomer: false,
+ updateExisting: true,
+ onFinish,
+ onError,
+ } );
+ useEffect( () => {
+ void run();
+ }, [] ); // eslint-disable-line react-hooks/exhaustive-deps
+ },
+ { wrapper: StrictMode }
+ );
+
+ await waitFor( () => expect( onFinish ).toHaveBeenCalledTimes( 1 ) );
+ expect( first.signal()?.aborted ).toBe( true );
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 2 );
+ expect( onError ).not.toHaveBeenCalled();
+ } );
+
+ it( 'ignores run() while a loop is already in flight', async () => {
+ const chunk = deferredChunk();
+ const { result, onFinish } = renderImport();
+
+ let firstRun!: Promise< void >;
+ let secondRun!: Promise< void >;
+ act( () => {
+ firstRun = result.current.run();
+ secondRun = result.current.run();
+ } );
+
+ await act( async () => {
+ chunk.resolve( buildResponse( 4, 4, true ) );
+ await Promise.all( [ firstRun, secondRun ] );
+ } );
+
+ expect( mockedRunChunk ).toHaveBeenCalledTimes( 1 );
+ expect( onFinish ).toHaveBeenCalledTimes( 1 );
+ } );
+} );
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/hooks/use-chunked-import.ts b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/hooks/use-chunked-import.ts
new file mode 100644
index 00000000000..34e84e1b1d3
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/hooks/use-chunked-import.ts
@@ -0,0 +1,336 @@
+/**
+ * External dependencies
+ */
+import { __ } from '@wordpress/i18n';
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+/**
+ * Internal dependencies
+ */
+import { runChunk } from '../data/api';
+import { errorCode, errorMessage, errorStatus } from '../data/errors';
+import type {
+ ColumnMapping,
+ ImporterSummary,
+ RunChunkCounts,
+ RunChunkResponse,
+} from '../data/types';
+
+export interface UseChunkedImportArgs {
+ token: string | null;
+ total: number;
+ /**
+ * Rows the server already confirmed. A step that mounts again continues
+ * from here instead of from 0.
+ */
+ processed: number;
+ /**
+ * True when the last request before this mount may have written its chunk
+ * without a clear answer. It keeps the may-have-finished warning across a
+ * step that mounts again.
+ */
+ outcomeUnknown: boolean;
+ mapping: ColumnMapping;
+ notifyCustomer: boolean;
+ updateExisting: boolean;
+ onChunk?: ( response: RunChunkResponse ) => void;
+ onFinish?: ( summary: ImporterSummary ) => void;
+ onError?: ( message: string, sessionEnded: boolean ) => void;
+}
+
+// Waits before resending a chunk the server refused without running it.
+const RETRY_BACKOFFS_MS = [ 1000, 3000, 6000 ];
+
+const TOKEN_INVALID_CODE = 'woocommerce_fulfillments_import_token_invalid';
+
+/**
+ * Reads the chunk size from the localized settings as an integer the /run
+ * endpoint accepts. Nothing sets it yet, so the default of 200 applies until
+ * the PHP side passes the size /run uses. Accepts numeric strings because
+ * wp_localize_script casts scalars to strings.
+ */
+function resolvedChunkSize(): number {
+ const size = Number( window.wcFulfillmentsImporterSettings?.chunkSize );
+ if ( Number.isFinite( size ) && size > 0 ) {
+ // 1,000 is the highest limit the /run endpoint accepts.
+ return Math.min( 1000, Math.max( 1, Math.floor( size ) ) );
+ }
+ return 200;
+}
+
+function delay( ms: number, signal: AbortSignal ): Promise< void > {
+ return new Promise( ( resolve, reject ) => {
+ if ( signal.aborted ) {
+ reject( new DOMException( 'Aborted', 'AbortError' ) );
+ return;
+ }
+ const timer = setTimeout( resolve, ms );
+ signal.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout( timer );
+ reject( new DOMException( 'Aborted', 'AbortError' ) );
+ },
+ { once: true }
+ );
+ } );
+}
+
+/**
+ * True when the server refused the chunk without running it, so sending it
+ * again cannot write a row twice: another request for the same session still
+ * holds the chunk lock.
+ */
+function isSafeToResend( error: unknown ): boolean {
+ return (
+ errorStatus( error ) === 409 &&
+ errorCode( error ) ===
+ 'woocommerce_fulfillments_import_chunk_in_progress'
+ );
+}
+
+/**
+ * True for a failure after which the chunk may or may not have been written:
+ * no response at all, or a server error.
+ */
+function hasUnknownOutcome( error: unknown ): boolean {
+ const status = errorStatus( error );
+ return status === null || status >= 500;
+}
+
+/**
+ * True for the codes the /run endpoint returns once the import session no
+ * longer exists. Sending the chunk again cannot succeed; the wizard has to
+ * start over.
+ */
+function isSessionEnded( error: unknown ): boolean {
+ const code = errorCode( error );
+ return (
+ code === TOKEN_INVALID_CODE ||
+ code === 'woocommerce_fulfillments_import_file_changed'
+ );
+}
+
+function isCount( value: unknown ): value is number {
+ return typeof value === 'number' && Number.isInteger( value ) && value >= 0;
+}
+
+/**
+ * True when the value carries the five result counters, each a count. Used for
+ * the counts of every chunk and for the summary of the last one.
+ */
+function hasCounts( value: unknown ): value is RunChunkCounts {
+ if ( ! value || typeof value !== 'object' ) {
+ return false;
+ }
+ const counts = value as Partial< RunChunkCounts >;
+ return (
+ isCount( counts.created ) &&
+ isCount( counts.updated ) &&
+ isCount( counts.skipped ) &&
+ isCount( counts.failed ) &&
+ isCount( counts.notified )
+ );
+}
+
+function isChunkResponse( response: unknown ): response is RunChunkResponse {
+ if ( ! response || typeof response !== 'object' ) {
+ return false;
+ }
+ const { processed, done, counts } = response as Partial< RunChunkResponse >;
+ return (
+ isCount( processed ) && typeof done === 'boolean' && hasCounts( counts )
+ );
+}
+
+/**
+ * Drives the chunk loop for the import step.
+ *
+ * A chunk is sent again automatically only when the server refused it without
+ * running it. Any other failure stops the loop with an error, because the
+ * chunk may already be written and sending it again could repeat customer
+ * emails. Calling run() again, or mounting the hook again with the stored
+ * progress, resumes from the last offset the server reported.
+ *
+ * The caller must keep the hook mounted while a request is in flight. An
+ * unmount aborts that request without an error, so a later mount sends the
+ * chunk again and treats its outcome as known, although the server may have
+ * written it and ended the session.
+ */
+export function useChunkedImport( args: UseChunkedImportArgs ) {
+ const {
+ token,
+ total,
+ processed,
+ outcomeUnknown,
+ mapping,
+ notifyCustomer,
+ updateExisting,
+ onChunk,
+ onFinish,
+ onError,
+ } = args;
+ const chunkSize = resolvedChunkSize();
+
+ const [ isRunning, setIsRunning ] = useState( false );
+ const offsetRef = useRef< number >( processed );
+ const abortRef = useRef< AbortController | null >( null );
+ const runningRef = useRef( false );
+ // Set when the last request failed in a way that may have written its chunk.
+ const outcomeUnknownRef = useRef( outcomeUnknown );
+ // Keep the latest callbacks in a ref so run() does not change identity each render.
+ const callbacksRef = useRef( { onChunk, onFinish, onError } );
+ useEffect( () => {
+ callbacksRef.current = { onChunk, onFinish, onError };
+ }, [ onChunk, onFinish, onError ] );
+
+ useEffect( () => {
+ return () => {
+ // Also release the run guard, so a remount that keeps these refs can start again.
+ abortRef.current?.abort();
+ abortRef.current = null;
+ runningRef.current = false;
+ };
+ }, [] );
+
+ const run = useCallback( async () => {
+ if ( ! token || runningRef.current ) {
+ return;
+ }
+ runningRef.current = true;
+ setIsRunning( true );
+ const controller = new AbortController();
+ abortRef.current = controller;
+ const { signal } = controller;
+ // After an unmount a newer run may own the refs; a late response must not reach the callbacks.
+ const ownsLoop = () =>
+ ! signal.aborted && abortRef.current === controller;
+ const fail = ( message: string, sessionEnded = false ) => {
+ callbacksRef.current.onError?.( message, sessionEnded );
+ };
+
+ try {
+ while ( true ) {
+ let response: unknown = null;
+ for ( let attempt = 0; ; attempt++ ) {
+ try {
+ response = await runChunk( {
+ token,
+ offset: offsetRef.current,
+ limit: chunkSize,
+ mapping,
+ notifyCustomer,
+ updateExisting,
+ signal,
+ } );
+ break;
+ } catch ( error ) {
+ if (
+ ! isSafeToResend( error ) ||
+ attempt >= RETRY_BACKOFFS_MS.length
+ ) {
+ throw error;
+ }
+ await delay( RETRY_BACKOFFS_MS[ attempt ], signal );
+ }
+ }
+
+ if ( ! ownsLoop() ) {
+ return;
+ }
+ if ( ! isChunkResponse( response ) ) {
+ // The server answered, so it may have written the chunk.
+ outcomeUnknownRef.current = true;
+ fail(
+ __(
+ 'The server sent an unexpected response. Please try again.',
+ 'woocommerce'
+ )
+ );
+ return;
+ }
+ // A response behind the confirmed offset, or one that does not move it
+ // before the import is done, would rewind or loop; keep the offset.
+ if (
+ response.processed < offsetRef.current ||
+ ( ! response.done &&
+ response.processed === offsetRef.current )
+ ) {
+ // The server answered, so it may have written the chunk.
+ outcomeUnknownRef.current = true;
+ fail(
+ __(
+ 'The import stopped making progress. Please try again.',
+ 'woocommerce'
+ )
+ );
+ return;
+ }
+ outcomeUnknownRef.current = false;
+
+ callbacksRef.current.onChunk?.( response );
+ offsetRef.current = response.processed;
+
+ if ( response.done ) {
+ if ( hasCounts( response.summary ) ) {
+ callbacksRef.current.onFinish?.( response.summary );
+ } else {
+ // The server ends the session with the last chunk, so there is nothing to retry.
+ fail(
+ __(
+ 'The import finished, but its summary could not be loaded. Check your orders to see what was imported.',
+ 'woocommerce'
+ ),
+ true
+ );
+ }
+ return;
+ }
+
+ if ( total > 0 && offsetRef.current >= total ) {
+ fail(
+ __(
+ 'The import did not finish. Please try again.',
+ 'woocommerce'
+ )
+ );
+ return;
+ }
+ }
+ } catch ( error ) {
+ if (
+ ( error as DOMException )?.name === 'AbortError' ||
+ ! ownsLoop()
+ ) {
+ return;
+ }
+ if (
+ outcomeUnknownRef.current &&
+ errorCode( error ) === TOKEN_INVALID_CODE
+ ) {
+ // The failed chunk may have been the last one: the server ends the session when the import finishes.
+ fail(
+ __(
+ 'The import session ended before the last batch of rows was confirmed, so the import may have finished. Check your orders before you upload the file again.',
+ 'woocommerce'
+ ),
+ true
+ );
+ return;
+ }
+ // Only a valid response settles an unknown outcome; another error does not.
+ if ( hasUnknownOutcome( error ) ) {
+ outcomeUnknownRef.current = true;
+ }
+ fail( errorMessage( error ), isSessionEnded( error ) );
+ } finally {
+ if ( abortRef.current === controller ) {
+ abortRef.current = null;
+ runningRef.current = false;
+ setIsRunning( false );
+ }
+ }
+ }, [ token, total, mapping, notifyCustomer, updateExisting, chunkSize ] );
+
+ return { run, isRunning };
+}
diff --git a/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/style.scss b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/style.scss
new file mode 100644
index 00000000000..fcaabf31d59
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/wp-admin-scripts/fulfillments-importer/style.scss
@@ -0,0 +1,57 @@
+@import "@wordpress/base-styles/_colors.scss";
+
+.woocommerce-fulfillment-importer-step {
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+ max-width: 700px;
+ margin: 0 auto;
+
+ // Border, radius and padding are the @wordpress/ui card defaults; the
+ // Stack inside it sets the gaps. Text sets the type but not the margins.
+ &__card-body > h2,
+ &__card-body > p {
+ margin: 0;
+ }
+
+ &__status {
+ color: $gray-900;
+ }
+}
+
+// The design system track defaults to a fixed width; the wizard uses the
+// full card width. The extra ancestor wins over the emotion-injected style.
+.woocommerce-fulfillment-importer-step .woocommerce-fulfillment-importer-progress {
+ width: 100%;
+}
+
+.woocommerce-fulfillment-importer-counts {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
+ gap: 12px;
+ margin: 0;
+
+ &__item {
+ // Value above label, keeping dt before dd in the markup.
+ display: flex;
+ flex-direction: column-reverse;
+ justify-content: flex-end;
+ gap: 4px;
+ padding: 16px;
+ border: 1px solid $gray-200;
+ border-radius: 4px;
+ }
+
+ dt {
+ font-size: 12px;
+ line-height: 16px;
+ color: $gray-700;
+ }
+
+ dd {
+ font-size: 20px;
+ line-height: 24px;
+ font-weight: 600;
+ margin: 0;
+ }
+}