Commit 25203641fa5 for woocommerce
commit 25203641fa57c6d68361fd7b468c584194da46b0
Author: Abdalsalaam Halawa <abdalsalaamnafez@gmail.com>
Date: Mon Nov 16 16:31:34 2026 +0200
[Order Fulfillments] Add the fulfillments import prepare endpoint (#70769)
* Add the fulfillments import session and its cleanup
ImportSession is the per-user transient that holds the staged CSV and the progress fields the chunked import reads. It schedules an Action Scheduler cleanup that removes an abandoned upload once the session expires; the listener is attached regardless of the feature flag.
(cherry picked from commit b1a21e1297edbd1c472ec2dd862d618d80a3ed37)
* Limit the cleanup to the wc-imports directory
is_staged_path() now accepts files under the CSVUploadHelper import directory only, so a stale cleanup payload cannot delete media elsewhere in uploads. The session test fixtures move there, the redundant per-test session deletion goes, and the controller test assertions get messages.
(cherry picked from commit a46a868c951fcba165aaaf7b198436bdc6df92e7)
* Drop the manual attachment cleanup from the mismatched-attachment test
The per-test transaction rolls the attachment post back and tearDown removes the file, so the try/finally only repeated that.
(cherry picked from commit cb4bfe0c2948ad523a400c76543ca188c7f6a9d5)
* Check the import directory before deleting an attachment for a missing file
The staging check only ran when the file still existed, so a stale cleanup payload naming a missing path and an attachment stored at that path could delete the attachment post and its sizes. is_staged_path() now resolves a missing file through its directory and the cleanup refuses anything outside wc-imports before touching the attachment.
(cherry picked from commit 67dd582d3ce2fcf890bf3833380d4b48c1f5977f)
* Accept staged paths on a stream wrapper uploads directory
realpath() returns false for a stream wrapper path, so is_staged_path()
refused every file on an S3-backed uploads directory and the cleanup
never deleted an abandoned CSV there. Stream paths are now normalized
instead of resolved, and refused when they contain a dot segment.
(cherry picked from commit 68d3cd01feaa039f23b7c2f1d4cfc8f473559976)
* Slide the session payload TTL on every persist
persist() skipped the payload write when the payload was unchanged, so
only the index pointer's TTL slid, against what the docblocks said.
The payload is now written every time; set_transient() returns false
for an unchanged value although it still extends the timeout, so a
false result is confirmed by reading the transient back.
(cherry picked from commit ce7908f54331875f04b69199c9ce94148dcb8c25)
* Document that the cleanup action also fires for live sessions
The hooks doc example logged every firing as an abandoned import, but
the action also fires while the session is live and the default
handler reschedules it. The doc and the hook docblock now say so, and
the example skips a session that ImportSession::load() still returns.
(cherry picked from commit b544f29fb2ef5a14edd2bcd19b9cd4165098bfeb)
* Refuse a directory path and a stale cache form of a stream path
A stream path with a trailing slash passed is_staged_path() for the
import directory itself, which the local branch refuses. An empty
segment is now refused like a dot segment. The stream path is also
normalized here instead of by wp_normalize_path(), which caches by the
raw string and collapses the scheme separator when the wrapper was not
registered at the time.
(cherry picked from commit f13494fd59c4ee24dd471212954febcd2d6cee11)
* Share one staged-file delete and drop a session that fails to persist
The containment rule for deleting a staged CSV lived only inside the
cleanup action handler, so the prepare endpoint had to carry its own
copy, and that copy skipped the check when the file was already gone.
delete_staged_file() is now the one place a path read back from stored
state is deleted: it refuses anything outside wc-imports, for a missing
file too, and only removes an attachment that still points at the path.
The cleanup handler calls it.
create() now removes the session record and index pointer when the
payload write fails as well, not only when the cleanup action cannot be
scheduled. persist() writes the index pointer before it knows whether
the payload was stored, so a failed session used to leave a pointer to
a token with no payload until the caller cleaned it up.
total is described as the number of non-blank data rows, which is what
the importer counts.
* Cast the cleanup hook arguments in the doc example
Action Scheduler stores the action arguments, so the user ID can come
back as a string. ImportSession::load() takes an int and a string, and
an extension that copies the example into a file with strict_types on
would get a TypeError inside the Action Scheduler run.
* Add the fulfillments import prepare endpoint
POST /wc/v3/fulfillments/import/prepare stages an uploaded CSV under
uploads/wc-imports, reads its header with FulfillmentsCsvImporter and
opens an ImportSession for the wizard's mapping step. The response
carries the session token, the headers, the first data row, the number
of data rows, the detected column mapping and the delimiter.
The route needs manage_woocommerce and is registered through
FulfillmentsController::$provides, so it only exists while the
fulfillments feature is on. The upload helper is injected through
init(), the way other container-resolved classes receive dependencies.
Uploads are checked in this order: PHP's own upload error code (a file
PHP refused for size gets the 413, a missing file gets the no-file
error), a zero-byte file, the filtered size limit, then CSVUploadHelper.
A staged file that an upload_dir filter moved outside wc-imports is
discarded and refused, because every later delete refuses paths outside
that directory. The delimiter is validated by value, so a quote, a line
break or a non-ASCII byte is rejected instead of being read as a comma.
The prior session is kept until the new upload is stored and parsed, so
a rejected upload leaves it intact. ImportSession::create() reports the
session it retired, and its staged file and attachment are removed
through ImportSession::delete_staged_file(), the one delete routine for
paths read back from stored state. A session that cannot be stored or
whose cleanup cannot be scheduled fails the prepare and the new staged
file is removed.
The REST doc gains a section for the endpoint with its parameters,
response fields and error codes.
* Create the fulfillment tables before the controller tests and drop redundant cleanup
The flag-toggle test called initialize_fulfillments() with the feature
on inside the test transaction. When the tables are missing that path
runs DDL, which commits implicitly and leaves temporary tables behind,
so the class now creates the tables once in wpSetUpBeforeClass() and
restores the flag afterwards.
The REST controller test deleted sessions and attachments in tearDown()
that the transaction already rolls back. Only the files and the
container state are cleaned up by hand now.
* Load the multisite upload helpers before reading the import size limit
On multisite WordPress hooks fix_import_form_size() onto the
import_upload_size_limit filter on every request, but the function is
defined in wp-admin/includes/ms.php, which only wp-admin loads. The
prepare endpoint applied the filter from a REST request, so every
upload on a multisite network ended in a fatal error. The file is
required first when is_multisite() is true.
The same filter returns 0 when the site has used up its upload space.
The size check treated 0 as no limit and let the upload through; a
limit of 0 is now a 413 with a message about the missing space.
* Remove the stored upload when the upload helper throws after storing it
CSVUploadHelper throws after storing the file when wc_is_file_valid_csv()
rejects it, and its own cleanup reads the attachment ID from the wrong array,
so the file in wc-imports and its attachment stayed behind. The prepare
endpoint now records the stored path and attachment from the wp_handle_upload
and add_attachment hooks while the helper runs, and removes both on any throw.
The staging step is split into the pre-flight checks, which store nothing,
and the store step, which owns the cleanup. The repeated no-file and
upload-failed errors are built by one helper each.
* Skip the type check when the upload test stores its fixture
PHP 8.5 detects the comma-separated .txt fixture as text/csv, and WordPress refuses a .txt whose detected type is text/csv, so the stub stored nothing and the test failed on its precondition. The stub now stores the file without the type check and the test reports the sideload error if there is one.
---------
Co-authored-by: Taha Paksu <3295+tpaksu@users.noreply.github.com>
diff --git a/docs/apis/rest-api/v3/order-fulfillments.mdx b/docs/apis/rest-api/v3/order-fulfillments.mdx
index 7a2584c5961..44f7b2930e9 100644
--- a/docs/apis/rest-api/v3/order-fulfillments.mdx
+++ b/docs/apis/rest-api/v3/order-fulfillments.mdx
@@ -1053,6 +1053,79 @@ The two error cases are different and return different codes:
- Missing `tracking_number`: WordPress rejects the request before the endpoint runs, because the parameter is registered as required. The response is a `400` with the code `rest_missing_callback_param`.
- Empty `tracking_number` (for example `?tracking_number=`): the request reaches the endpoint and returns a `400` with the code `woocommerce_rest_tracking_number_missing`.
+## Prepare a fulfillments import
+
+Uploads a CSV of tracking data, reads its header row and opens an import session for the column-mapping step of the import wizard. Requires the `manage_woocommerce` capability. Each user has one import session at a time: a successful call replaces the caller's previous session and removes its staged file, while a rejected upload (a `400` or `413` response) leaves the previous session untouched.
+
+The request body is `multipart/form-data`. The official client libraries do not send multipart requests, so the example uses cURL.
+
+```http
+POST /wp-json/wc/v3/fulfillments/import/prepare
+```
+
+<Tabs>
+ <TabItem value="curl" label="cURL">
+
+```shell
+curl -X POST "https://example.com/wp-json/wc/v3/fulfillments/import/prepare" \
+ -u consumer_key:consumer_secret \
+ -F "file=@shipments.csv;type=text/csv" \
+ -F "delimiter=,"
+```
+
+ </TabItem>
+ <TabItem value="response" label="JSON Response">
+
+```json
+{
+ "token": "6b4c90a944064f5ba32938f140d453d5",
+ "headers": ["order_id", "tracking_number", "shipment_provider", "tracking_url"],
+ "sample": ["101", "1Z999AA10123456784", "ups", "https://www.ups.com/track?tracknum=1Z999AA10123456784"],
+ "total": 1,
+ "detected_mapping": {
+ "0": "order_number",
+ "1": "tracking_number",
+ "2": "shipment_provider",
+ "3": "tracking_url"
+ },
+ "delimiter": ","
+}
+```
+
+ </TabItem>
+</Tabs>
+
+#### Available parameters
+
+| Parameter | Type | Description |
+| ----------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
+| `file` | file | Required. The CSV file to import, up to the site's upload size limit and at most 5,000 data rows. A `.txt` file is accepted only when WordPress identifies its content as plain text; comma-separated content must use the `.csv` extension. |
+| `delimiter` | string | Single ASCII character used as the column delimiter, or `tab`. Defaults to `,`. |
+| `notify_customer` | boolean | Initial value for the import run: whether customers are notified about imported fulfillments. Stored on the session. Defaults to `false`. |
+| `update_existing` | boolean | Initial value for the import run: whether a fulfillment with the same tracking number is updated instead of skipped. Stored on the session. Defaults to `true`. |
+
+#### Response properties
+
+| Property | Type | Description |
+| ------------------ | ------- | ------------------------------------------------------------------------------------------------------ |
+| `token` | string | Import session token to pass to the next step of the import. |
+| `headers` | array | Header row of the staged CSV. The first non-blank record is the header. |
+| `sample` | array | First non-blank data row, for the mapping preview. Cells are trimmed and padded to the header length. |
+| `total` | integer | Number of non-blank data rows. |
+| `detected_mapping` | object | Auto-detected canonical column for each CSV column index. Columns that were not detected are omitted. |
+| `delimiter` | string | Delimiter used to read the file. |
+
+Error codes specific to this endpoint:
+
+- `woocommerce_fulfillments_import_no_file` (`400`) - No file was uploaded.
+- `woocommerce_fulfillments_import_file_too_large` (`413`) - The file exceeds the upload size limit, including a file PHP itself refused for its size, or the site has no upload space left (multisite quota).
+- `woocommerce_fulfillments_import_upload_failed` (`400` or `500`) - The file could not be staged, is not a CSV, or was stored outside the import directory.
+- `woocommerce_fulfillments_csv_parse_error` (`400`) - The file is empty, unreadable, not valid UTF-8, saved as UTF-16 or with CR-only line endings, or has no data rows. The error `data.reason` carries the importer's code.
+- `woocommerce_fulfillments_import_too_many_rows` (`413`) - The file has more than 5,000 data rows.
+- `woocommerce_fulfillments_import_session_failed` (`500`) - The import session could not be stored, or the cleanup of its staged file could not be scheduled. The staged file is removed. The caller's previous session was replaced before this point and is gone as well.
+- `rest_invalid_param` (`400`) - The `delimiter` is not a single ASCII character or `tab`, or `notify_customer` or `update_existing` is not a boolean.
+- `woocommerce_rest_cannot_create` (`401` or `403`) - The request is not authenticated or the user lacks `manage_woocommerce`.
+
## Error responses
Errors follow the standard WooCommerce REST API error shape:
diff --git a/plugins/woocommerce/src/Admin/Features/Fulfillments/FulfillmentsController.php b/plugins/woocommerce/src/Admin/Features/Fulfillments/FulfillmentsController.php
index a4f09a14e11..a7799ed0365 100644
--- a/plugins/woocommerce/src/Admin/Features/Fulfillments/FulfillmentsController.php
+++ b/plugins/woocommerce/src/Admin/Features/Fulfillments/FulfillmentsController.php
@@ -3,6 +3,7 @@
namespace Automattic\WooCommerce\Admin\Features\Fulfillments;
use Automattic\WooCommerce\Admin\Features\Fulfillments\DataStore\FulfillmentsDataStore;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\FulfillmentsImporterRestController;
use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\ImportSession;
use Automattic\WooCommerce\Internal\Features\FeaturesController;
use Automattic\WooCommerce\Internal\Utilities\DatabaseUtil;
@@ -24,6 +25,7 @@ class FulfillmentsController {
FulfillmentsSettings::class,
OrderFulfillmentsRestController::class,
FulfillmentsPrivacy::class,
+ FulfillmentsImporterRestController::class,
);
/**
diff --git a/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsImporterRestController.php b/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsImporterRestController.php
new file mode 100644
index 00000000000..2525564cab7
--- /dev/null
+++ b/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsImporterRestController.php
@@ -0,0 +1,567 @@
+<?php
+/**
+ * FulfillmentsImporterRestController class file.
+ *
+ * @package Automattic\WooCommerce\Admin\Features\Fulfillments\Importer
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Admin\Features\Fulfillments\Importer;
+
+use Automattic\WooCommerce\Internal\Admin\ImportExport\CSVUploadHelper;
+use Automattic\WooCommerce\Internal\RestApiControllerBase;
+use Automattic\WooCommerce\Internal\Utilities\FilesystemUtil;
+use WP_Error;
+use WP_Http;
+use WP_REST_Request;
+use WP_REST_Server;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * REST controller backing the Fulfillments CSV importer.
+ *
+ * Exposes `POST /wc/v3/fulfillments/import/prepare`, which uploads the CSV, parses the
+ * headers and opens an ImportSession for the wizard's column-mapping step.
+ *
+ * @internal
+ * @since 11.4.0
+ */
+class FulfillmentsImporterRestController extends RestApiControllerBase {
+
+ /**
+ * REST API base.
+ *
+ * @var string
+ */
+ protected string $rest_base = '/fulfillments/import';
+
+ /**
+ * Upload helper that stages the CSV under the wc-imports directory.
+ *
+ * @var CSVUploadHelper
+ */
+ private CSVUploadHelper $csv_upload_helper;
+
+ /**
+ * Receive the upload helper from the container.
+ *
+ * @internal
+ * @since 11.4.0
+ *
+ * @param CSVUploadHelper $csv_upload_helper Upload helper.
+ */
+ final public function init( CSVUploadHelper $csv_upload_helper ): void {
+ $this->csv_upload_helper = $csv_upload_helper;
+ }
+
+ /**
+ * Get the WooCommerce REST API namespace key for this controller.
+ *
+ * @since 11.4.0
+ *
+ * @return string
+ */
+ protected function get_rest_api_namespace(): string {
+ return 'fulfillments_importer';
+ }
+
+ /**
+ * Register the routes for the importer.
+ *
+ * @since 11.4.0
+ */
+ public function register_routes(): void {
+ register_rest_route(
+ $this->route_namespace,
+ $this->rest_base . '/prepare',
+ array(
+ array(
+ 'methods' => WP_REST_Server::CREATABLE,
+ 'callback' => fn( WP_REST_Request $request ) => $this->run( $request, 'handle_prepare' ),
+ 'permission_callback' => fn( WP_REST_Request $request ) => $this->check_permission_for_fulfillments_import( $request ),
+ 'args' => array(
+ 'delimiter' => array(
+ 'type' => 'string',
+ 'default' => ',',
+ 'description' => __( 'Single ASCII character used as the CSV delimiter, or "tab". Defaults to comma.', 'woocommerce' ),
+ 'validate_callback' => fn( $value ) => $this->validate_delimiter( $value ),
+ 'sanitize_callback' => array( FulfillmentsCsvImporter::class, 'normalize_delimiter' ),
+ ),
+ 'notify_customer' => array(
+ 'type' => 'boolean',
+ 'default' => false,
+ 'description' => __( 'Initial value for the import run: whether customers are notified about imported fulfillments. Stored on the session.', 'woocommerce' ),
+ ),
+ 'update_existing' => array(
+ 'type' => 'boolean',
+ 'default' => true,
+ 'description' => __( 'Initial value for the import run: whether a fulfillment with the same tracking number is updated instead of skipped. Stored on the session.', 'woocommerce' ),
+ ),
+ ),
+ ),
+ 'schema' => fn() => $this->get_schema_for_prepare(),
+ )
+ );
+ }
+
+ /**
+ * Get the response schema for the prepare endpoint.
+ *
+ * @return array
+ */
+ private function get_schema_for_prepare(): array {
+ $schema = $this->get_base_schema();
+ $schema['title'] = __( 'Prepare fulfillments import response.', 'woocommerce' );
+ $schema['properties'] = array(
+ 'token' => array(
+ 'type' => 'string',
+ 'description' => __( 'Import session token to pass to the next step of the import.', 'woocommerce' ),
+ ),
+ 'headers' => array(
+ 'type' => 'array',
+ 'items' => array( 'type' => 'string' ),
+ 'description' => __( 'Header row of the staged CSV.', 'woocommerce' ),
+ ),
+ 'sample' => array(
+ 'type' => 'array',
+ 'items' => array( 'type' => 'string' ),
+ 'description' => __( 'First non-blank data row, for the mapping preview. Cells are trimmed and padded to the header length.', 'woocommerce' ),
+ ),
+ 'total' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Number of non-blank data rows after the header.', 'woocommerce' ),
+ ),
+ 'detected_mapping' => array(
+ 'type' => 'object',
+ 'additionalProperties' => array( 'type' => 'string' ),
+ 'description' => __( 'Auto-detected column mapping, keyed by CSV column index.', 'woocommerce' ),
+ ),
+ 'delimiter' => array(
+ 'type' => 'string',
+ 'description' => __( 'Effective CSV delimiter.', 'woocommerce' ),
+ ),
+ );
+ return $schema;
+ }
+
+ /**
+ * Permission check for the import endpoint.
+ *
+ * @since 11.4.0
+ *
+ * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+ * @param WP_REST_Request $request The request for which the permission is checked.
+ * @return bool|WP_Error True when allowed; WP_Error otherwise.
+ */
+ protected function check_permission_for_fulfillments_import( WP_REST_Request $request ) {
+ return $this->check_permission( $request, 'manage_woocommerce' );
+ }
+
+ /**
+ * Validate the delimiter argument: one ASCII byte, a tab spelling, or empty for the default.
+ *
+ * The check mirrors FulfillmentsCsvImporter::normalize_delimiter(): a value the
+ * normalizer would replace (a quote, a line break, a non-ASCII byte, more than one
+ * byte) is rejected here instead of being read as a comma without telling the caller.
+ *
+ * @since 11.4.0
+ *
+ * @param mixed $value Raw request value.
+ * @return true|WP_Error
+ */
+ protected function validate_delimiter( $value ) {
+ if ( ! is_string( $value ) ) {
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_invalid_delimiter',
+ __( 'The delimiter must be a string.', 'woocommerce' ),
+ array( 'status' => WP_Http::BAD_REQUEST )
+ );
+ }
+ if ( '' === $value || FulfillmentsCsvImporter::is_tab_spelling( $value ) ) {
+ return true;
+ }
+ if ( strlen( $value ) > 1 || FulfillmentsCsvImporter::normalize_delimiter( $value ) !== $value ) {
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_invalid_delimiter',
+ __( 'The delimiter must be a single ASCII character or "tab".', 'woocommerce' ),
+ array( 'status' => WP_Http::BAD_REQUEST )
+ );
+ }
+ return true;
+ }
+
+ /**
+ * Prepare step: validate and stage the upload, parse the headers, open a session.
+ *
+ * The prior session of the user is kept until the new upload is stored and parsed, so
+ * a rejected upload (400 or 413) leaves it intact. ImportSession::create() decides which
+ * session is replaced, so two overlapping prepares by the same user each delete the
+ * staged file of the session they retired. A 500 from a session that could not be
+ * stored comes after that point, so the prior session is gone on that path too.
+ *
+ * @since 11.4.0
+ *
+ * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+ * @param WP_REST_Request $request The incoming multipart request.
+ * @return array|WP_Error
+ */
+ protected function handle_prepare( WP_REST_Request $request ) {
+ $delimiter_param = (string) $request->get_param( 'delimiter' );
+ $notify = (bool) $request->get_param( 'notify_customer' );
+ $update = (bool) $request->get_param( 'update_existing' );
+ $user_id = get_current_user_id();
+
+ $staged = $this->stage_uploaded_csv( $request );
+ if ( $staged instanceof WP_Error ) {
+ return $staged;
+ }
+ $file_path = (string) $staged['file'];
+ $attachment_id = (int) $staged['id'];
+
+ $parsed = ( new FulfillmentsCsvImporter( $file_path ) )->parse_headers( $delimiter_param );
+ if ( isset( $parsed['error'] ) ) {
+ $this->discard_failed_upload( $file_path, $attachment_id );
+ return new WP_Error(
+ 'woocommerce_fulfillments_csv_parse_error',
+ (string) $parsed['error']['message'],
+ array(
+ 'status' => WP_Http::BAD_REQUEST,
+ 'reason' => (string) $parsed['error']['code'],
+ )
+ );
+ }
+
+ $total = (int) ( $parsed['total'] ?? 0 );
+ if ( 0 === $total ) {
+ $this->discard_failed_upload( $file_path, $attachment_id );
+ return new WP_Error(
+ 'woocommerce_fulfillments_csv_parse_error',
+ __( 'The CSV file has no data rows.', 'woocommerce' ),
+ array( 'status' => WP_Http::BAD_REQUEST )
+ );
+ }
+ if ( $total > FulfillmentsCsvImporter::MAX_IMPORT_ROWS ) {
+ $this->discard_failed_upload( $file_path, $attachment_id );
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_too_many_rows',
+ sprintf(
+ /* translators: %s: maximum supported rows. */
+ __( 'The importer supports up to %s rows per file. Please split the file and import it in parts.', 'woocommerce' ),
+ number_format_i18n( FulfillmentsCsvImporter::MAX_IMPORT_ROWS )
+ ),
+ array( 'status' => WP_Http::REQUEST_ENTITY_TOO_LARGE )
+ );
+ }
+
+ $session = ImportSession::create(
+ $user_id,
+ $file_path,
+ (string) ( $parsed['delimiter'] ?? ',' ),
+ (array) ( $parsed['headers'] ?? array() ),
+ $total,
+ $notify,
+ $update,
+ $attachment_id
+ );
+
+ // The replaced session's record and cleanup action are already gone, so its staged
+ // file goes too, whether or not the new session could be stored. The path comes from
+ // stored session state, so the containment check in ImportSession applies.
+ $replaced = $session->replaced();
+ if ( $replaced instanceof ImportSession ) {
+ ImportSession::delete_staged_file( $replaced->file(), $replaced->attachment_id() );
+ }
+
+ // Not stored, or stored without a scheduled cleanup: either way the new staged file
+ // would have no owner, so the prepare fails and the file is removed now.
+ if ( ! $session->persisted() ) {
+ $this->discard_failed_upload( $file_path, $attachment_id );
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_session_failed',
+ __( 'The import session could not be saved. Please try again.', 'woocommerce' ),
+ array( 'status' => WP_Http::INTERNAL_SERVER_ERROR )
+ );
+ }
+
+ return array(
+ 'token' => $session->token(),
+ 'headers' => $parsed['headers'] ?? array(),
+ 'sample' => $parsed['sample'] ?? array(),
+ 'total' => $parsed['total'] ?? 0,
+ 'detected_mapping' => $this->mapping_for_response( (array) ( $parsed['detected_mapping'] ?? array() ) ),
+ 'delimiter' => $parsed['delimiter'] ?? ',',
+ );
+ }
+
+ /**
+ * Validate the multipart file, hand it to CSVUploadHelper, and return the staged file details.
+ *
+ * @since 11.4.0
+ *
+ * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+ * @param WP_REST_Request $request Incoming request carrying the multipart upload.
+ * @return array{file:string, id:int}|WP_Error Staged absolute path and the attachment post ID created for it.
+ */
+ protected function stage_uploaded_csv( WP_REST_Request $request ) {
+ $files = $request->get_file_params();
+ if ( empty( $files['file'] ) ) {
+ return $this->no_file_error();
+ }
+
+ $rejected = $this->check_uploaded_file( $files['file'] );
+ if ( $rejected instanceof WP_Error ) {
+ return $rejected;
+ }
+
+ return $this->store_uploaded_file( $files['file'] );
+ }
+
+ /**
+ * Check an uploaded file against the site's upload limit and PHP's upload result.
+ *
+ * Nothing is stored yet, so a rejection here leaves nothing to clean up.
+ *
+ * @param array $file Multipart file entry, in the $_FILES format.
+ * @return WP_Error|null The error to return, or null when the file can be stored.
+ */
+ private function check_uploaded_file( array $file ): ?WP_Error {
+ // On multisite WordPress hooks fix_import_form_size() onto this filter on every request
+ // but defines it in wp-admin/includes/ms.php, which only wp-admin loads.
+ if ( is_multisite() && ! function_exists( 'fix_import_form_size' ) ) {
+ require_once ABSPATH . 'wp-admin/includes/ms.php';
+ }
+
+ /** This filter is documented in wp-admin/includes/import.php. */
+ $upload_limit = (int) apply_filters( 'import_upload_size_limit', wp_max_upload_size() ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingSinceComment
+
+ // On multisite the limit is the site's remaining upload space, so 0 means no space left
+ // and no file could be stored, whatever PHP reported for it.
+ if ( $upload_limit <= 0 ) {
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_file_too_large',
+ __( 'This site has no upload space left for the file.', 'woocommerce' ),
+ array( 'status' => WP_Http::REQUEST_ENTITY_TOO_LARGE )
+ );
+ }
+
+ // PHP reports a file it refused for size with error 1 or 2 and size 0, so the error
+ // code is checked before the size, or the merchant would get the generic message.
+ $upload_error = (int) ( $file['error'] ?? UPLOAD_ERR_OK );
+ if ( UPLOAD_ERR_INI_SIZE === $upload_error || UPLOAD_ERR_FORM_SIZE === $upload_error ) {
+ return $this->file_too_large_error( $upload_limit );
+ }
+ if ( UPLOAD_ERR_NO_FILE === $upload_error ) {
+ return $this->no_file_error();
+ }
+ if ( UPLOAD_ERR_OK !== $upload_error ) {
+ wc_get_logger()->warning(
+ sprintf( 'Fulfillments importer upload rejected by PHP with upload error code %d.', $upload_error ),
+ array( 'source' => 'fulfillments-importer' )
+ );
+ return $this->upload_failed_error();
+ }
+
+ $file_size = (int) ( $file['size'] ?? 0 );
+ if ( 0 === $file_size ) {
+ return new WP_Error(
+ 'woocommerce_fulfillments_csv_parse_error',
+ __( 'CSV file is empty.', 'woocommerce' ),
+ array(
+ 'status' => WP_Http::BAD_REQUEST,
+ 'reason' => 'empty_csv',
+ )
+ );
+ }
+ if ( $file_size > $upload_limit ) {
+ return $this->file_too_large_error( $upload_limit );
+ }
+
+ return null;
+ }
+
+ /**
+ * Store a checked file under wc-imports through CSVUploadHelper.
+ *
+ * Every failure removes whatever this call stored. CSVUploadHelper can throw after the
+ * file and its attachment exist (when wc_is_file_valid_csv() rejects the stored file), and
+ * its exception does not say what it stored, so the stored path and attachment are
+ * recorded from the upload hooks while the helper runs.
+ *
+ * @param array $file Multipart file entry, in the $_FILES format.
+ * @return array{file:string, id:int}|WP_Error Staged absolute path and the attachment post ID created for it.
+ */
+ private function store_uploaded_file( array $file ) {
+ // CSVUploadHelper ultimately calls wp_handle_upload(), which is only loaded
+ // on wp-admin page loads; REST requests must pull it in explicitly.
+ if ( ! function_exists( 'wp_handle_upload' ) ) {
+ require_once ABSPATH . 'wp-admin/includes/file.php';
+ }
+
+ $stored = array(
+ 'file' => '',
+ 'id' => 0,
+ );
+
+ // Runs last, so it sees the path after any other filter changed it.
+ $record_file = static function ( $upload ) use ( &$stored ) {
+ if ( is_array( $upload ) && empty( $upload['error'] ) && isset( $upload['file'] ) && is_string( $upload['file'] ) ) {
+ $stored['file'] = $upload['file'];
+ }
+ return $upload;
+ };
+ // Runs first, so the attachment for the stored file is recorded before any other
+ // callback could insert one of its own.
+ $record_attachment = static function ( $post_id ) use ( &$stored ) {
+ if ( 0 === $stored['id'] && '' !== $stored['file'] ) {
+ $stored['id'] = (int) $post_id;
+ }
+ };
+
+ // CSVUploadHelper reads from $_FILES under a configurable key. Stage the REST file under
+ // that key and unset it again in finally so the assignment cannot outlive this call.
+ $_FILES['fulfillment_import_file'] = $file;
+ add_filter( 'wp_handle_upload', $record_file, PHP_INT_MAX );
+ add_action( 'add_attachment', $record_attachment, PHP_INT_MIN );
+ try {
+ try {
+ $upload = $this->csv_upload_helper->handle_csv_upload(
+ 'fulfillment',
+ 'fulfillment_import_file',
+ array(
+ 'csv' => 'text/csv',
+ 'txt' => 'text/plain',
+ )
+ );
+ $stored = array(
+ 'file' => (string) ( $upload['file'] ?? '' ),
+ 'id' => (int) ( $upload['id'] ?? 0 ),
+ );
+
+ FilesystemUtil::validate_upload_file_path( $stored['file'] );
+
+ // Every later delete of this path refuses anything outside wc-imports, so a file an
+ // upload_dir filter moved elsewhere is refused here, while it can still be discarded.
+ if ( ! ImportSession::is_staged_path( $stored['file'] ) ) {
+ $this->discard_failed_upload( $stored['file'], $stored['id'] );
+ wc_get_logger()->warning(
+ sprintf( 'Fulfillments importer upload rejected: the staged file is outside the import directory: %s', $stored['file'] ),
+ array( 'source' => 'fulfillments-importer' )
+ );
+ return $this->upload_failed_error();
+ }
+ } catch ( \Exception $e ) {
+ // The upload handler's message can carry server paths, so it is logged, not returned.
+ $this->discard_failed_upload( $stored['file'], $stored['id'] );
+ wc_get_logger()->warning(
+ 'Fulfillments importer upload rejected: ' . html_entity_decode( $e->getMessage(), ENT_QUOTES, 'UTF-8' ),
+ array( 'source' => 'fulfillments-importer' )
+ );
+ return $this->upload_failed_error();
+ } catch ( \Throwable $e ) {
+ $this->discard_failed_upload( $stored['file'], $stored['id'] );
+ wc_get_logger()->error(
+ 'Fulfillments importer upload failed: ' . html_entity_decode( $e->getMessage(), ENT_QUOTES, 'UTF-8' ),
+ array( 'source' => 'fulfillments-importer' )
+ );
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_upload_failed',
+ __( 'The upload could not be processed. Please try again.', 'woocommerce' ),
+ array( 'status' => WP_Http::INTERNAL_SERVER_ERROR )
+ );
+ }
+ } finally {
+ remove_filter( 'wp_handle_upload', $record_file, PHP_INT_MAX );
+ remove_action( 'add_attachment', $record_attachment, PHP_INT_MIN );
+ unset( $_FILES['fulfillment_import_file'] );
+ }
+
+ return $stored;
+ }
+
+ /**
+ * Build the 400 error for a request without a file.
+ *
+ * @return WP_Error
+ */
+ private function no_file_error(): WP_Error {
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_no_file',
+ __( 'No CSV file was uploaded.', 'woocommerce' ),
+ array( 'status' => WP_Http::BAD_REQUEST )
+ );
+ }
+
+ /**
+ * Build the 400 error for a file that could not be uploaded or staged.
+ *
+ * The message is fixed because the underlying reason can carry server paths; the reason is logged instead.
+ *
+ * @return WP_Error
+ */
+ private function upload_failed_error(): WP_Error {
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_upload_failed',
+ __( 'The file could not be uploaded.', 'woocommerce' ),
+ array( 'status' => WP_Http::BAD_REQUEST )
+ );
+ }
+
+ /**
+ * Build the 413 error for an upload above the size limit.
+ *
+ * @param int $upload_limit Effective limit in bytes.
+ * @return WP_Error
+ */
+ private function file_too_large_error( int $upload_limit ): WP_Error {
+ return new WP_Error(
+ 'woocommerce_fulfillments_import_file_too_large',
+ sprintf(
+ /* translators: %s: human-readable maximum upload size, e.g. "8 MB". */
+ __( 'The uploaded file is larger than the allowed maximum of %s.', 'woocommerce' ),
+ size_format( $upload_limit )
+ ),
+ array( 'status' => WP_Http::REQUEST_ENTITY_TOO_LARGE )
+ );
+ }
+
+ /**
+ * Remove a file this request just staged, including its attachment post.
+ *
+ * Only for a path the upload handler stored in this request, whether returned by
+ * stage_uploaded_csv() or recorded by store_uploaded_file() before a throw: it is wherever
+ * the upload handler wrote it, so no containment check applies and a misplaced file is
+ * still removed. A path read back from a session goes through
+ * ImportSession::delete_staged_file() instead.
+ *
+ * @param string $file Staged absolute path; may be empty when staging never completed.
+ * @param int $attachment_id Attachment post created by the upload handler; 0 when none.
+ */
+ private function discard_failed_upload( string $file, int $attachment_id ): void {
+ if ( $attachment_id > 0 ) {
+ wp_delete_attachment( $attachment_id, true );
+ }
+ if ( '' !== $file && file_exists( $file ) ) {
+ wp_delete_file( $file );
+ }
+ }
+
+ /**
+ * Shape the detected mapping so it always serializes as a JSON object.
+ *
+ * PHP canonicalizes numeric string keys back to int, so a mapping over contiguous
+ * columns starting at 0 would otherwise encode as a JSON array and break the object
+ * shape declared in the response schema.
+ *
+ * @param array<int, string> $mapping CSV column index => canonical key.
+ * @return \stdClass Column index => canonical key.
+ */
+ private function mapping_for_response( array $mapping ): \stdClass {
+ $out = array();
+ foreach ( $mapping as $col => $canonical ) {
+ $out[ (string) $col ] = (string) $canonical;
+ }
+ return (object) $out;
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/FulfillmentsControllerTest.php b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/FulfillmentsControllerTest.php
index ed5172a9861..f1b4a1a09a5 100644
--- a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/FulfillmentsControllerTest.php
+++ b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/FulfillmentsControllerTest.php
@@ -6,6 +6,7 @@ namespace Automattic\WooCommerce\Tests\Admin\Features\Fulfillments;
use Automattic\WooCommerce\Admin\Features\Fulfillments\DataStore\FulfillmentsDataStore;
use Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentsController;
use Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentsPrivacy;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\FulfillmentsImporterRestController;
use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\ImportSession;
use Automattic\WooCommerce\Internal\Features\FeaturesController;
use WC_Unit_Test_Case;
@@ -36,6 +37,38 @@ class FulfillmentsControllerTest extends WC_Unit_Test_Case {
*/
private $original_tables_created;
+ /**
+ * Feature flag value before the class enabled the feature.
+ *
+ * @var mixed
+ */
+ private static $class_fulfillments_flag;
+
+ /**
+ * Create the fulfillment tables once, outside the per-test transaction.
+ *
+ * initialize_fulfillments() creates the tables lazily when the flag is on. That is
+ * DDL, which must not run inside a test transaction, so it runs here first.
+ */
+ public static function wpSetUpBeforeClass(): void {
+ self::$class_fulfillments_flag = get_option( 'woocommerce_feature_fulfillments_enabled' );
+ update_option( 'woocommerce_feature_fulfillments_enabled', 'yes' );
+ $controller = wc_get_container()->get( FulfillmentsController::class );
+ $controller->register();
+ $controller->initialize_fulfillments();
+ }
+
+ /**
+ * Restore the feature flag the class changed.
+ */
+ public static function wpTearDownAfterClass(): void {
+ if ( false === self::$class_fulfillments_flag ) {
+ delete_option( 'woocommerce_feature_fulfillments_enabled' );
+ } else {
+ update_option( 'woocommerce_feature_fulfillments_enabled', self::$class_fulfillments_flag );
+ }
+ }
+
/**
* Set up test fixtures.
*/
@@ -76,6 +109,23 @@ class FulfillmentsControllerTest extends WC_Unit_Test_Case {
$this->assertSame( 10, has_action( ImportSession::CLEANUP_HOOK, array( ImportSession::class, 'handle_cleanup_hook' ) ), 'register() must attach the cleanup handler at priority 10 while the feature is off' );
}
+ /**
+ * @testdox Should register the import REST controller only while the feature flag is on.
+ */
+ public function test_initialize_fulfillments_registers_import_rest_controller_only_when_enabled(): void {
+ $importer = wc_get_container()->get( FulfillmentsImporterRestController::class );
+ $callback = array( $importer, 'handle_woocommerce_rest_api_get_rest_namespaces' );
+ remove_filter( 'woocommerce_rest_api_get_rest_namespaces', $callback );
+
+ update_option( 'woocommerce_feature_fulfillments_enabled', 'no' );
+ $this->sut->initialize_fulfillments();
+ $this->assertFalse( has_filter( 'woocommerce_rest_api_get_rest_namespaces', $callback ), 'The prepare route must not be registered while the feature is off' );
+
+ update_option( 'woocommerce_feature_fulfillments_enabled', 'yes' );
+ $this->sut->initialize_fulfillments();
+ $this->assertSame( 10, has_filter( 'woocommerce_rest_api_get_rest_namespaces', $callback ), 'The prepare route is registered once the feature is on' );
+ }
+
/**
* @testdox Should register the order-fulfillment data store when feature is enabled.
*/
diff --git a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsImporterRestControllerTest.php b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsImporterRestControllerTest.php
new file mode 100644
index 00000000000..3dd735aaf2a
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsImporterRestControllerTest.php
@@ -0,0 +1,1057 @@
+<?php declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Tests\Admin\Features\Fulfillments\Importer;
+
+use Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentsController;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\FulfillmentsCsvImporter;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\FulfillmentsImporterRestController;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\ImportSession;
+use Automattic\WooCommerce\Internal\Admin\ImportExport\CSVUploadHelper;
+use WC_REST_Unit_Test_Case;
+use WP_REST_Request;
+
+/**
+ * Integration tests for the importer REST routes.
+ */
+class FulfillmentsImporterRestControllerTest extends WC_REST_Unit_Test_Case {
+
+ /**
+ * Original fulfillments feature flag value.
+ *
+ * @var mixed
+ */
+ private static $original_fulfillments_flag;
+
+ /**
+ * Admin user ID for permission checks.
+ *
+ * @var int
+ */
+ private static int $admin_id;
+
+ /**
+ * Temporary CSV files created by tests; removed in tearDown.
+ *
+ * @var array<int, string>
+ */
+ private array $temp_files = array();
+
+ /**
+ * The System Under Test.
+ *
+ * @var FulfillmentsImporterRestController
+ */
+ private FulfillmentsImporterRestController $sut;
+
+ /**
+ * Bootstrap the fulfillments feature and create an admin user.
+ */
+ public static function setUpBeforeClass(): void {
+ parent::setUpBeforeClass();
+ self::$original_fulfillments_flag = get_option( 'woocommerce_feature_fulfillments_enabled' );
+ update_option( 'woocommerce_feature_fulfillments_enabled', 'yes' );
+ $sut = wc_get_container()->get( FulfillmentsController::class );
+ $sut->register();
+ $sut->initialize_fulfillments();
+
+ $result = wp_insert_user(
+ array(
+ 'user_login' => 'fulfill_admin_' . wp_generate_password( 6, false ),
+ 'user_pass' => wp_generate_password( 12, false ),
+ 'role' => 'administrator',
+ )
+ );
+ if ( is_wp_error( $result ) ) {
+ throw new \RuntimeException( 'Failed to create admin user: ' . esc_html( $result->get_error_message() ) );
+ }
+ self::$admin_id = (int) $result;
+ }
+
+ /**
+ * Tear down the feature flag and the admin user.
+ */
+ public static function tearDownAfterClass(): void {
+ if ( self::$admin_id > 0 ) {
+ wp_delete_user( self::$admin_id );
+ }
+ if ( false === self::$original_fulfillments_flag ) {
+ delete_option( 'woocommerce_feature_fulfillments_enabled' );
+ } else {
+ update_option( 'woocommerce_feature_fulfillments_enabled', self::$original_fulfillments_flag );
+ }
+ parent::tearDownAfterClass();
+ }
+
+ /**
+ * Sign in as admin and register the controller for this test.
+ *
+ * The hook snapshot the WP test case restores after every test predates this class, so
+ * hooks added in setUpBeforeClass() only survive the first test. Registering here keeps
+ * the namespace filter in place for each test.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ wp_set_current_user( (int) self::$admin_id );
+ $this->sut = wc_get_container()->get( FulfillmentsImporterRestController::class );
+ $this->sut->register();
+ }
+
+ /**
+ * Clean up files and container replacements created during the test.
+ *
+ * Sessions, attachments and scheduled actions are database rows the test
+ * transaction rolls back; files and container state are not.
+ */
+ public function tearDown(): void {
+ foreach ( $this->temp_files as $path ) {
+ if ( file_exists( $path ) ) {
+ wp_delete_file( $path );
+ }
+ }
+ $this->temp_files = array();
+ $this->reset_container_replacements();
+ $this->reset_container_resolutions();
+ parent::tearDown();
+ }
+
+ /**
+ * Write a file inside the uploads directory and track it for cleanup.
+ *
+ * @param string $content File content.
+ * @param string $extension File extension without the dot.
+ * @return string
+ */
+ private function make_staged_file( string $content, string $extension = 'csv' ): string {
+ // Stage inside wc-imports, like CSVUploadHelper does in production, so the
+ // controller's staged-path containment checks hold in tests.
+ $dir = wc_get_container()->get( CSVUploadHelper::class )->get_import_dir();
+ $path = trailingslashit( $dir ) . 'wc-fulfillments-rest-' . wp_generate_uuid4() . '.' . $extension;
+ file_put_contents( $path, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture write.
+ $this->temp_files[] = $path;
+ return $path;
+ }
+
+ /**
+ * Create an attachment post for a staged file.
+ *
+ * @param string $file Absolute path of the staged file.
+ * @return int
+ */
+ private function make_attachment( string $file ): int {
+ $attachment_id = wp_insert_attachment(
+ array(
+ 'post_title' => 'Fulfillments import test CSV',
+ 'post_mime_type' => 'text/csv',
+ ),
+ $file
+ );
+ $this->assertIsInt( $attachment_id );
+ $this->assertGreaterThan( 0, $attachment_id );
+ return $attachment_id;
+ }
+
+ /**
+ * Open a session for the admin user over a staged file.
+ *
+ * @param string $file Absolute path of the staged file.
+ * @param int $attachment_id Attachment post for the file.
+ * @return ImportSession
+ */
+ private function make_session( string $file, int $attachment_id = 0 ): ImportSession {
+ $session = ImportSession::create(
+ get_current_user_id(),
+ $file,
+ ',',
+ array( 'order_number', 'tracking_number', 'shipment_provider' ),
+ 1,
+ false,
+ true,
+ $attachment_id
+ );
+ $this->assertTrue( $session->persisted() );
+ return $session;
+ }
+
+ /**
+ * Build a controller whose staging step returns a canned path instead of a real upload.
+ *
+ * is_uploaded_file() can never pass for files created inside a test process, so this
+ * stubs the staging seam and exercises everything handle_prepare does after it.
+ *
+ * @param string $file Path to return as the staged file.
+ * @param int $attachment_id Attachment ID to return with it.
+ * @param callable|null $on_stage Runs while the upload is being staged, to simulate another request landing in between.
+ * @return FulfillmentsImporterRestController
+ */
+ private function make_controller_with_staged_file( string $file, int $attachment_id = 0, ?callable $on_stage = null ): FulfillmentsImporterRestController {
+ $sut = new class() extends FulfillmentsImporterRestController {
+ /**
+ * Path returned instead of staging a real upload.
+ *
+ * @var string
+ */
+ public string $staged = '';
+
+ /**
+ * Attachment ID returned with the staged path.
+ *
+ * @var int
+ */
+ public int $staged_attachment = 0;
+
+ /**
+ * Callback run while staging, before the canned path is returned.
+ *
+ * @var callable|null
+ */
+ public $on_stage = null;
+
+ /**
+ * Return the canned staged path.
+ *
+ * @param WP_REST_Request $request Unused.
+ * @return array{file:string, id:int}
+ */
+ protected function stage_uploaded_csv( WP_REST_Request $request ) {
+ unset( $request );
+ if ( is_callable( $this->on_stage ) ) {
+ call_user_func( $this->on_stage );
+ }
+ return array(
+ 'file' => $this->staged,
+ 'id' => $this->staged_attachment,
+ );
+ }
+ };
+
+ $sut->init( wc_get_container()->get( CSVUploadHelper::class ) );
+ $sut->staged = $file;
+ $sut->staged_attachment = $attachment_id;
+ $sut->on_stage = $on_stage;
+ return $sut;
+ }
+
+ /**
+ * Build a controller whose upload helper is replaced by a mock.
+ *
+ * The helper is injected through init() when the container resolves the controller, so the
+ * replacement has to be registered before a fresh controller is resolved.
+ *
+ * @param CSVUploadHelper $helper Mocked helper.
+ * @return FulfillmentsImporterRestController
+ */
+ private function controller_with_helper( CSVUploadHelper $helper ): FulfillmentsImporterRestController {
+ wc_get_container()->replace( CSVUploadHelper::class, $helper );
+ $this->reset_container_resolutions();
+ return wc_get_container()->get( FulfillmentsImporterRestController::class );
+ }
+
+ /**
+ * Build a multipart file entry the way PHP populates $_FILES.
+ *
+ * @param string $name Client file name.
+ * @param int $error PHP upload error code.
+ * @param int $size Reported size in bytes.
+ * @return array<string, array<string, mixed>>
+ */
+ private function file_params( string $name = 'sample.csv', int $error = UPLOAD_ERR_OK, int $size = 20 ): array {
+ return array(
+ 'file' => array(
+ 'name' => $name,
+ 'type' => 'text/csv',
+ 'tmp_name' => UPLOAD_ERR_OK === $error ? '/tmp/does-not-matter.csv' : '',
+ 'error' => $error,
+ 'size' => $size,
+ ),
+ );
+ }
+
+ /**
+ * Invoke a protected handler on a controller.
+ *
+ * @param string $method Handler method name.
+ * @param WP_REST_Request $request Built request.
+ * @param FulfillmentsImporterRestController|null $sut Controller to invoke; the container's one by default.
+ * @return mixed
+ */
+ private function invoke( string $method, WP_REST_Request $request, ?FulfillmentsImporterRestController $sut = null ) {
+ $sut = $sut ?? $this->sut;
+ $reflection = new \ReflectionClass( $sut );
+ $handler = $reflection->getMethod( $method );
+ $handler->setAccessible( true );
+ return $handler->invoke( $sut, $request );
+ }
+
+ /**
+ * Build a prepare request with the default parameters.
+ *
+ * @return WP_REST_Request
+ */
+ private function make_prepare_request(): WP_REST_Request {
+ $request = new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' );
+ $request->set_param( 'delimiter', ',' );
+ $request->set_param( 'notify_customer', false );
+ $request->set_param( 'update_existing', true );
+ return $request;
+ }
+
+ /**
+ * Run handle_prepare against a staged file and return the handler result.
+ *
+ * @param string $file Staged file path.
+ * @param int $attachment_id Attachment ID for the staged file.
+ * @param callable|null $on_stage Runs while the upload is being staged.
+ * @return mixed
+ */
+ private function prepare_with_staged_file( string $file, int $attachment_id = 0, ?callable $on_stage = null ) {
+ $sut = $this->make_controller_with_staged_file( $file, $attachment_id, $on_stage );
+ return $this->invoke( 'handle_prepare', $this->make_prepare_request(), $sut );
+ }
+
+ /**
+ * Count the callbacks registered on a hook.
+ *
+ * @param string $hook_name Hook name.
+ * @return int
+ */
+ private function callback_count( string $hook_name ): int {
+ global $wp_filter;
+ if ( ! isset( $wp_filter[ $hook_name ] ) ) {
+ return 0;
+ }
+ return array_sum( array_map( 'count', $wp_filter[ $hook_name ]->callbacks ) );
+ }
+
+ /**
+ * Build a CSV with the given number of data rows.
+ *
+ * @param int $rows Number of data rows.
+ * @return string
+ */
+ private function csv_with_rows( int $rows ): string {
+ $csv = "order_number,tracking_number,shipment_provider\n";
+ for ( $i = 1; $i <= $rows; $i++ ) {
+ $csv .= "1,CAP-{$i},ups\n";
+ }
+ return $csv;
+ }
+
+ /**
+ * @testdox register() exposes the prepare route on the REST server through the WooCommerce namespace filter.
+ */
+ public function test_register_exposes_prepare_route(): void {
+ $this->assertSame( 10, has_filter( 'woocommerce_rest_api_get_rest_namespaces', array( $this->sut, 'handle_woocommerce_rest_api_get_rest_namespaces' ) ) );
+ $this->assertArrayHasKey( '/wc/v3/fulfillments/import/prepare', rest_get_server()->get_routes( 'wc/v3' ) );
+ }
+
+ /**
+ * @testdox handle_prepare parses the staged CSV and opens a session bound to the current user.
+ */
+ public function test_prepare_stages_csv_and_opens_session(): void {
+ $file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n1001,TRK-1,ups\n" );
+
+ $response = $this->prepare_with_staged_file( $file );
+
+ $this->assertIsArray( $response );
+ $this->assertArrayHasKey( 'token', $response );
+ $this->assertSame( 1, $response['total'] );
+ $this->assertSame( array( 'order_number', 'tracking_number', 'shipment_provider' ), $response['headers'] );
+ $this->assertSame( array( '1001', 'TRK-1', 'ups' ), $response['sample'] );
+ $this->assertSame( ',', $response['delimiter'] );
+
+ $session = ImportSession::load( get_current_user_id(), (string) $response['token'] );
+ $this->assertNotNull( $session );
+ $this->assertSame( $file, $session->file() );
+ $this->assertSame( $response['headers'], $session->headers() );
+ $this->assertSame( 1, $session->total() );
+ $this->assertSame( ',', $session->delimiter() );
+ $this->assertFalse( $session->notify_customer(), 'The default notify_customer must be stored' );
+ $this->assertTrue( $session->update_existing(), 'The default update_existing must be stored' );
+ $this->assertFileExists( $file, 'The staged file must stay in place for the import run' );
+
+ // Contiguous 0-based column indexes would encode as a JSON array without the cast.
+ $this->assertJsonStringEqualsJsonString(
+ '{"0":"order_number","1":"tracking_number","2":"shipment_provider"}',
+ (string) wp_json_encode( $response['detected_mapping'] )
+ );
+ }
+
+ /**
+ * @testdox handle_prepare accepts a CSV with exactly the maximum number of rows.
+ */
+ public function test_prepare_accepts_csv_at_row_cap(): void {
+ $file = $this->make_staged_file( $this->csv_with_rows( FulfillmentsCsvImporter::MAX_IMPORT_ROWS ) );
+
+ $response = $this->prepare_with_staged_file( $file );
+
+ $this->assertIsArray( $response );
+ $this->assertSame( FulfillmentsCsvImporter::MAX_IMPORT_ROWS, $response['total'] );
+ }
+
+ /**
+ * @testdox handle_prepare rejects a CSV with one row more than the importer supports.
+ */
+ public function test_prepare_rejects_csv_over_row_cap(): void {
+ $file = $this->make_staged_file( $this->csv_with_rows( FulfillmentsCsvImporter::MAX_IMPORT_ROWS + 1 ) );
+
+ $response = $this->prepare_with_staged_file( $file );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_too_many_rows', $response->get_error_code() );
+ $this->assertSame( 413, $response->get_error_data()['status'] );
+ $this->assertFileDoesNotExist( $file, 'The staged file must be cleaned up when the row cap rejects it' );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ }
+
+ /**
+ * @testdox handle_prepare rejects a file far over the cap, where the importer reports a capped total, and removes its attachment.
+ */
+ public function test_prepare_rejects_capped_total_and_removes_attachment(): void {
+ $file = $this->make_staged_file( $this->csv_with_rows( FulfillmentsCsvImporter::MAX_IMPORT_ROWS + 2 ) );
+ $attachment_id = $this->make_attachment( $file );
+
+ $response = $this->prepare_with_staged_file( $file, $attachment_id );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_too_many_rows', $response->get_error_code() );
+ $this->assertSame( 413, $response->get_error_data()['status'] );
+ $this->assertStringContainsString( number_format_i18n( FulfillmentsCsvImporter::MAX_IMPORT_ROWS ), $response->get_error_message(), 'The message names the cap, never the capped total' );
+ $this->assertFileDoesNotExist( $file );
+ $this->assertNull( get_post( $attachment_id ), 'The attachment must go with the staged file on the 413 path' );
+ }
+
+ /**
+ * @testdox handle_prepare stores the notify_customer and update_existing values on the session.
+ */
+ public function test_prepare_stores_notify_and_update_flags_on_the_session(): void {
+ $file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n1001,TRK-1,ups\n" );
+ $sut = $this->make_controller_with_staged_file( $file );
+ $request = $this->make_prepare_request();
+ $request->set_param( 'notify_customer', true );
+ $request->set_param( 'update_existing', false );
+
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->assertIsArray( $response );
+ $session = ImportSession::load( get_current_user_id(), (string) $response['token'] );
+ $this->assertNotNull( $session );
+ $this->assertTrue( $session->notify_customer() );
+ $this->assertFalse( $session->update_existing() );
+ }
+
+ /**
+ * @testdox A replaced session whose file sits outside wc-imports keeps that file and its attachment.
+ */
+ public function test_prepare_keeps_a_replaced_sessions_file_outside_the_import_directory(): void {
+ $media = trailingslashit( wp_upload_dir()['basedir'] ) . 'wc-fulfillments-rest-' . wp_generate_uuid4() . '.jpg';
+ file_put_contents( $media, 'not a csv' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture write.
+ $this->temp_files[] = $media;
+ $media_attachment = $this->make_attachment( $media );
+ $prior = $this->make_session( $media, $media_attachment );
+ $new_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n2,NEW-1,ups\n" );
+
+ $response = $this->prepare_with_staged_file( $new_file );
+
+ $this->assertIsArray( $response );
+ $this->assertNull( ImportSession::load( get_current_user_id(), $prior->token() ), 'The prior session record is still replaced' );
+ $this->assertFileExists( $media, 'A session path outside wc-imports must not be deleted' );
+ $this->assertNotNull( get_post( $media_attachment ), 'Its attachment must not be deleted' );
+
+ wp_delete_file( $media );
+ $this->assertNotNull( get_post( $media_attachment ) );
+ $again = $this->make_session( $media, $media_attachment );
+ $this->prepare_with_staged_file( $this->make_staged_file( "order_number,tracking_number,shipment_provider\n3,NEW-2,ups\n" ) );
+ $this->assertNull( ImportSession::load( get_current_user_id(), $again->token() ) );
+ $this->assertNotNull( get_post( $media_attachment ), 'The containment check must run for a missing file too' );
+ }
+
+ /**
+ * @testdox handle_prepare rejects a header-only CSV and removes the staged file.
+ */
+ public function test_prepare_rejects_header_only_csv(): void {
+ $file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n" );
+ $attachment_id = $this->make_attachment( $file );
+
+ $response = $this->prepare_with_staged_file( $file, $attachment_id );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_csv_parse_error', $response->get_error_code() );
+ $this->assertSame( 'The CSV file has no data rows.', $response->get_error_message() );
+ $this->assertSame( 400, $response->get_error_data()['status'] );
+ $this->assertFileDoesNotExist( $file );
+ $this->assertNull( get_post( $attachment_id ), 'The attachment post must go with the staged file' );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ }
+
+ /**
+ * @testdox handle_prepare removes the staged file when the header cannot be parsed.
+ */
+ public function test_prepare_removes_staged_file_on_parse_error(): void {
+ $file = $this->make_staged_file( '' );
+ $attachment_id = $this->make_attachment( $file );
+
+ $response = $this->prepare_with_staged_file( $file, $attachment_id );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_csv_parse_error', $response->get_error_code() );
+ $this->assertSame( 'CSV file is empty.', $response->get_error_message() );
+ $this->assertFileDoesNotExist( $file );
+ $this->assertNull( get_post( $attachment_id ) );
+ }
+
+ /**
+ * @testdox A successful upload replaces the prior session and removes its staged file and attachment.
+ */
+ public function test_prepare_replaces_prior_session_after_successful_upload(): void {
+ $prior_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n1,OLD-1,ups\n" );
+ $prior_attachment = $this->make_attachment( $prior_file );
+ $prior = $this->make_session( $prior_file, $prior_attachment );
+ $new_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n2,NEW-1,ups\n" );
+
+ $response = $this->prepare_with_staged_file( $new_file );
+
+ $this->assertIsArray( $response );
+ $this->assertNotSame( $prior->token(), $response['token'] );
+ $active = ImportSession::active_for_user( get_current_user_id() );
+ $this->assertNotNull( $active );
+ $this->assertSame( $response['token'], $active->token() );
+ $this->assertNull( ImportSession::load( get_current_user_id(), $prior->token() ), 'The prior session record must be gone' );
+ $this->assertFileDoesNotExist( $prior_file, 'The prior staged file must be removed' );
+ $this->assertNull( get_post( $prior_attachment ), 'The prior attachment post must be removed' );
+ $this->assertFileExists( $new_file );
+ }
+
+ /**
+ * @testdox Two overlapping prepares by the same user each remove the staged file of the session they replaced.
+ */
+ public function test_prepare_deletes_file_of_session_replaced_at_create_time(): void {
+ $prior_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n1,OLD-1,ups\n" );
+ $prior = $this->make_session( $prior_file );
+ $a_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n2,A-1,ups\n" );
+ $a_attach = $this->make_attachment( $a_file );
+ $b_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n3,B-1,ups\n" );
+ $a_session = null;
+
+ // Request A finishes while request B is still staging its upload: it replaces the
+ // prior session and removes the prior staged file, as handle_prepare would.
+ $request_a = function () use ( $a_file, $a_attach, $prior_file, &$a_session ) {
+ $a_session = $this->make_session( $a_file, $a_attach );
+ wp_delete_file( $prior_file );
+ };
+
+ $response = $this->prepare_with_staged_file( $b_file, 0, $request_a );
+
+ $this->assertIsArray( $response );
+ $this->assertInstanceOf( ImportSession::class, $a_session );
+ $this->assertNull( ImportSession::load( get_current_user_id(), $prior->token() ) );
+ $this->assertNull( ImportSession::load( get_current_user_id(), $a_session->token() ), 'Request B retired request A\'s session' );
+ $this->assertFileDoesNotExist( $a_file, 'Request B must remove the staged file of the session it retired' );
+ $this->assertNull( get_post( $a_attach ), 'Request B must remove the attachment of the session it retired' );
+ $this->assertFileExists( $b_file );
+ $active = ImportSession::active_for_user( get_current_user_id() );
+ $this->assertNotNull( $active );
+ $this->assertSame( $response['token'], $active->token() );
+ }
+
+ /**
+ * @testdox handle_prepare fails with a 500 and removes the staged file when the cleanup cannot be scheduled.
+ */
+ public function test_prepare_fails_when_cleanup_cannot_be_scheduled(): void {
+ $file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n1001,TRK-1,ups\n" );
+ $attachment_id = $this->make_attachment( $file );
+
+ $fail_schedule = static function () {
+ return 0;
+ };
+ add_filter( 'pre_as_schedule_single_action', $fail_schedule );
+ try {
+ $response = $this->prepare_with_staged_file( $file, $attachment_id );
+ } finally {
+ remove_filter( 'pre_as_schedule_single_action', $fail_schedule );
+ }
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_session_failed', $response->get_error_code() );
+ $this->assertSame( 500, $response->get_error_data()['status'] );
+ $this->assertFileDoesNotExist( $file, 'A staged file with no cleanup owner must not be left behind' );
+ $this->assertNull( get_post( $attachment_id ) );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ }
+
+ /**
+ * @testdox A rejected upload leaves the prior session, its staged file and its attachment intact.
+ */
+ public function test_prepare_keeps_prior_session_after_rejected_upload(): void {
+ $prior_file = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n1,OLD-1,ups\n" );
+ $prior_attachment = $this->make_attachment( $prior_file );
+ $prior = $this->make_session( $prior_file, $prior_attachment );
+ $header_only = $this->make_staged_file( "order_number,tracking_number,shipment_provider\n" );
+
+ $response = $this->prepare_with_staged_file( $header_only );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $active = ImportSession::active_for_user( get_current_user_id() );
+ $this->assertNotNull( $active );
+ $this->assertSame( $prior->token(), $active->token() );
+ $this->assertFileExists( $prior_file );
+ $this->assertNotNull( get_post( $prior_attachment ) );
+ $this->assertFileDoesNotExist( $header_only );
+ }
+
+ /**
+ * @testdox A staged file the upload handler wrote outside wc-imports is rejected and removed together with its attachment.
+ */
+ public function test_prepare_discards_a_staged_file_outside_the_import_directory(): void {
+ $staged = trailingslashit( wp_upload_dir()['basedir'] ) . 'wc-fulfillments-rest-' . wp_generate_uuid4() . '.csv';
+ file_put_contents( $staged, "order_number,tracking_number,shipment_provider\n1,T-1,ups\n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture write.
+ $this->temp_files[] = $staged;
+ $attachment_id = $this->make_attachment( $staged );
+
+ $helper = $this->getMockBuilder( CSVUploadHelper::class )
+ ->onlyMethods( array( 'handle_csv_upload' ) )
+ ->getMock();
+ $helper->method( 'handle_csv_upload' )->willReturn(
+ array(
+ 'id' => $attachment_id,
+ 'file' => $staged,
+ )
+ );
+ $sut = $this->controller_with_helper( $helper );
+
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params() );
+
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_upload_failed', $response->get_error_code() );
+ $this->assertSame( 400, $response->get_error_data()['status'] );
+ $this->assertFileDoesNotExist( $staged, 'A misplaced upload is still removed' );
+ $this->assertNull( get_post( $attachment_id ) );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ $this->assertArrayNotHasKey( 'fulfillment_import_file', $_FILES ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Asserting the superglobal was restored, not reading input.
+ }
+
+ /**
+ * @testdox A staged file passes the real pipeline when the helper stages it inside wc-imports.
+ */
+ public function test_prepare_succeeds_over_the_rest_server_with_a_mocked_upload(): void {
+ $staged = $this->make_staged_file( "order_number\ttracking_number\tshipment_provider\n1001\tTRK-1\tups\n" );
+ $attachment_id = $this->make_attachment( $staged );
+
+ $helper = $this->getMockBuilder( CSVUploadHelper::class )
+ ->onlyMethods( array( 'handle_csv_upload' ) )
+ ->getMock();
+ $helper->method( 'handle_csv_upload' )->willReturn(
+ array(
+ 'id' => $attachment_id,
+ 'file' => $staged,
+ )
+ );
+ $this->controller_with_helper( $helper )->register();
+
+ $request = new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' );
+ $request->set_body_params( array( 'delimiter' => 'tab' ) );
+ $request->set_file_params( $this->file_params( 'sample.txt' ) );
+
+ $response = rest_do_request( $request );
+ $data = $response->get_data();
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertSame( "\t", $data['delimiter'], 'The tab spelling must reach the importer as a tab' );
+ $this->assertSame( array( 'order_number', 'tracking_number', 'shipment_provider' ), $data['headers'] );
+ $this->assertSame( 1, $data['total'] );
+ $this->assertJsonStringEqualsJsonString(
+ '{"0":"order_number","1":"tracking_number","2":"shipment_provider"}',
+ (string) wp_json_encode( $data['detected_mapping'] )
+ );
+ $session = ImportSession::load( get_current_user_id(), (string) $data['token'] );
+ $this->assertNotNull( $session );
+ $this->assertSame( "\t", $session->delimiter() );
+ $this->assertFileExists( $staged );
+ }
+
+ /**
+ * @testdox PHP upload errors are mapped to the matching error code before the helper runs.
+ *
+ * @testWith [1, "woocommerce_fulfillments_import_file_too_large", 413]
+ * [2, "woocommerce_fulfillments_import_file_too_large", 413]
+ * [4, "woocommerce_fulfillments_import_no_file", 400]
+ * [3, "woocommerce_fulfillments_import_upload_failed", 400]
+ *
+ * @param int $error PHP upload error code.
+ * @param string $code Expected error code.
+ * @param int $status Expected status.
+ */
+ public function test_prepare_maps_php_upload_errors( int $error, string $code, int $status ): void {
+ $helper = $this->getMockBuilder( CSVUploadHelper::class )
+ ->onlyMethods( array( 'handle_csv_upload' ) )
+ ->getMock();
+ $helper->expects( $this->never() )->method( 'handle_csv_upload' );
+ $sut = $this->controller_with_helper( $helper );
+
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params( 'big.csv', $error, 0 ) );
+
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( $code, $response->get_error_code() );
+ $this->assertSame( $status, $response->get_error_data()['status'] );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ }
+
+ /**
+ * @testdox A zero-byte upload gets the importer's empty-file message before the helper runs.
+ */
+ public function test_prepare_rejects_a_zero_byte_upload_as_an_empty_csv(): void {
+ $helper = $this->getMockBuilder( CSVUploadHelper::class )
+ ->onlyMethods( array( 'handle_csv_upload' ) )
+ ->getMock();
+ $helper->expects( $this->never() )->method( 'handle_csv_upload' );
+ $sut = $this->controller_with_helper( $helper );
+
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params( 'empty.csv', UPLOAD_ERR_OK, 0 ) );
+
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_csv_parse_error', $response->get_error_code() );
+ $this->assertSame( 'CSV file is empty.', $response->get_error_message() );
+ $this->assertSame( 400, $response->get_error_data()['status'] );
+ }
+
+ /**
+ * @testdox An error thrown by the upload helper returns a 500 with the fixed message.
+ */
+ public function test_prepare_returns_500_when_the_upload_helper_throws_an_error(): void {
+ $helper = $this->getMockBuilder( CSVUploadHelper::class )
+ ->onlyMethods( array( 'handle_csv_upload' ) )
+ ->getMock();
+ $helper->method( 'handle_csv_upload' )->willThrowException( new \TypeError( 'wp_import_handle_upload(): Argument #1 must be of type array' ) );
+ $sut = $this->controller_with_helper( $helper );
+
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params() );
+
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_upload_failed', $response->get_error_code() );
+ $this->assertSame( 500, $response->get_error_data()['status'] );
+ $this->assertStringNotContainsString( 'wp_import_handle_upload', $response->get_error_message() );
+ $this->assertArrayNotHasKey( 'fulfillment_import_file', $_FILES ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Asserting the superglobal was restored, not reading input.
+ }
+
+ /**
+ * @testdox A throw from the upload helper after it stored the file removes the file and its attachment.
+ */
+ public function test_prepare_removes_the_stored_upload_when_the_helper_throws_after_storing_it(): void {
+ // CSVUploadHelper throws after storing when wc_is_file_valid_csv() rejects the stored
+ // file. is_uploaded_file() cannot pass in a test process, so this helper stores the file
+ // with wp_handle_sideload() (which fires the same hooks as wp_import_handle_upload()) and
+ // then throws the way the real helper does.
+ $helper = new class() extends CSVUploadHelper {
+ /**
+ * Absolute path of the file stored before the throw.
+ *
+ * @var string
+ */
+ public string $stored_file = '';
+
+ /**
+ * Attachment created for the stored file before the throw.
+ *
+ * @var int
+ */
+ public int $stored_id = 0;
+
+ /**
+ * Error wp_handle_sideload() returned, empty when the file was stored.
+ *
+ * @var string
+ */
+ public string $sideload_error = '';
+
+ // The stub always throws; the array return type is never reached.
+ // phpcs:disable Squiz.Commenting.FunctionComment.InvalidNoReturn
+ /**
+ * Store the upload under wc-imports with its attachment, then fail the CSV check.
+ *
+ * @param string $import_type Unused.
+ * @param string $files_index Unused.
+ * @param array|null $allowed_mime_types Unused.
+ * @return array
+ * @throws \Exception Always, after the file and attachment exist.
+ */
+ public function handle_csv_upload( string $import_type, string $files_index = 'import', ?array $allowed_mime_types = null ): array {
+ $tmp = wp_tempnam( 'fulfillment-sample.txt' );
+ file_put_contents( $tmp, "order_number,tracking_number,shipment_provider\n1,T-1,ups\n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixture write.
+
+ $file = array(
+ 'name' => 'fulfillment-sample.txt',
+ 'type' => 'text/plain',
+ 'tmp_name' => $tmp,
+ 'error' => UPLOAD_ERR_OK,
+ 'size' => (int) filesize( $tmp ),
+ );
+
+ $this->get_import_dir();
+ add_filter( 'upload_dir', array( $this, 'override_upload_dir' ) );
+ // The type check is off: finfo reports this content as text/plain or text/csv
+ // depending on the PHP version, and core refuses a .txt detected as text/csv.
+ $upload = wp_handle_sideload(
+ $file,
+ array(
+ 'test_form' => false,
+ 'test_type' => false,
+ )
+ );
+ remove_filter( 'upload_dir', array( $this, 'override_upload_dir' ) );
+
+ $this->sideload_error = (string) ( $upload['error'] ?? '' );
+ $this->stored_file = (string) ( $upload['file'] ?? '' );
+ $this->stored_id = (int) wp_insert_attachment(
+ array(
+ 'post_title' => 'fulfillment-sample.txt',
+ 'post_mime_type' => 'text/plain',
+ ),
+ $this->stored_file
+ );
+
+ throw new \Exception( 'Invalid file type for a CSV import.' );
+ }
+ // phpcs:enable Squiz.Commenting.FunctionComment.InvalidNoReturn
+ };
+ $sut = $this->controller_with_helper( $helper );
+
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params( 'sample.txt' ) );
+
+ $hooks_before = array( $this->callback_count( 'wp_handle_upload' ), $this->callback_count( 'add_attachment' ) );
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->temp_files[] = $helper->stored_file;
+ $this->assertSame( $hooks_before, array( $this->callback_count( 'wp_handle_upload' ), $this->callback_count( 'add_attachment' ) ), 'The recording hooks are removed' );
+ $this->assertSame( '', $helper->sideload_error, 'The helper stored the fixture' );
+ $this->assertTrue( ImportSession::is_staged_path( $helper->stored_file ), 'The helper stored the file under wc-imports' );
+ $this->assertGreaterThan( 0, $helper->stored_id, 'The helper created an attachment' );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_upload_failed', $response->get_error_code() );
+ $this->assertSame( 400, $response->get_error_data()['status'] );
+ $this->assertFileDoesNotExist( $helper->stored_file, 'The stored file is removed' );
+ $this->assertNull( get_post( $helper->stored_id ), 'The attachment is removed' );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ $this->assertArrayNotHasKey( 'fulfillment_import_file', $_FILES ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Asserting the superglobal was restored, not reading input.
+ }
+
+ /**
+ * @testdox An upload the helper rejects returns a fixed message instead of the helper's own.
+ */
+ public function test_prepare_hides_upload_helper_error_message(): void {
+ $helper = $this->getMockBuilder( CSVUploadHelper::class )
+ ->onlyMethods( array( 'handle_csv_upload' ) )
+ ->getMock();
+ $helper->method( 'handle_csv_upload' )->willThrowException( new \Exception( 'Unable to write to /var/www/html/wp-content/uploads/wc-imports' ) );
+ $sut = $this->controller_with_helper( $helper );
+
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params() );
+
+ $response = $this->invoke( 'handle_prepare', $request, $sut );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_upload_failed', $response->get_error_code() );
+ $this->assertSame( 'The file could not be uploaded.', $response->get_error_message() );
+ $this->assertSame( 400, $response->get_error_data()['status'] );
+ $this->assertStringNotContainsString( '/var/www', $response->get_error_message() );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ }
+
+ /**
+ * @testdox handle_prepare rejects an empty multipart request with a 400.
+ */
+ public function test_prepare_rejects_missing_file(): void {
+ $response = $this->invoke( 'handle_prepare', $this->make_prepare_request() );
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_no_file', $response->get_error_code() );
+ $this->assertSame( 400, $response->get_error_data()['status'] );
+ }
+
+ /**
+ * @testdox The permission check returns 403 for a user without manage_woocommerce.
+ */
+ public function test_permission_check_returns_403_for_subscriber(): void {
+ $subscriber = wp_insert_user(
+ array(
+ 'user_login' => 'fulfill_subscriber_' . wp_generate_password( 6, false ),
+ 'user_pass' => wp_generate_password( 12, false ),
+ 'role' => 'subscriber',
+ )
+ );
+ $this->assertIsInt( $subscriber );
+ wp_set_current_user( $subscriber );
+
+ $result = $this->invoke( 'check_permission_for_fulfillments_import', new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' ) );
+
+ $this->assertInstanceOf( \WP_Error::class, $result );
+ $this->assertSame( 403, $result->get_error_data()['status'] );
+ }
+
+ /**
+ * @testdox The permission check returns 401 for an unauthenticated request.
+ */
+ public function test_permission_check_returns_401_for_logged_out_user(): void {
+ wp_set_current_user( 0 );
+
+ $result = $this->invoke( 'check_permission_for_fulfillments_import', new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' ) );
+
+ $this->assertInstanceOf( \WP_Error::class, $result );
+ $this->assertSame( 401, $result->get_error_data()['status'] );
+ }
+
+ /**
+ * @testdox The prepare route rejects a request without a file when dispatched through the REST server.
+ */
+ public function test_rest_prepare_route_rejects_missing_file(): void {
+ $request = new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' );
+ $request->set_body_params( array( 'delimiter' => ',' ) );
+
+ $response = rest_do_request( $request );
+
+ $this->assertSame( 400, $response->get_status() );
+ $this->assertSame( 'woocommerce_fulfillments_import_no_file', $response->get_data()['code'] );
+ }
+
+ /**
+ * @testdox The delimiter argument is rejected with a 400 when it is not a single ASCII character or a tab spelling.
+ *
+ * @testWith ["ab"]
+ * [";;"]
+ * [["a"]]
+ * ["\""]
+ * ["\n"]
+ * ["\u00a7"]
+ *
+ * @param mixed $delimiter Delimiter value to send.
+ */
+ public function test_rest_prepare_route_rejects_invalid_delimiter( $delimiter ): void {
+ $request = new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' );
+ $request->set_body_params( array( 'delimiter' => $delimiter ) );
+
+ $response = rest_do_request( $request );
+
+ $this->assertSame( 400, $response->get_status() );
+ $this->assertSame( 'rest_invalid_param', $response->get_data()['code'] );
+ $this->assertArrayHasKey( 'delimiter', $response->get_data()['data']['params'] );
+ }
+
+ /**
+ * @testdox The delimiter argument accepts a tab spelling, a single ASCII character or an empty value and reaches the handler.
+ *
+ * @testWith ["\\t"]
+ * ["\t"]
+ * ["tab"]
+ * ["TAB"]
+ * [";"]
+ * [","]
+ * [""]
+ *
+ * @param string $delimiter Delimiter value to send.
+ */
+ public function test_rest_prepare_route_accepts_valid_delimiter( string $delimiter ): void {
+ $request = new WP_REST_Request( 'POST', '/wc/v3/fulfillments/import/prepare' );
+ $request->set_body_params( array( 'delimiter' => $delimiter ) );
+
+ $response = rest_do_request( $request );
+
+ $this->assertSame( 400, $response->get_status() );
+ $this->assertSame( 'woocommerce_fulfillments_import_no_file', $response->get_data()['code'], 'A valid delimiter must pass validation and fail only on the missing file' );
+ }
+
+ /**
+ * @testdox A zero upload limit, which multisite reports when the site is out of upload space, rejects the upload with a 413.
+ */
+ public function test_prepare_rejects_upload_when_no_upload_space_is_left(): void {
+ $no_space = static function () {
+ return 0;
+ };
+ add_filter( 'import_upload_size_limit', $no_space );
+
+ try {
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params( 'small.csv', UPLOAD_ERR_OK, 20 ) );
+
+ $response = $this->invoke( 'handle_prepare', $request );
+ } finally {
+ remove_filter( 'import_upload_size_limit', $no_space );
+ }
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_file_too_large', $response->get_error_code() );
+ $this->assertSame( 413, $response->get_error_data()['status'] );
+ $this->assertStringContainsString( 'no upload space', $response->get_error_message() );
+ }
+
+ /**
+ * @testdox A site with no upload space left gets the no-space 413 even for a file PHP refused for its size.
+ */
+ public function test_prepare_reports_no_upload_space_before_a_php_size_error(): void {
+ $no_space = static function () {
+ return 0;
+ };
+ add_filter( 'import_upload_size_limit', $no_space );
+
+ try {
+ $request = $this->make_prepare_request();
+ $request->set_file_params( $this->file_params( 'large.csv', UPLOAD_ERR_INI_SIZE, 0 ) );
+
+ $response = $this->invoke( 'handle_prepare', $request );
+ } finally {
+ remove_filter( 'import_upload_size_limit', $no_space );
+ }
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_file_too_large', $response->get_error_code() );
+ $this->assertSame( 413, $response->get_error_data()['status'] );
+ $this->assertSame( 'This site has no upload space left for the file.', $response->get_error_message() );
+ }
+
+ /**
+ * @testdox handle_prepare rejects uploads above the filtered size limit.
+ */
+ public function test_prepare_rejects_file_above_size_limit(): void {
+ $limit_filter = static function () {
+ return 10;
+ };
+ add_filter( 'import_upload_size_limit', $limit_filter );
+
+ try {
+ $request = $this->make_prepare_request();
+ $request->set_file_params(
+ array(
+ 'file' => array(
+ 'name' => 'big.csv',
+ 'type' => 'text/csv',
+ 'tmp_name' => '/tmp/does-not-matter.csv',
+ 'error' => 0,
+ 'size' => 1000,
+ ),
+ )
+ );
+
+ $response = $this->invoke( 'handle_prepare', $request );
+ } finally {
+ remove_filter( 'import_upload_size_limit', $limit_filter );
+ }
+
+ $this->assertInstanceOf( \WP_Error::class, $response );
+ $this->assertSame( 'woocommerce_fulfillments_import_file_too_large', $response->get_error_code() );
+ $this->assertSame( 413, $response->get_error_data()['status'] );
+ $this->assertNull( ImportSession::active_for_user( get_current_user_id() ) );
+ $this->assertArrayNotHasKey( 'fulfillment_import_file', $_FILES ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Asserting the superglobal was never written, not reading input.
+ }
+}