Repository navigation
Stop forms clearing contact details, and updates clearing the owner - #34
Merged
Merged
Conversation
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.
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.
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.
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.
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
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
added a commit
that referenced
this pull request
Sep 1, 2026
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
…33) * Let a first import overwrite the contacts it created itself 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. * Mark the contacts a first import creates instead of timing them 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. * Only let the history walk revise the contacts it made 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. * Load the job class before restarting an import 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. * Satisfy phpcs on the lines this branch changed 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 * Reuse the existing email lookup and stop re-asking per order 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 --------- Co-authored-by: tellyworth <alex@automattic.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
tellyworth
added a commit
that referenced
this pull request
Nov 10, 2026
addUpdateCompany() saves custom fields and external sources after the columns, but only on the full update path. A limited field update skipped both without a word. An update becomes a limited field update when "Overwrite Option" (fieldoverride) is on and it comes from an external source: the CSV importer, forms, the API and the sync extensions. So on those sites a CSV import mapping a company custom field left the old value in place, and the source was never recorded against an existing company. A caller passing limitedFields directly fared no better: the custom field keys it named were moved out of the column update "for separate update", which then never ran. Contacts have saved custom fields on either path since 2.98.1, skipping blanks under do_not_update_blanks, and #34 moved their external sources out of the same check. Companies now do the same, from the same shapes. Also fix getCompany() and getCompanies() with withExternalSources: both passed their args as getExternalSources()'s $id, so they always returned false. The grouped variant and every other caller pass -1 first. Found while testing JETCRM-1465 (Automattic/jetpack-crm-extensions#908). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tellyworth
added a commit
that referenced
this pull request
Nov 10, 2026
* Save company custom fields and sources on limited field updates addUpdateCompany() saves custom fields and external sources after the columns, but only on the full update path. A limited field update skipped both without a word. An update becomes a limited field update when "Overwrite Option" (fieldoverride) is on and it comes from an external source: the CSV importer, forms, the API and the sync extensions. So on those sites a CSV import mapping a company custom field left the old value in place, and the source was never recorded against an existing company. A caller passing limitedFields directly fared no better: the custom field keys it named were moved out of the column update "for separate update", which then never ran. Contacts have saved custom fields on either path since 2.98.1, skipping blanks under do_not_update_blanks, and #34 moved their external sources out of the same check. Companies now do the same, from the same shapes. Also fix getCompany() and getCompanies() with withExternalSources: both passed their args as getExternalSources()'s $id, so they always returned false. The grouped variant and every other caller pass -1 first. Found while testing JETCRM-1465 (Automattic/jetpack-crm-extensions#908). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Collapse the company custom field saves into one loop From a /simplify review: the three near-identical addUpdateCustomField() blocks (custom fields, addr_ and secaddr_ address fields) become one list of keys and one loop, with the blank rule stated once. Same behaviour. The test no longer resets the CRM tables twice per test (the base integration test case already does), and fetches through get_company(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #31.
Two fixes here. The first is what #31 asked for. The second is a bug in
addUpdateContact()that review turned up while checking the first, and it is not about forms at all.A form submission does not keep fields it did not send
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 arrives at
addUpdateContact()as a full set of contact fields with everything else blank, so on a default install the details already on that contact are not preserved.There is a setting for it. "Overwrite Option" in Field Options converts the blanks into a limited field update instead. It ships unticked, so the default is to lose the data.
The three form styles now pass
do_not_update_blanksand keep what is on record. 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.Sites that already have the setting ticked see no change at all.
ZeroBSCRM.DAL3.Obj.Contacts.php:2803only ever forcesdo_not_update_blanksto true, never to false, so the setting and the new argument cannot disagree.Why not change the setting instead
Two reasons.
Changing the default would not reach anyone.
WHWPConfigLibpersists defaults rather than falling back to them —initCreate()writes the whole set at install andvalidateAndUpdate()writes any missing key on every load (includes/wh.config.lib.php:80and:90).fieldoverrideis already stored as-1on every existing site, so editing the default inConfig.Init.phpreaches new installs and nothing else.And the setting is still right for the callers it was written for. It governs the API, CSV import and everything else non-manual, where a caller sending a blank may well mean it. A lead capture form is a different proposition, because it has no input for any of the fields in question, so there is no intention to honour.
So this changes the form endpoints and leaves the setting alone.
How
zeroBS_addUpdateCustomer()andzeroBS_integrations_addOrUpdateCustomer()take a trailing$do_not_update_blanks, defaulting tofalse, and forward it. Same shape as the trailing argument #30 added a week ago.addUpdateContact()is unchanged — it has always accepted the option (ZeroBSCRM.DAL3.Obj.Contacts.php:2523); the setting merely forces it true for external sources.The value comes from
jpcrm_form_capture_do_not_update_blanks(), which exists for the filter of the same name. A site that relied on forms clearing fields can returnfalsefrom it and get the old behaviour back without touching the site-wide setting.The external source, which I broke on the way
do_not_update_blanksconverts the update tolimitedFields, andaddUpdateContact()skipped its external sources block wheneverlimitedFieldswas set. So routing forms through it stopped recording the 'form' source against contacts that already existed. Contacts a form created were unaffected, and matching still worked off the email address, but the Source row on the contact record stopped mentioning the form.That call now sits outside the check. It only adds and updates, never removes, so a caller passing no sources leaves the record alone and the other limited field callers are unaffected.
On the authenticated case
I considered allowing the blanking when the submitter is logged in to WordPress under the submitted address, on the grounds that WordPress has confirmed that address and the person is then updating their own record. I left it out.
It would almost never fire — lead capture submitters are rarely logged in — and when it did it would erase details the submitter had not asked to erase, because the form has no inputs for them. A branch with no beneficiary. The authenticated distinction belongs on the API path, where a deliberate blank is a real thing to express.
An update clears the user the contact is assigned to
addUpdateContact()takes an owner defaulting to-1, and the full update path writes it tozbs_owneralong with every other column (:2898). Most callers never name an owner, because most of them are updating fields and have no opinion about who the contact belongs to. That-1landed on the record and unassigned it.-1there means "not specified" rather than "unassign". Nothing assigns a contact through this path:setContactOwner()refuses anything below 1, and so does the ownership box on the contact edit screen. So an update now writeszbs_owneronly when the caller named one. An insert still writes it, because a new contact needs the column set and-1is what an unowned contact holds.Who this was hurting:
modules/portal/class-client-portal.php:289), so a customer editing their own details unassigned their contact.-1.I first wrote the lead capture half of this up as a fix that came free with the blanking change. It was not free, and a second review caught why: it only held for the default path. A site returning
falsefrom the filter, which is advertised as restoring the blanking, went back to the full update path and lost the owner again. Fixing the write itself covers the filter path and the portal as well.Testing
Form_Capture_Blanking_Testin the existingentitiessuite, twelve tests:Contact_Ownership_Test, three more, because the owner fix is in the DAL and is not about forms:The first tests went through a copy of the endpoint's call rather than the endpoint, so nothing covered the three call sites this changes. Drop the argument from any one of them and every test still passed.
submit_lead_capture_form()now fills in$_POSTand posts tozbs_lead_form_capture()itself, catching the exitwp_send_json()ends the request with. One test per form style, so a style added or edited without the option fails on its own.I checked each new test fails without its fix rather than only passing with it:
limitedFieldscheck andtest_submission_records_the_form_as_a_sourcefails onFailed asserting that an array contains 'form'.zbs_nakedcall site and only the naked endpoint test fails, onaddr1. Simple and content grab still pass.test_update_without_an_owner_keeps_the_ownerandtest_submission_does_not_unassign_the_contact_with_the_filter_offfail on-1 is identical tothe owner. The other two ownership tests still pass, which is what I wanted: one covers the insert path and the other names an owner, so neither should depend on the guard.The copy of the endpoint's call is down to one, shared with the #30 tests, whose own copy this branch had left a version behind. It lives in
tests/php/trait-jpcrm-lead-capture-form.phpand loads frombootstrap.php.Contact_Ownership_Testis a second new file in the same directory-globbed suite. So this adds no test suite and does not touch the phpunit configs. #29 and #33 both add one at the same insertion point and will conflict with each other; this stays out of that.Full suite green: 66 tests, 291 assertions.
To verify manually
Create a contact with an address and a mobile number, assign it to a user, and note the Source row on the record.
Put a lead capture form on a page, submit it with that contact's email address and any name.
Before: the address, city, postcode and phone numbers are empty, and the contact is no longer assigned to anyone. After: they are untouched, the assignment holds, the name still fills in if it was blank, and the Source row still lists the form.
Worth also submitting for an email address with no contact behind it, to confirm new leads are still captured.
For the ownership fix on its own, log in to the client portal as a contact assigned to someone and save the profile. Before: the contact comes away unassigned. After: it does not. Changing the owner on the contact edit screen should still work either way.