Skip to content

Let a first Woo Sync import overwrite the contacts it created itself - #33

Merged
tellyworth merged 7 commits into
trunkfrom
fix/woosync-backfill-protection-window
Sep 1, 2026
Merged

tellyworth merged 7 commits into
trunkfrom
fix/woosync-backfill-protection-window

Conversation

@donnchawp

@donnchawp donnchawp commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #32.

What

During a Woo Sync first import, the contact field protection added in #30 only applies to contacts that were already in the CRM when the import started.

Why

The import walks order history oldest first, creating contacts as it goes. So the first order to mention an email address fills in the blanks, and every later order is locked out of those fields. Somebody who ordered three times and moved house in between ends up with the address from their oldest order.

Before #30 each order overwrote the last, and since the walk is oldest first, that meant the newest order won. That was the better answer for a backfill and I did not mean to change it.

The reasoning behind protecting a field is that a CRM user may have corrected it by hand. That does not hold for a contact the same import created seconds earlier from an older order.

How

The first version of this compared the contact's creation time against a timestamp stamped when the import began. That does not work, and the second commit replaces it.

Woo Sync sets zbsc_created from the order's date (class-woo-sync-background-sync-job.php:1478), and the DAL honours a caller-supplied created on insert, so a contact the import creates from a 2019 order carries a 2019 creation time. Every contact the import makes therefore looks older than the import, and the bug survives untouched. It gets the answer backwards too: the only contacts whose creation time lands after the import started are the ones created mid-run by something that does not supply a date, so a contact somebody typed in by hand on day two of a long backfill would lose its protection on day three.

So instead of deriving the answer, the import records it where it already knows it. import_crm_object_data() resolves the contact an order matches before it writes, which tells it whether the order is creating the contact or updating one that was already there. That is written to the contact as woosync_first_import_created meta, valued with the sync site key, and only ever at the moment of creation. The protection then reads:

$is_guest_order && ! $this->contact_created_by_import_walk( $existing_contact_id )

Which comes out as:

Case Protected
The history walk creates the contact from a 2019 order, a 2025 order follows No, the newest order wins
Contact added by hand while the import is running Yes, and it stays protected across every later order
Contact already in the CRM before the import Yes
Contact created by another store's import Yes, as far as this store's import is concerned
Contact created by an order arriving on the site during the import Yes, from the moment it exists
Order with a WooCommerce account behind it Nothing protected, as before
Order with no contact behind it Nothing to protect

Dropping the timestamp takes a few problems with it. There is no first_import_started attribute any more, so class-woo-sync.php is back to what it was and the fixed key list in update_sync_site() cannot silently drop it. There is no stale stamp for a restarted import to inherit. The lookup is now the onlyID form, the same query addUpdateContact() runs to decide insert from update, so it resolves to the same contact and avoids the email query with the OR ... IN (SELECT ...) that the DAL keeps a fast path for (#gh-2450).

Testing

New woo-sync suite, registered in the three phpunit configs. The job is handed its site info directly, so nothing in it needs WooCommerce or the Woo Sync module to be loaded, which is what let the earlier version go untested.

Twelve tests: the truth table above, the seams under it, and one apiece for the two bugs review turned up. The one that matters most is still:

Woo Sync stores the order's date as the contact's creation time, so creation time cannot say who made the contact.

That is the test that would have failed the first attempt.

I confirmed each of the two regression tests fails on its own with its fix backed out — test_a_live_order_does_not_get_the_walk_exemption with the walk guard removed, test_restarting_an_import_clears_the_marks with the clear stubbed out — and that nothing else fails in either case.

Full suite green, 63 tests, 250 assertions.

What review changed

Two reviewers found the same shape of mistake twice, in both cases a condition that is right for the walk through order history and wrong for something else that shares the code path.

import_crm_object_data() serves the walk and it serves add_update_from_woo_order(), which is hooked to woocommerce_order_status_changed and friends. ! first_import_completed() was standing in for "this is the walk", and it is equally true of an order placed on the site while the first import is running. A guest checkout could therefore create a contact, have it marked as one the import created, and any later guest checkout quoting that address was free to overwrite it, over a CRM user's correction included. That is what #30 exists to prevent, restored for the length of every first import, and unbounded where an import stalls.

There is a flag for it now. import_orders_from_store() and import_orders_from_api() set is_first_import_walk, nothing else does, and both the marking and the exemption require it. A contact a live order creates is new to the CRM as of now, so it is protected from the moment it exists, exactly like one added by hand.

The second was the hub's restart. It reset the progress and left the marks in place, so a resync treated every contact the previous import created as one it had just created, and months of hand corrections were open to being replaced by guest billing data. Under #30 alone a resync preserved them, so this PR introduced it. Resetting the progress and clearing the marks are one operation now, Woo_Sync::restart_first_import(), so there is no version of this where a caller does half the job. The clear is scoped to the site key, so restarting one store on a multi-store install leaves the others alone.

Three smaller things came out of the same review:

  • existing_contact_id() now only runs when the walk can act on the answer. It was running on every order write for the life of the site, including on the checkout request, and being read by nothing once the import had finished.
  • contact_predates_import() is now contact_created_by_import_walk(). It never meant "was already in the CRM" — it meant "not created by this store's import" — and the first fix moved the old name further from the truth.
  • A failed mark writes to the debug log rather than passing silently, since the consequence is the reported bug surviving with no trace.

Notes

The earlier claim that contact_fields_to_protect() could not be covered because Woo is not installed was wrong. Its only module dependency is first_import_completed(), and PHP dispatches that virtually even from inside a private method, so a subclass can stand in for it. It is protected now and the tests reach it through Test_Sync_Job, which also stands in for first_import_walk_in_progress() — the one seam everything the walk does differently hangs off. The decision itself is covered, not just the helpers under it.

So I ran a backfill by hand instead, in wp-env with WooCommerce 11.0.1 installed alongside the plugin. Three guest orders for one email address, oldest first, the scenario from #32:

Order Date Billing address
#12 2019-03-04 19 Prospect Hill, Galway
#13 2022-07-19 66 Sundays Well Road, Cork
#14 2025-11-02 12 Blarney Street, Cork

The contact comes out of the import holding 12 Blarney Street. The newest order wins, which is what #32 asked for.

Then the case the first attempt had backwards. I added a contact by hand with an address of its own, gave it two old guest orders, and restarted the first import. Every hand-entered field survived, across both orders. A third guest order arriving after the import had finished left it alone too, so the protection from #30 still does its job.

The contact from the first run has a created of 2019-03-04, the date of its oldest order. That is the reason the timestamp version could not have worked, visible in a live store.

Setting this up needs one thing that is not obvious: cron_job() defines jpcrm_woosync_cron_running and bails on the second call, so each page of the import has to run in a fresh process.

phpcs is not in vendor/bin and phpcs-changed is not installed, so make lint no-ops. This has not been linted.

Costs one indexed lookup and one meta read per order while a first import's walk is running, and one meta row per contact that walk creates. Nothing on a live order, and nothing once the import has finished.

Two things from the review of #30 are still open and not addressed here: the partial address hazard, where a guest's city can be grafted onto a stored street and postcode, and #31.

Also not addressed, and worth knowing: a site upgrading mid-first-import carries no marks for the contacts that import has already created, so those stay locked to their oldest order until the sync is restarted. And "oldest first" is really lowest order ID first (orderby => 'ID'), which is not date order on a store migrated in from another platform. Neither is introduced here.

A Woo Sync first import works through order history oldest first, creating
contacts as it goes. With the field protection added in #30, the oldest order
to mention an email address fills in the blanks and every later order is then
locked out, so a backfill leaves people holding the address they had when they
first ordered rather than the one they use now.

Protecting a contact makes sense once somebody could have corrected it by hand.
It does not when the same import created it seconds earlier from an older order.

So during a first import we only protect contacts that were already in the CRM
when it started. Everything else is unchanged: once the import has finished,
every contact predates it and ordinary orders protect as before.

`first_import_started` is stamped at the top of each page of orders, and only
the first call of an import writes it. It is cleared when the import finishes so
a restart takes a fresh one. Note that `update_sync_site()` rebuilds the record
from a fixed list of keys, so an attribute that is not in that list is silently
dropped on the next write. Both copies of the list needed the new key.

The lookup asks `getContact()` for a limited field set, which comes back through
`lazyTidyGeneric()` rather than `tidy_contact()`, so the creation time reads as
`created` rather than `zbsc_created`. Getting that wrong would fail silently, in
the same way the shipping fields did, so there is a test for the lookup itself.

Woo is not installed in the test environment, so the sync job is still not
covered end to end. The seam it depends on is.
The timestamp check does not work. Woo Sync sets a contact's `zbsc_created`
from the order's date, so a contact the import creates from a 2019 order
carries a 2019 creation time and reads as though it had been in the CRM for
years. Comparing that against the moment the import started tells you nothing,
and the backfill still leaves people holding the address from their oldest
order.

It also gets the answer backwards. The only contacts whose creation time lands
after the import started are the ones created during the run by something that
does not supply a date: somebody typing into the CRM, a lead capture form, the
API, another integration. Those are exactly the records the protection is for,
and they were the ones losing it.

So rather than working the answer out from a timestamp, note it where we
already know it. `import_crm_object_data()` resolves the contact an order
matches before it writes, so it knows whether the order is about to create the
contact or update one that was already there. That is now written to the
contact as `woosync_first_import_created` meta, holding the key of the sync
site whose import created it, and only ever at the moment of creation. A later
order in the same run sees the mark and is free to replace what an older one
filled in. A contact added by hand has no mark and keeps its protection,
whenever it was added and however many orders arrive after it.

Dropping the timestamp takes a few problems with it. There is no
`first_import_started` attribute any more, so `class-woo-sync.php` goes back to
what it was and cannot quietly drop the key on the next write. There is no
stale stamp for a restarted import to inherit. And the lookup is now the
`onlyID` form, the same query `addUpdateContact()` runs to decide insert from
update, so it resolves to the same contact and skips the slow email query the
DAL keeps a fast path for.

Tests move to a `woo-sync` suite. The job is handed its site info directly, so
none of it needs WooCommerce or the Woo Sync module loaded. The first test pins
the thing that broke the last attempt: a contact created the way Woo Sync
creates one carries the order's date, not the time the import ran.
Two reviewers found the same shape of bug twice: the condition is right for the
first import's walk through order history and wrong for the other things that
share the code path.

`import_crm_object_data()` serves the walk and it serves the hooks that fire
when an order arrives on the site. `! first_import_completed()` was standing in
for "this is the walk", and it is equally true of a live order placed while the
first import is running. So a guest checkout could create a contact, get it
marked as one the import created, and any later guest checkout quoting that
address was then free to overwrite it, including over a correction a CRM user
had made in between. That is the behaviour #30 exists to prevent, restored for
the length of every first import, and unbounded where an import stalls.

There is now a flag for what was being inferred. `import_orders_from_store()`
and `import_orders_from_api()` set it, nothing else does, and both the marking
and the exemption require it.

The second is the hub's restart. It reset the progress and left the marks
behind, so a resync treated every contact the previous import created as one it
had just created itself, and months of hand corrections were open to being
replaced by guest billing data. Resetting the progress and clearing the marks
are one operation now, `restart_first_import()`, so there is no version of this
where a caller does half of it.

Also here:

- `existing_contact_id()` only runs when the walk can act on the answer. It was
  running on every order write for the life of the site and being read by
  nothing once the import had finished.
- `contact_predates_import()` is now `contact_created_by_import_walk()`. It
  never meant "was already in the CRM", and after the first fix the old name
  was further still from the truth.
- A failed mark says so in the debug log rather than passing silently.

The tests cover the decision rather than only the helpers under it.
`contact_fields_to_protect()` is protected and reached through a subclass, which
also stands in for `first_import_walk_in_progress()` — the one seam everything
the walk does differently now hangs off. That covers the truth table, the
account-order case, and both bugs above; each of the two new regression tests
fails on its own without its fix.
restart_first_import() calls a static on Woo_Sync_Background_Sync_Job, and
nothing guaranteed the class was there. The background sync only requires it
when verify_ready_mode() passes, which turns on the jpcrm_woosync_52_mig
option, and the hub page renders whether that option is set or not. On an
install without it, clicking through the restart confirmation was a fatal.

Also fixes a docblock still pointing at contact_predates_import(), which the
last commit renamed.
@donnchawp donnchawp modified the milestones: 6.8.3, 6.8.4 Aug 18, 2026
tellyworth and others added 3 commits August 28, 2026 15:06
The PR notes said "This has not been linted" — make lint no-oped before
CI: fix the two real gaps (a missing @var, a comment full stop), take the
established inline ignores for $zbs->DAL and $ZBSCRM_t (the same names
every caller ignores, per class-mailpoet-background-sync-job.php), and
scope a OneObjectStructurePerFile disable to the test file whose helper
subclass lives beside it, as WP_UnitTestCase_Fix.php already does.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RvvHfGbJ9Qd4pqibZyh2g7
From a /simplify review of this branch together with #34:

- existing_contact_id() now delegates to zeroBS_getCustomerIDWithEmail(),
  the same lookup addUpdateContact() makes, rather than hand-rolling a
  copy of it. The copy also passed 'ignoreOwner', which getContact()
  ignores (it reads 'ignoreowner'), so the two were already running the
  identical query.
- The walk memoises what it learns on the job: email-to-contact lookups
  and mark checks, both of which were an uncached query per order and
  are asked repeatedly about the same repeat customers. A job never
  spans a restart (each page runs in its own process), so the answers
  cannot go stale on it.
- import_crm_object_data() reads first_import_walk_in_progress() once
  into a local instead of three times per order.
- The tests that check marks persist now do so through a fresh job, as
  the walk's own pages would, so the memo cannot answer for the stored
  mark. The fixture's repeated (email, order date) incantation is now
  its defaults.

Full suite green, 122 tests, 391 assertions. phpcs clean on the
changed lines.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KLtQPfBVmAH2vuER7WWbdT
tellyworth added a commit that referenced this pull request Sep 1, 2026
From a /simplify review of this branch together with #33:

- The owner guard now follows the companies DAL: zbs_owner is left out
  of the base column arrays and appended when written, on update only
  when the caller named one. The unset()-plus-array_shift() pairing it
  replaces held the two parallel arrays together by position, an
  invariant documented only by a comment ninety lines away.
- The blanks decision is made once above the form-style switch, with the
  one sanitised email read, instead of once per case. A style added
  later cannot silently miss it.
- capture_json_response() is hoisted from Invoice_Capability_Test into
  JPCRM_Base_TestCase and the lead capture trait uses it too, so there
  is one copy of the wp_die-interception plumbing.
- The owner-capable-user fixture lives once on the base integration
  test case as create_contact_owner(), the contact-with-details fixture
  goes through add_contact(), and the five details-intact assertions
  live once in assert_contact_details_intact().

Full suite green, 125 tests, 432 assertions. phpcs clean on the
changed lines.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KLtQPfBVmAH2vuER7WWbdT
@tellyworth
tellyworth merged commit 0bcdaf7 into trunk Sep 1, 2026
4 checks passed
@tellyworth
tellyworth deleted the fix/woosync-backfill-protection-window branch September 1, 2026 05:02
tellyworth added a commit that referenced this pull request Sep 1, 2026
)

* Keep contact details a lead capture form did not collect

A lead capture form collects a name and an email address. The submission is
matched to a contact on that address, which is what we want, but it reaches
addUpdateContact() as a full set of contact fields with everything else blank.
So on a default install a submission against an existing contact empties the
address, the city, the postcode, both telephone numbers and the social fields.

There is a setting for this. "Overwrite Option" in Field Options turns the
blanks into a limited field update instead, and it ships unticked, so the
default is to lose the data.

The forms have no input for any of the fields being emptied, so a blank
arriving from one is an absence rather than an instruction. The three form
styles now pass do_not_update_blanks and keep what is on record.

This leaves the setting alone. It still decides the question for the API and
every other non-manual source, where a caller sending a blank may well mean it.
A public form is a different proposition: it takes submissions from anyone
against any email address, so there is nobody whose intention we would be
honouring.

zeroBS_addUpdateCustomer() and zeroBS_integrations_addOrUpdateCustomer() take a
trailing do_not_update_blanks argument to carry it, defaulting to false, so
every other caller behaves as it did. addUpdateContact() is unchanged; it has
always accepted the option.

A site that wants the old behaviour back can return false from
jpcrm_form_capture_do_not_update_blanks.

Fixes #31.

* Keep recording where a contact came from, and test the endpoint

Routing form submissions through do_not_update_blanks converts the update to
a limited field update, and addUpdateContact() skips its external sources
block whenever limitedFields is set. So the fix stopped recording the 'form'
source against every contact that already existed. Contacts created by a form
were unaffected, and matching still worked off the email address, but the
Source row on the contact record stopped mentioning the form.

Move that call outside the limitedFields check. It adds and updates and never
removes, so a caller passing no sources leaves the record alone, and the other
limited field callers are unaffected. The assignment went with it: the update
path never read the return, only the insert path does.

The tests went through a copy of the endpoint's call rather than the endpoint,
so nothing covered the three call sites the previous commit changed. Drop the
argument from any one of them and every test still passed. They now also post
to zbs_lead_form_capture() itself, once per form style.

The copy of that call is down to one, shared with the #30 tests, whose own
copy was left a version behind by the previous commit.

* Pin the owner a form submission used to clear

The full update path writes every column, the owner among them, and nothing on
this path supplies one. So a submission wrote -1 back over whoever the contact
was assigned to and unassigned it. A limited field update leaves the column
alone, which means keeping blanks off the update fixed this as well, quietly.

Nothing said so, so nothing stopped a later change to that path from undoing
it. This asserts it.

* Stop an update clearing the user a contact is assigned to

addUpdateContact() takes an owner defaulting to -1, and the full update path
writes it to zbs_owner with every other column. -1 there means "not specified",
not "unassign": setContactOwner() refuses anything below 1, and so does the
ownership box on the contact edit screen. Nothing assigns a contact this way.

So any caller updating a contact without naming an owner cleared whoever it was
assigned to. Most callers do not name one. A client portal profile save does it
with no form involved, and so did a lead capture submission until the previous
commit routed those through the limited field update instead.

That fix only held for the default path. A site returning false from
jpcrm_form_capture_do_not_update_blanks, which is advertised as restoring the
blanking, went back to the full update path and lost the owner again. Fixing
the write itself covers both, and the portal.

An insert still writes the column. A new contact needs it set, and -1 is what
an unowned contact holds.

Found in review.

* Satisfy phpcs on the lines this branch changed

All three sites are pre-existing style carried on changed lines, not new
code: the two legacy camelCase signatures do_not_update_blanks was
appended to (renaming a public API is not on), and the test trait's
read of \$_POST, which simulates the public form endpoint that has no
nonce by design. Inline ignores in the established style.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RvvHfGbJ9Qd4pqibZyh2g7

* Take the shapes the codebase already has for the owner fix and the tests

From a /simplify review of this branch together with #33:

- The owner guard now follows the companies DAL: zbs_owner is left out
  of the base column arrays and appended when written, on update only
  when the caller named one. The unset()-plus-array_shift() pairing it
  replaces held the two parallel arrays together by position, an
  invariant documented only by a comment ninety lines away.
- The blanks decision is made once above the form-style switch, with the
  one sanitised email read, instead of once per case. A style added
  later cannot silently miss it.
- capture_json_response() is hoisted from Invoice_Capability_Test into
  JPCRM_Base_TestCase and the lead capture trait uses it too, so there
  is one copy of the wp_die-interception plumbing.
- The owner-capable-user fixture lives once on the base integration
  test case as create_contact_owner(), the contact-with-details fixture
  goes through add_contact(), and the five details-intact assertions
  live once in assert_contact_details_intact().

Full suite green, 125 tests, 432 assertions. phpcs clean on the
changed lines.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KLtQPfBVmAH2vuER7WWbdT

---------

Co-authored-by: tellyworth <alex@automattic.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Woo Sync backfill leaves a contact holding the address from their oldest order

2 participants