Commit e27172dc099 for woocommerce
commit e27172dc099cd4f81f0aff0aeac6b7fd244f6b89
Author: Taha Paksu <3295+tpaksu@users.noreply.github.com>
Date: Mon Nov 16 21:42:31 2026 +0300
Lock shipping zone actions while a save, add or delete is in progress (#70447)
* [WOOPLUG-8128] Surface shipping zone save failures and keep edits made mid-save
* Add changefile(s) from automation for the following project(s): woocommerce
* [WOOPLUG-8128] Drop pending method rows on save and stop faking unsaved zone changes
* [WOOPLUG-8128] Guard the save response before reading its success flag
* [WOOPLUG-8128] Keep shipping method rows blocked through an in-flight save
* [WOOPLUG-8130] Lock shipping zone actions while a save, add or delete is running
* Add changefile(s) from automation for the following project(s): woocommerce
* [WOOPLUG-8130] Assert the block overlay, not the empty base layer, in the in-flight e2e test
* [WOOPLUG-8130] Guard the remaining actions and keep pending zone edits on delete
* Add changefile(s) from automation for the following project(s): woocommerce
* [WOOPLUG-8130] Lock the method selector and fix both method removal paths
* Add changefile(s) from automation for the following project(s): woocommerce
* Add changefile(s) from automation for the following project(s): woocommerce
* [WOOPLUG-8130] Merge pending edits on add and count overlapping operations
* [WOOPLUG-8130] Guard the Save button while an operation is running
* [WOOPLUG-8130] Decide Save by the pending change set after a failed method removal
---------
Co-authored-by: woocommercebot <woocommercebot@users.noreply.github.com>
diff --git a/plugins/woocommerce/changelog/70447-wooplug-8130-shipping-zones-a-method-row-edited-while-a-zone-save-is-in b/plugins/woocommerce/changelog/70447-wooplug-8130-shipping-zones-a-method-row-edited-while-a-zone-save-is-in
new file mode 100644
index 00000000000..689aad7525e
--- /dev/null
+++ b/plugins/woocommerce/changelog/70447-wooplug-8130-shipping-zones-a-method-row-edited-while-a-zone-save-is-in
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Stop losing unsaved shipping method changes made while another action is still running, and report method removals that fail.
diff --git a/plugins/woocommerce/client/legacy/js/admin/backbone-modal.js b/plugins/woocommerce/client/legacy/js/admin/backbone-modal.js
index 6c3e5496965..5916e1d2c01 100644
--- a/plugins/woocommerce/client/legacy/js/admin/backbone-modal.js
+++ b/plugins/woocommerce/client/legacy/js/admin/backbone-modal.js
@@ -175,7 +175,7 @@
if ( ! $okButton.prop( 'disabled' ) ) {
this.addButton( e );
}
- } else if ( $( '#btn-next' ).length ) {
+ } else if ( this.$( '#btn-next' ).length && ! this.$( '#btn-next' ).prop( 'disabled' ) ) {
this.nextButton( e );
}
}
diff --git a/plugins/woocommerce/client/legacy/js/admin/wc-shipping-zone-methods.js b/plugins/woocommerce/client/legacy/js/admin/wc-shipping-zone-methods.js
index 1675bcace9a..0a98eafc855 100644
--- a/plugins/woocommerce/client/legacy/js/admin/wc-shipping-zone-methods.js
+++ b/plugins/woocommerce/client/legacy/js/admin/wc-shipping-zone-methods.js
@@ -1,11 +1,12 @@
/* global shippingZoneMethodsLocalizeScript, ajaxurl, WCNumberValidation, WCMaybeModifyDecimal */
( function( $, data, wp, ajaxurl ) {
$( function() {
- var $table = $( '.wc-shipping-zone-methods' ),
- $tbody = $( '.wc-shipping-zone-method-rows' ),
- $save_button = $( '.wc-shipping-zone-method-save' ),
- $row_template = wp.template( 'wc-shipping-zone-method-row' ),
- $blank_template = wp.template( 'wc-shipping-zone-method-row-blank' ),
+ var $table = $( '.wc-shipping-zone-methods' ),
+ $tbody = $( '.wc-shipping-zone-method-rows' ),
+ $save_button = $( '.wc-shipping-zone-method-save' ),
+ $add_method_button = $( '.wc-shipping-zone-add-method' ),
+ $row_template = wp.template( 'wc-shipping-zone-method-row' ),
+ $blank_template = wp.template( 'wc-shipping-zone-method-row-blank' ),
// Backbone model
ShippingMethod = Backbone.Model.extend({
@@ -40,10 +41,9 @@
snapshot = _.clone( this.changes ),
changes = _.clone( this.changes );
- // Mark a save in flight: disable the button so a second save cannot start, and
- // let render() keep the rows blocked through a mid-request zone edit.
- this.isSaving = true;
- $save_button.prop( 'disabled', true );
+ // Mark an operation in flight: lock the action controls (Save, Add method, and
+ // the method rows via render()) so no other action can start mid-request.
+ setRunning( this, true );
// Special handling for an empty 'zone_locations' array, which jQuery filters out during $.post().
if ( _.has( changes, 'zone_locations' ) && _.isEmpty( changes.zone_locations ) ) {
@@ -66,7 +66,7 @@
} );
},
onSaveFailure: function() {
- shippingMethod.isSaving = false;
+ setRunning( shippingMethod, false );
window.alert( data.strings.save_failed );
@@ -90,8 +90,6 @@
}
},
onSaveResponse: function( response, textStatus, snapshot ) {
- shippingMethod.isSaving = false;
-
if (
'success' !== textStatus ||
! response ||
@@ -102,6 +100,8 @@
return;
}
+ setRunning( shippingMethod, false );
+
if ( response.data.zone_id !== data.zone_id ) {
data.zone_id = response.data.zone_id;
if ( window.history.pushState ) {
@@ -152,6 +152,7 @@
);
$( document.body ).on( 'click', '.wc-shipping-zone-method-settings', { view: this }, this.onConfigureShippingMethod );
$( document.body ).on( 'click', '.wc-shipping-zone-add-method', { view: this }, this.onAddShippingMethod );
+ $( document.body ).on( 'wc_backbone_modal_before_response', this.onModalBeforeResponse );
$( document.body ).on( 'wc_backbone_modal_response', this.onConfigureShippingMethodSubmitted );
$( document.body ).on( 'wc_region_picker_update', this.onUpdateZoneRegionPicker );
$( document.body ).on( 'wc_backbone_modal_next_response', this.onAddShippingMethodSubmitted );
@@ -195,6 +196,11 @@
});
},
unblock: function() {
+ // Another operation is still running, so keep the rows blocked until it ends.
+ if ( this.model.isRunning ) {
+ return;
+ }
+
$( this.el ).unblock();
},
render: function() {
@@ -207,7 +213,7 @@
// Blank out the contents.
this.$el.empty();
- this.unblock();
+ this.$el.unblock();
if ( _.size( methods ) ) {
// Sort methods
@@ -249,8 +255,8 @@
this.initTooltips();
- // render() unblocks the rows; re-apply the block if a save is still in flight.
- if ( this.model.isSaving ) {
+ // render() unblocks the rows; re-apply the block if an operation is still running.
+ if ( this.model.isRunning ) {
this.block();
}
},
@@ -260,22 +266,45 @@
$( '.tips' ).tipTip({ 'attribute': 'data-tip', 'fadeIn': 50, 'fadeOut': 50, 'delay': 50 });
},
onSubmit: function( event ) {
+ event.preventDefault();
+
+ // Save is disabled while an operation runs, but a click queued just before that
+ // can still arrive.
+ if ( event.data.view.model.isRunning ) {
+ return;
+ }
+
$save_button.addClass( 'is-busy' );
event.data.view.block();
event.data.view.model.save();
- event.preventDefault();
},
onDeleteRow: function( event ) {
var view = event.data.view,
model = view.model,
- methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
- changes = {},
instance_id = $( this ).closest( 'tr' ).data( 'id' );
event.preventDefault();
+ // The row overlay only blocks the mouse, so refuse the action while another
+ // one is running.
+ if ( model.isRunning ) {
+ return;
+ }
+
if ( window.confirm( data.strings.delete_shipping_method_confirmation ) ) {
shippingMethodView.block();
+ setRunning( model, true );
+
+ var onRemoveFailure = function() {
+ setRunning( model, false );
+ window.alert( data.strings.remove_method_failed );
+ shippingMethodView.unblock();
+ // Adding a method raises the unload warning on a clean form, so the change
+ // set, not needsUnloadConfirm, says whether Save has anything to post.
+ if ( ! _.isEmpty( model.changes ) && ! model.isRunning ) {
+ $save_button.prop( 'disabled', false );
+ }
+ };
// Add method to zone via ajax call
$.post( {
@@ -285,19 +314,19 @@
instance_id: instance_id,
zone_id: data.zone_id,
},
- success: function( { data } ) {
- delete methods[instance_id];
- changes.methods = changes.methods || data.methods;
- model.set('methods', methods);
- model.logChanges( changes );
- view.clearUnloadConfirmation();
- view.render();
- shippingMethodView.unblock();
- },
- error: function( jqXHR, textStatus, errorThrown ) {
- window.alert( data.strings.remove_method_failed );
+ success: function( response, textStatus ) {
+ // A refused delete still arrives as HTTP 200, so check the payload
+ // before dropping the row.
+ if ( 'success' !== textStatus || ! response || ! response.success || ! response.data ) {
+ onRemoveFailure();
+ return;
+ }
+
+ setRunning( model, false );
+ applyMethodRemoval( model, view, response, instance_id );
shippingMethodView.unblock();
},
+ error: onRemoveFailure,
dataType: 'json'
});
}
@@ -312,6 +341,13 @@
changes = {};
event.preventDefault();
+
+ // The row overlay only blocks the mouse, so refuse the action while another
+ // one is running.
+ if ( model.isRunning ) {
+ return;
+ }
+
methods[ instance_id ].enabled = enabled;
changes.methods = changes.methods || { methods : {} };
changes.methods[ instance_id ] = _.extend( changes.methods[ instance_id ] || {}, { enabled : enabled } );
@@ -322,9 +358,9 @@
setUnloadConfirmation: function() {
this.needsUnloadConfirm = true;
- // A mid-request edit must not re-enable the button, or it could start a second,
- // concurrent save while this one is still in flight.
- if ( this.model.isSaving ) {
+ // A mid-request edit must not re-enable the button, or it could start another
+ // action while an operation is still running.
+ if ( this.model.isRunning ) {
return;
}
@@ -395,6 +431,12 @@
event.preventDefault();
+ // The row overlay only blocks the mouse, so refuse the action while another
+ // one is running.
+ if ( model.isRunning ) {
+ return;
+ }
+
method.settings_html = shippingMethodView.reformatSettingsHTML( method.settings_html );
$( this ).WCBackboneModal({
@@ -449,9 +491,17 @@
return data;
},
+ onModalBeforeResponse: function( event, target ) {
+ // The modal closes itself once the response fires, so refuse the submit here to
+ // keep the entered settings while another operation is running.
+ if ( 'wc-modal-shipping-method-settings' === target && shippingMethod.isRunning ) {
+ event.preventDefault();
+ }
+ },
onConfigureShippingMethodSubmitted: function( event, target, posted_data ) {
if ( 'wc-modal-shipping-method-settings' === target ) {
shippingMethodView.block();
+ setRunning( shippingMethod, true );
// Save method settings via ajax call
$.post(
@@ -466,12 +516,14 @@
$( 'table.wc-shipping-zone-methods' ).parent().find( '#woocommerce_errors' ).remove();
// If there were errors, prepend the form.
- if ( response.data.errors.length > 0 ) {
+ if ( ( response.data.errors || [] ).length > 0 ) {
shippingMethodView.showErrors( response.data.errors );
}
// Method was saved. Re-render.
if ( _.size( shippingMethodView.model.changes ) ) {
+ // save() takes its own lock, so hand this one back first.
+ setRunning( shippingMethod, false );
shippingMethodView.model.save();
} else {
shippingMethodView.model.onSaveResponse( response, textStatus );
@@ -667,6 +719,7 @@
onAddShippingMethodSubmitted: function( event, target, posted_data, closeModal ) {
if ( 'wc-modal-add-shipping-method' === target ) {
shippingMethodView.block();
+ setRunning( shippingMethod, true );
$('#btn-next').addClass( 'is-busy' );
@@ -703,15 +756,7 @@
// Avoid triggering a rerender here because we don't want to show the method
// in the table in case merchant doesn't finish flow.
- // The server list replaces the rows, so lay the unsaved toggles and order back over it;
- // they stay pending and are saved with the next save.
- _.each( _.omit( shippingMethodView.model.changes.methods, 'methods' ), function( row, id ) {
- if ( response.data.methods[ id ] ) {
- _.extend( response.data.methods[ id ], _.pick( row, 'enabled', 'method_order' ) );
- }
- } );
-
- shippingMethodView.model.set( 'methods', response.data.methods );
+ shippingMethodView.model.set( 'methods', withPendingEdits( shippingMethodView.model, response.data.methods ) );
// Setting 'methods' above marks the form dirty, which on the modal branch below
// still has to warn about navigating away from unfinished settings, so only
@@ -727,6 +772,9 @@
var instance_id = response.data.instance_id,
method = response.data.methods[ instance_id ];
+ // The add request is done; any follow-up settings modal re-locks on its
+ // own submit, so release here to avoid a stuck lock if it is cancelled.
+ setRunning( shippingMethod, false );
shippingMethodView.unblock();
if ( method.settings_html ) {
@@ -756,6 +804,8 @@
shippingMethodView.block();
shippingMethodView.model.save();
} else {
+ // onSaveResponse releases a lock, so take one back for it.
+ setRunning( shippingMethod, true );
shippingMethodView.model.onSaveResponse( response, textStatus );
}
}
@@ -846,7 +896,7 @@
},
validateFormArguments: function( event, target, data ) {
if ( target === 'wc-modal-add-shipping-method' ) {
- if ( data.add_method_id ) {
+ if ( data.add_method_id && ! shippingMethod.isRunning ) {
const nextButton = document.getElementById( 'btn-next' );
nextButton.disabled = false;
nextButton.classList.remove( 'disabled' );
@@ -861,12 +911,30 @@
if ( ! addButtonCalled && btnData && btnData.status === 'new' ) {
shippingMethodView.block();
+ setRunning( shippingMethod, true );
var view = shippingMethodView,
model = view.model,
- methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
instance_id = post_data.instance_id;
+ var onCleanupFailure = function() {
+ setRunning( shippingMethod, false );
+ window.alert( data.strings.remove_method_failed );
+ shippingMethodView.unblock();
+ // The method is still in the model and on the server, and the add deliberately
+ // skipped rendering it, so draw it now or the merchant cannot reach it. The
+ // delete handler's failure path must not render, as it never touched the model.
+ shippingMethodView.render();
+ // The method stays on the server, so nothing is left to warn about, and
+ // clearing the warning switches Save off too. Otherwise Save comes back,
+ // the same rule applyMethodRemoval() applies on success.
+ if ( _.isEmpty( shippingMethod.changes ) ) {
+ shippingMethodView.clearUnloadConfirmation();
+ } else if ( ! shippingMethod.isRunning ) {
+ $save_button.prop( 'disabled', false );
+ }
+ };
+
// Remove method to zone via ajax call
$.post( {
url: ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?') + 'action=woocommerce_shipping_zone_remove_method',
@@ -875,29 +943,19 @@
instance_id: instance_id,
zone_id: data.zone_id,
},
- success: function() {
- delete methods[instance_id];
- model.set('methods', methods);
-
- // Keep the merchant's pending edits: writing the server's rows over them
- // would revert a toggle the table still shows.
- if ( model.changes.methods ) {
- delete model.changes.methods[ instance_id ];
- if ( _.isEmpty( _.omit( model.changes.methods, 'methods' ) ) ) {
- delete model.changes.methods;
- }
+ success: function( response, textStatus ) {
+ // A refused removal still arrives as HTTP 200, so check the payload
+ // before treating the method as gone.
+ if ( 'success' !== textStatus || ! response || ! response.success || ! response.data ) {
+ onCleanupFailure();
+ return;
}
- if ( _.isEmpty( model.changes ) ) {
- view.clearUnloadConfirmation();
- }
- view.render();
- shippingMethodView.unblock();
- },
- error: function( jqXHR, textStatus, errorThrown ) {
- window.alert( data.strings.remove_method_failed );
+ setRunning( shippingMethod, false );
+ applyMethodRemoval( model, view, response, instance_id );
shippingMethodView.unblock();
},
+ error: onCleanupFailure,
dataType: 'json'
});
}
@@ -919,6 +977,70 @@
el: $tbody
} );
+ // Index the server's methods and lay the merchant's unsaved edits over them. The server is
+ // the truth for which methods exist, except those already removed: a response that arrives
+ // late carries an older list that still has them. The edits stay the truth for how they look.
+ function withPendingEdits( model, methods ) {
+ var pending = _.omit( model.changes.methods || {}, 'methods' ),
+ fresh = _.omit( _.indexBy( methods, 'instance_id' ), _.keys( model.removedIds || {} ) );
+
+ // Only these two are editable without a save, so only these may override the server.
+ _.each( pending, function( row, id ) {
+ if ( fresh[ id ] ) {
+ _.extend( fresh[ id ], _.pick( row, 'enabled', 'method_order' ) );
+ }
+ } );
+
+ return fresh;
+ }
+
+ // Apply a completed removal.
+ function applyMethodRemoval( model, view, response, instance_id ) {
+ model.removedIds = model.removedIds || {};
+ model.removedIds[ instance_id ] = true;
+
+ // The removed row's pending edits are moot. 'methods' is a key logChanges seeds,
+ // not a row, so it never counts as a pending edit.
+ if ( model.changes.methods ) {
+ delete model.changes.methods[ instance_id ];
+ if ( _.isEmpty( _.omit( model.changes.methods, 'methods' ) ) ) {
+ delete model.changes.methods;
+ }
+ }
+
+ model.set( 'methods', withPendingEdits( model, response.data.methods ) );
+
+ // Save stays off while another operation runs; whichever finishes last restores it.
+ if ( _.isEmpty( model.changes ) ) {
+ view.clearUnloadConfirmation();
+ } else if ( ! model.isRunning ) {
+ $save_button.prop( 'disabled', false );
+ }
+ view.render();
+ }
+
+ // Lock or release the controls that start an operation. While one runs, the method rows
+ // stay blocked (via render()) and Save, Add method, the add modal's method selector and
+ // its Continue button are disabled, so no second action can begin. Save re-enables through
+ // the unsaved-changes flow, Continue through the modal's own validation.
+ // Operations can overlap, so this counts them: the controls unlock only when the last one ends.
+ // Every setRunning( model, true ) needs exactly one matching false.
+ function setRunning( model, running ) {
+ model.runningCount = Math.max( 0, ( model.runningCount || 0 ) + ( running ? 1 : -1 ) );
+ model.isRunning = model.runningCount > 0;
+ $add_method_button.prop( 'disabled', model.isRunning );
+ // Disabled controls fire no input events, so validation cannot re-enable Continue mid-run.
+ $( '.wc-shipping-zone-method-selector' ).prop( 'disabled', model.isRunning );
+ if ( model.isRunning ) {
+ $save_button.prop( 'disabled', true );
+ $( '#btn-next' ).prop( 'disabled', true ).addClass( 'disabled' );
+ } else {
+ // Re-validate so Continue matches the selection the merchant already made.
+ // Continue sits in the footer, outside the form, so walk up to the dialog first.
+ $( '#btn-next' ).closest( '#wc-backbone-modal-dialog' ).find( 'form' ).trigger( 'input' );
+ }
+ }
+
shippingMethodView.render();
$tbody.sortable({
diff --git a/plugins/woocommerce/tests/e2e/tests/shipping/shipping-zones.spec.ts b/plugins/woocommerce/tests/e2e/tests/shipping/shipping-zones.spec.ts
index 1042d9916f4..6c84e7b7b41 100644
--- a/plugins/woocommerce/tests/e2e/tests/shipping/shipping-zones.spec.ts
+++ b/plugins/woocommerce/tests/e2e/tests/shipping/shipping-zones.spec.ts
@@ -18,11 +18,26 @@ function rand() {
const SAVE_CHANGES_ACTION = 'woocommerce_shipping_zone_methods_save_changes';
const SAVE_SETTINGS_ACTION = 'woocommerce_shipping_zone_methods_save_settings';
const ADD_METHOD_ACTION = 'woocommerce_shipping_zone_add_method';
+const REMOVE_METHOD_ACTION = 'woocommerce_shipping_zone_remove_method';
+const REMOVE_FAILED_MESSAGE =
+ 'Shipping method could not be removed. Please retry.';
function isSaveChanges( url: URL ) {
return url.searchParams.get( 'action' ) === SAVE_CHANGES_ACTION;
}
+function isRemoveMethod( url: URL ) {
+ return url.searchParams.get( 'action' ) === REMOVE_METHOD_ACTION;
+}
+
+function methodRow( page: Page, title: string ) {
+ return page.locator( '.wc-shipping-zone-method-rows tr[data-id]', {
+ has: page.locator( '.wc-shipping-zone-method-title', {
+ hasText: title,
+ } ),
+ } );
+}
+
async function openAddMethodModal( page: Page ) {
// The edit screen binds the add-method modal after its methods table renders, so retry
// opening it in case the first click lands before the handler is bound.
@@ -433,9 +448,8 @@ test( 'surfaces a failed zone save and releases the methods table', async ( {
.poll( () => dialogMessages )
.toContain( 'Your changes were not saved. Please retry.' );
- // Releasing the table and clearing the busy state are what regress; the enabled button
- // is recorded as the expected end state rather than as coverage, since Save changes is
- // never disabled on this path either way.
+ // Releasing the table and clearing the busy state are what regress; Save is re-enabled
+ // here because the change set is still pending.
await expect( page.locator( '.blockUI' ) ).toHaveCount( 0 );
await expect( page.locator( '#submit' ) ).toBeEnabled();
await expect( page.locator( '#submit' ) ).not.toHaveClass( /is-busy/ );
@@ -775,8 +789,30 @@ test( 'keeps a zone edit made while an earlier save is in flight', async ( {
await page.getByLabel( 'Zone name' ).fill( firstName );
await page.locator( '#submit' ).click();
+ // While the save is in flight every action control is locked, so no second operation can
+ // start: Save and Add method are disabled and the method rows stay blocked.
+ await expect( page.locator( '#submit' ) ).toBeDisabled();
+ await expect(
+ page.locator( '.wc-shipping-zone-add-method' )
+ ).toBeDisabled();
+ await expect( page.locator( '.blockOverlay' ).first() ).toBeVisible();
+
+ // Keyboard activation reaches the row links through the overlay, so prove the guard
+ // refuses the action rather than trusting the overlay.
+ const firstRow = page
+ .locator( '.wc-shipping-zone-method-rows tr[data-id]' )
+ .first();
+ await expect( firstRow ).toHaveAttribute( 'data-enabled', 'yes' );
+ await firstRow.locator( '.wc-shipping-zone-method-enabled a' ).focus();
+ await page.keyboard.press( 'Enter' );
+ await expect( firstRow ).toHaveAttribute( 'data-enabled', 'yes' );
+
// The zone fields stay editable while the table is blocked, so type again mid-request.
await page.getByLabel( 'Zone name' ).fill( secondName );
+
+ // That edit re-renders the rows, so the block has to be reapplied.
+ await expect( page.locator( '.blockOverlay' ).first() ).toBeVisible();
+
releaseFirstSave();
await page.waitForFunction(
() =>
@@ -794,6 +830,7 @@ test( 'keeps a zone edit made while an earlier save is in flight', async ( {
await page.locator( '#submit' ).click();
await secondSave;
await expect( page.locator( '#submit' ) ).toBeDisabled();
+ await expect( page.locator( '.blockUI' ) ).toHaveCount( 0 );
const saved = await restApi.get(
`${ WC_API_PATH }/shipping/zones/${ zone.id }`
@@ -958,3 +995,294 @@ test( 'does not claim unsaved zone changes after a row delete and a failed setti
)
).toHaveLength( 1 );
} );
+
+// Regression: a refused delete answers with HTTP 200 and success: false, so the row has to stay
+// and the merchant has to be told, not shown a method that vanished while it still exists.
+test( 'keeps the method and reports it when a delete is refused', async ( {
+ page,
+ zone,
+} ) => {
+ await openZone( page, zone.name );
+
+ const dialogMessages: string[] = [];
+ page.on( 'dialog', async ( dialog ) => {
+ dialogMessages.push( dialog.message() );
+ await dialog.accept();
+ } );
+
+ await page.route( isRemoveMethod, ( route ) =>
+ route.fulfill( {
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify( { success: false, data: 'bad_nonce' } ),
+ } )
+ );
+
+ await methodRow( page, 'Flat rate' )
+ .locator( '.wc-shipping-zone-method-delete' )
+ .click();
+
+ await expect
+ .poll( () => dialogMessages )
+ .toContain( REMOVE_FAILED_MESSAGE );
+
+ await expect( methodRow( page, 'Flat rate' ) ).toHaveCount( 1 );
+ await expect( page.locator( '.blockUI' ) ).toHaveCount( 0 );
+ // Nothing about the zone changed, so the screen must not look dirty.
+ await expect( page.locator( '#submit' ) ).toBeDisabled();
+ await expect(
+ page.locator( '.wc-shipping-zone-add-method' )
+ ).toBeEnabled();
+} );
+
+// Regression: the delete answer carries the server's copy of the methods, where every method is
+// still on, so the merchant's unsaved switch has to be laid back over it.
+test( 'keeps a switched-off method off after another method is deleted', async ( {
+ page,
+ restApi,
+ zone,
+} ) => {
+ await restApi.post(
+ `${ WC_API_PATH }/shipping/zones/${ zone.id }/methods`,
+ {
+ method_id: 'free_shipping',
+ }
+ );
+ await openZone( page, zone.name );
+ page.on( 'dialog', ( dialog ) => dialog.accept() );
+
+ const flatRate = methodRow( page, 'Flat rate' );
+ await flatRate.locator( '.wc-shipping-zone-method-enabled a' ).click();
+ await expect( flatRate ).toHaveAttribute( 'data-enabled', 'no' );
+
+ await methodRow( page, 'Free shipping' )
+ .locator( '.wc-shipping-zone-method-delete' )
+ .click();
+ await expect( methodRow( page, 'Free shipping' ) ).toHaveCount( 0 );
+
+ await expect( flatRate ).toHaveAttribute( 'data-enabled', 'no' );
+ await expect( page.locator( '#submit' ) ).toBeEnabled();
+
+ const saved = page.waitForResponse( ( response ) =>
+ isSaveChanges( new URL( response.url() ) )
+ );
+ await page.locator( '#submit' ).click();
+ await saved;
+ await expect( page.locator( '#submit' ) ).toBeDisabled();
+
+ const methods = await restApi.get(
+ `${ WC_API_PATH }/shipping/zones/${ zone.id }/methods`
+ );
+ const stored = methods.data.find(
+ ( method: { method_id: string } ) => method.method_id === 'flat_rate'
+ );
+ expect( stored.enabled ).toBe( false );
+} );
+
+// Regression: adding a method replaced the method list with the server's copy, so a switch the
+// merchant had already turned off looked on again after the settings step was abandoned and its
+// cleanup failed, while Save still stored it as off.
+test( 'keeps a switched-off method off when removing an abandoned new method fails', async ( {
+ page,
+ restApi,
+ zone,
+} ) => {
+ await openZone( page, zone.name );
+
+ const dialogMessages: string[] = [];
+ page.on( 'dialog', async ( dialog ) => {
+ dialogMessages.push( dialog.message() );
+ await dialog.accept();
+ } );
+
+ const original = methodRow( page, 'Flat rate' );
+ const originalId = await original.getAttribute( 'data-id' );
+ await original.locator( '.wc-shipping-zone-method-enabled a' ).click();
+ await expect( original ).toHaveAttribute( 'data-enabled', 'no' );
+
+ await page.route( isRemoveMethod, ( route ) =>
+ route.fulfill( {
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify( { success: false, data: 'bad_nonce' } ),
+ } )
+ );
+
+ await openAddMethodModal( page );
+ await page
+ .locator( '.wc-backbone-modal' )
+ .getByText( 'Flat rate', { exact: true } )
+ .click();
+ await page.getByRole( 'button', { name: 'Continue' } ).click();
+ await expect( page.locator( '#btn-ok' ) ).toBeVisible();
+ await page.locator( '.modal-close-link' ).click();
+
+ await expect
+ .poll( () => dialogMessages )
+ .toContain( REMOVE_FAILED_MESSAGE );
+
+ const originalRow = page.locator(
+ `.wc-shipping-zone-method-rows tr[data-id="${ originalId }"]`
+ );
+ await expect( originalRow ).toHaveAttribute( 'data-enabled', 'no' );
+ await expect( page.locator( '#submit' ) ).toBeEnabled();
+
+ const saved = page.waitForResponse( ( response ) =>
+ isSaveChanges( new URL( response.url() ) )
+ );
+ await page.locator( '#submit' ).click();
+ await saved;
+
+ const methods = await restApi.get(
+ `${ WC_API_PATH }/shipping/zones/${ zone.id }/methods`
+ );
+ const stored = methods.data.find(
+ ( method: { id: number } ) => method.id === Number( originalId )
+ );
+ expect( stored.enabled ).toBe( false );
+} );
+
+// Regression: adding a method raises the unload warning even on a clean form, because the
+// unfinished settings step still has to be warned about. A failed cleanup must not read that
+// warning as pending changes and turn Save back on with nothing to post.
+test( 'leaves Save changes disabled when removing an abandoned new method fails', async ( {
+ page,
+ zone,
+} ) => {
+ await openZone( page, zone.name );
+
+ const dialogMessages: string[] = [];
+ page.on( 'dialog', async ( dialog ) => {
+ dialogMessages.push( dialog.message() );
+ await dialog.accept();
+ } );
+
+ await page.route( isRemoveMethod, ( route ) =>
+ route.fulfill( {
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify( { success: false, data: 'bad_nonce' } ),
+ } )
+ );
+
+ await openAddMethodModal( page );
+ await page
+ .locator( '.wc-backbone-modal' )
+ .getByText( 'Flat rate', { exact: true } )
+ .click();
+ await page.getByRole( 'button', { name: 'Continue' } ).click();
+ await expect( page.locator( '#btn-ok' ) ).toBeVisible();
+ await page.locator( '.modal-close-link' ).click();
+
+ await expect
+ .poll( () => dialogMessages )
+ .toContain( REMOVE_FAILED_MESSAGE );
+
+ // The failed cleanup draws the method it could not remove, so the merchant can reach it.
+ // It decides Save in the same block, so two rows also means Save has settled.
+ await expect( methodRow( page, 'Flat rate' ) ).toHaveCount( 2 );
+ await expect( page.locator( '#submit' ) ).toBeDisabled();
+} );
+
+// Regression: the lock is released before the settings step opens, so a row behind it can be
+// deleted and the step then closed, leaving two removals in flight. The first to finish must
+// not unlock the table or turn Save back on while the second is still running.
+test( 'keeps the table locked and Save off until overlapping removals have both finished', async ( {
+ page,
+ restApi,
+ zone,
+} ) => {
+ await restApi.post(
+ `${ WC_API_PATH }/shipping/zones/${ zone.id }/methods`,
+ {
+ method_id: 'free_shipping',
+ }
+ );
+ await openZone( page, zone.name );
+ page.on( 'dialog', ( dialog ) => dialog.accept() );
+
+ // Switch a method off so the form is dirty: Save is then what the removals must leave alone.
+ const flatRate = methodRow( page, 'Flat rate' );
+ await flatRate.locator( '.wc-shipping-zone-method-enabled a' ).click();
+ await expect( flatRate ).toHaveAttribute( 'data-enabled', 'no' );
+ await expect( page.locator( '#submit' ) ).toBeEnabled();
+
+ // Hold each response, not the request: the server handles the removals in order while the
+ // browser receives them the other way round, so the older method list lands last.
+ const releases: Array< () => void > = [];
+ await page.route( isRemoveMethod, async ( route ) => {
+ const response = await route.fetch();
+ await new Promise< void >( ( resolve ) => releases.push( resolve ) );
+ await route.fulfill( { response } );
+ } );
+
+ // jQuery fires ajaxComplete after the request's success callback, so the counter proves a
+ // removal response was handled.
+ await page.evaluate( ( action: string ) => {
+ const context = window as unknown as {
+ wcRemovalsHandled?: number;
+ jQuery: ( target: Document ) => {
+ on: (
+ event: string,
+ handler: ( ...args: unknown[] ) => void
+ ) => void;
+ };
+ };
+
+ context.wcRemovalsHandled = 0;
+ context.jQuery( document ).on( 'ajaxComplete', ( ...args ) => {
+ const settings = args[ 2 ] as { url?: string } | undefined;
+ if ( settings && settings.url && settings.url.includes( action ) ) {
+ context.wcRemovalsHandled =
+ ( context.wcRemovalsHandled || 0 ) + 1;
+ }
+ } );
+ }, REMOVE_METHOD_ACTION );
+
+ const removalsHandled = ( count: number ) =>
+ page.waitForFunction(
+ ( expected: number ) =>
+ ( window as unknown as { wcRemovalsHandled?: number } )
+ .wcRemovalsHandled === expected,
+ count
+ );
+
+ await openAddMethodModal( page );
+ await page
+ .locator( '.wc-backbone-modal' )
+ .getByText( 'Flat rate', { exact: true } )
+ .click();
+ await page.getByRole( 'button', { name: 'Continue' } ).click();
+ await expect( page.locator( '#btn-ok' ) ).toBeVisible();
+
+ // The modal does not trap focus, so the row behind it can still be deleted.
+ await methodRow( page, 'Free shipping' )
+ .locator( '.wc-shipping-zone-method-delete' )
+ .dispatchEvent( 'click' );
+ await expect.poll( () => releases.length ).toBe( 1 );
+
+ await page.locator( '.modal-close-link' ).click();
+ await expect.poll( () => releases.length ).toBe( 2 );
+
+ releases[ 1 ]();
+ await removalsHandled( 1 );
+ await expect(
+ page.locator( '.wc-shipping-zone-add-method' )
+ ).toBeDisabled();
+ await expect( page.locator( '.blockOverlay' ).first() ).toBeVisible();
+ await expect( page.locator( '#submit' ) ).toBeDisabled();
+
+ releases[ 0 ]();
+ await removalsHandled( 2 );
+ await expect(
+ page.locator( '.wc-shipping-zone-add-method' )
+ ).toBeEnabled();
+ await expect( page.locator( '.blockUI' ) ).toHaveCount( 0 );
+ // The switch is still pending, so the last removal to finish hands Save back.
+ await expect( page.locator( '#submit' ) ).toBeEnabled();
+
+ // Both removals succeeded, so only the original method is left, still switched off.
+ await expect( methodRow( page, 'Free shipping' ) ).toHaveCount( 0 );
+ await expect( methodRow( page, 'Flat rate' ) ).toHaveCount( 1 );
+ await expect( flatRate ).toHaveAttribute( 'data-enabled', 'no' );
+} );