Skip to content

Fix date custom fields being dropped by the create/update API - #25

Merged
tellyworth merged 5 commits into
trunkfrom
fix/jetcrm-1436-idempotent-date-normalisation
Nov 11, 2026
Merged

tellyworth merged 5 commits into
trunkfrom
fix/jetcrm-1436-idempotent-date-normalisation

Conversation

@donnchawp

@donnchawp donnchawp commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #21

Please don't merge this yet. The tests pass, but there's an end-to-end check still outstanding, see the note at the end.

What was broken

Send a date custom field to the contact or company create/update API and the value is silently thrown away. The contact is created, the response says success, and the custom field is simply missing. The response is misleading because the create endpoints echo the request payload back rather than the record that was saved. #22 covers that separately.

Why

The payload gets normalised twice:

  • api/create_customer.php:51 calls zeroBS_buildContactMeta(), which turns "2026-07-23" into 1784764800.
  • That array goes to zeroBS_addUpdateCustomer(), which calls the builder again with $removeEmpties on.
  • The second pass hits the same date branch, this time with a timestamp. DateTime::createFromFormat( '!Y-m-d', '1784764800' ) fails, jpcrm_date_str_to_uts() returns false, and the empty-stripping at ZeroBSCRM.DAL3.Helpers.php:3029 drops the key before it reaches the DAL.

api/create_company.php does the same thing. The admin UI is fine, it normalises once and goes straight to the DAL.

The fix

The date and datetime branches of zeroBS_buildObjArr() now recognise an already-converted timestamp and pass it through, so normalising twice matches normalising once. New helper jpcrm_value_is_uts() does the check.

I left the double normalisation alone. zeroBS_addUpdateCustomer() is called by a lot of integrations that pass raw fields, so changing its contract is a much bigger job than making the conversion idempotent.

Two decisions worth a look:

The rule for "this is already a timestamp" is an int, or a string of nine or more digits with an optional leading minus. The digit floor is there because a bare is_numeric() would swallow short numeric strings: a date field submitted as "2026" would become a timestamp in 1970 instead of failing to parse the way it does today. Nine digits covers 1973 onwards, and the optional minus covers pre-1970 dates, which matters for birthday fields.

The check runs before the conversion, not after. I had it as a fallback on false first, which is the obvious shape, but it doesn't work for the datetime branch. zeroBSCRM_locale_dateToUTS() falls back to strtotime(), and strtotime( '-631152000' ) doesn't fail, it reads the minus as a relative offset and returns roughly now:

php > date_default_timezone_set('UTC'); var_dump(date('Y-m-d H:i', strtotime('-631152000')));
string(16) "2026-07-29 21:51"

So a pre-1970 datetime would have quietly become today rather than being dropped. Checking first sidesteps that.

One behaviour change to be aware of: a date custom field submitted directly as "1784764800" used to be dropped and will now be stored as that timestamp. That seems right to me, it's the same value the read side hands back, but shout if you disagree.

Tests

tests/php/entities/Object_Array_Builder_Date_Test.php covers the two-pass path for contacts and companies, date and datetime, the pre-1970 case, and that "2026", empty and unparseable values still behave as they did.

All 50 tests across the four suites pass locally in wp-env on PHP 8.3:

OK (50 tests, 214 assertions)

I checked the new tests actually catch the bug rather than just passing alongside it. Reverting includes/ to trunk and running them again fails 6 of the 8:

✘ A date custom field survives the second normalisation pass. with data set "contact"
  The date custom field was stripped before reaching the DAL.
✘ A pre-1970 date custom field survives the second pass without becoming today.
  Failed asserting that null is identical to -631152000.
...
Tests: 8, Assertions: 12, Failures: 6

The two that still pass with the fix reverted are the "behaviour unchanged" ones, which is what you'd want.

There's no PHPUnit workflow in .github/workflows/, so nothing runs these on the PR. phpcs isn't installed locally so the lint didn't run either.

Still to do

  • End-to-end check against a real site: create a contact through the API with a date custom field, then confirm the row in wp_zbs_customfields and the value in the admin UI. The tests here stop at the builder, so that's the gap.
  • Confirm the admin UI create/edit path still saves date custom fields. It normalises once so it should be untouched, but I haven't clicked through it.

Leaving this as a draft until that end-to-end check is done. zeroBS_buildObjArr() is the shared normaliser for contacts, companies, transactions, invoices, quotes and tasks, across the admin UI, API, forms and imports, so it's worth confirming on a real site before it goes anywhere near a release. Happy for someone else to do that check and take it off draft if it's urgent.

Reported by @alllexandrz.

Contact and company date custom fields sent to the API were silently
discarded. The endpoint returned success because it echoes the request
payload rather than the saved record.

api/create_customer.php normalises the payload with zeroBS_buildObjArr(),
turning "2026-07-23" into a timestamp, then passes the result to
zeroBS_addUpdateCustomer(), which normalises it a second time with
$removeEmpties on. The second pass can't read the timestamp the first pass
produced, jpcrm_date_str_to_uts() returns false, and the field is stripped
before it reaches the DAL. api/create_company.php does the same thing.

The date and datetime branches of zeroBS_buildObjArr() now pass an
already-converted timestamp through untouched, so normalising twice matches
normalising once. Adds jpcrm_value_is_uts() for the check.

The check runs before conversion, not after. zeroBSCRM_locale_dateToUTS()
falls back to strtotime(), which reads a negative timestamp as a relative
offset and returns roughly the current time, so a pre-1970 datetime would
never reach a guard placed after the conversion.

Reported by Oleksandr Zaichenko.

Fixes #21
PHPUnit 12 ignores the @dataProvider docblock, so the two data-driven tests
ran with no arguments and errored. The rest of the repo uses attributes
already.

Also assert the key exists before reading it in the two tests that indexed
straight into the result, so a regression fails with the message rather than
an undefined array key warning.
@DevinWalker
DevinWalker requested a review from mikestottuk July 31, 2026 19:07
@mikestottuk

Copy link
Copy Markdown
Contributor

While this works, it's a taping over a symptom that the create_customer.php shouldn't be calling the build meta.

@donnchawp did you explore reworking the /api/create_customer.php (and other relevant API files). Here's where that got to

#27

I think if we point an agent at the API layer, and ask it to rework it, it would be beneficial and any API docs (so the correct date format is passed by the user) could be auto-generated on the back of it.

@donnchawp donnchawp self-assigned this Aug 5, 2026
@donnchawp

Copy link
Copy Markdown
Contributor Author

Thanks @mikestottuk. Will take a look at that!

@donnchawp

Copy link
Copy Markdown
Contributor Author

I've written the end-to-end test this needed and it settles the reported bug either way.

tests/php/rest-api/API_Date_Custom_Field_Test.php registers a real date custom field, makes the same calls api/create_customer.php and api/create_company.php make, then reads the record back out of the database. Against trunk:

✘ A date custom field sent to the contact create API is stored.
  Failed asserting that '' matches expected 1784764800.
✘ A date custom field sent to the company create API is stored.
  Failed asserting that '' matches expected 1784764800.

With this branch both pass, and the full suite is green at 52 tests. The '' is what the read side returns for a custom field that was never written, so that's the value going missing between the endpoint and wp_zbs_customfields, not a builder simulation.

Where it goes. The second normalisation is inside zeroBS_addUpdateCustomer() at includes/ZeroBSCRM.DAL3.Helpers.php:1863, which calls the builder again with $removeEmpties on. Pass one writes zbsc_contract-date as a UTS, pass two reads zbsc_contract-date and tries DateTime::createFromFormat( '!Y-m-d', '1784764800' ), which fails. false is empty, so the key is dropped at Helpers.php:3049, and addUpdateContact() skips absent custom fields at Contacts.php:3087. Nothing is written and nothing complains.

On your point about the endpoint. You're right, and I'd put it more strongly than "it causes this bug". create_customer.php:51 normalises before anything has looked at the payload, and the builder pre-fills every field in the model with '' (Helpers.php:2693-2700). After that line you can't tell what the client sent. {"email":"a@b.com"} and a payload that deliberately blanked twenty fields are the same array. That information is gone before any decision uses it, which is why jpcrm_api_prepare_contact_fields() in #27 has to load the contact back out of the database to reconstruct it. So the endpoint parses the request into a shape that can't answer the questions the endpoint needs to ask, and both the date bug and the clobbered-fields bug fall out of that. #27 should land.

Where I'd still push back is that #25 isn't only about the API. The internal representation of a date here is already a UTS. zbscf_objval holds the timestamp and tidyAddCustomFields() (ObjectLayer.php:826) returns it as the value, adding _cfdate and _date_str alongside as views of it. So the builder is a boundary converter, and every other branch of that switch already survives being run twice: tel and textarea are sanitize_text_field() and sanitize_textarea_field(), numberint ends in intval(), price and numberfloat in floatval(). date is the only branch where the output type can't be the input type, so it's the only one where normalising twice differs from normalising once. I called it a workaround in the PR body. That was wrong of me. It's one branch not honouring the contract the rest of the switch honours.

That matters because the builder is shared. Three callers hand it an array that's already been through it: create_customer.php:51, create_company.php:30, and zeroBSCRM_mergeCustomers(), which sets $masterNewMeta = $master from zeroBS_getCustomer() at Helpers.php:1343 and passes it to zeroBS_addUpdateCustomer() at line 1471. Everything else normalises once and goes straight to addUpdateContact(): the admin metaboxes, the client portal, woo-sync my-account, and every integration pushing raw fields. Those are fine.

The merge one is the interesting case, because reworking the API layer doesn't reach it. I wrote a test and it confirms the bug. On trunk, merging a contact whose main record has an empty date custom field and whose secondary record has a value silently drops the value, and this branch fixes it:

Trunk:  ✘ Merging contacts copies a date custom field from the secondary record.
          Failed asserting that '' matches expected 1784764800.
Branch: OK (1 test, 2 assertions)

I've kept that test out of this PR and opened #28 for it. It trips a pre-existing deprecation at ZeroBSCRM.DAL3.ObjectLayer.php:934, where strlen() gets a null tw/fb/li for any contact without socials, and failOnDeprecation turns that into a failing suite. It fires on trunk too, so it's unrelated to dates.

Two notes on #27 as it stands. It only does the contact endpoint, so create_company.php has the same shape waiting. And jpcrm_api_prepare_contact_fields() reads existing values back into the builder, which is the same UTS-into-the-date-branch pattern. Today that no-ops rather than corrupting, because the key gets stripped and the custom field is skipped, so the preservation works by accident. With the idempotency fix underneath it, it works for the right reason.

I'd also say moving the endpoint from full-row replace to PATCH semantics is a public behaviour change worth its own issue and release note, rather than arriving as part of a date fix.

A correction to my own description. The datetime half of this PR is defensive, not a live bug for contacts or companies. zeroBSCRM_customfields_acceptableCFTypes() (DAL3.Fields.php:1380) doesn't list datetime, so that branch is only reachable on transaction model fields. The pre-1970 strtotime() problem is real, but not from any path #21 covers. I oversold it.

The weakest part of this PR is the nine-digit check, and it's worth saying where it comes from. DateTime::getTimestamp() returns an int, so is_int() covers the API double pass exactly with no guessing. The regex is only there for values coming back out of the database, where wpdb hands you "1784764800" as a string. So the heuristic is paying for the DAL not casting its own column types on read, not for the double normalisation. Fixing it at that end would be cleaner, but tidyAddCustomFields() initialises those keys to '' and branches on '' === for the display strings, so casting there changes what every consumer sees. Not something I want to bundle in here. Shout if you'd rather I tried it.

The end-to-end check I had outstanding is now covered by tests rather than by clicking through a site, so this can come out of draft whenever someone's happy with it. You're away until the 13th, so I'll leave it unless somebody else wants to pick it up.

On pointing an agent at the API layer and generating docs from it, agreed. The format the endpoint expects is undocumented and that's most of why this went unnoticed.

The tests in Object_Array_Builder_Date_Test.php stop at
zeroBS_buildObjArr(). These go the whole way: they register a real date
custom field, make the same calls api/create_customer.php and
api/create_company.php make, then read the record back out of the
database.

Both fail against trunk, where the read side returns '' for a custom
field that was never written, and pass with the idempotency fix.

register_custom_field() goes on the base integration test case because
custom fields are stored twice, once per object type for DAL3 and once
in the legacy customfields setting. zeroBSCRM_unpackCustomFields() gates
the DAL3 overload on the object key existing in the legacy setting, so
both are needed before the field reaches the field globals.
@tellyworth

Copy link
Copy Markdown
Contributor

Ran the outstanding end-to-end check in wp-env (PHP 8.3, MySQL 8, WP 7.1.3), over real HTTP against /zbs_api/create_customer with generated API creds and a date custom field (e2e-date) registered via updateActiveCustomFields():

On this branch:

  • Create: POST {"email":…, "e2e-date":"2026-07-23"} → row in wp_zbs_customfields with zbscf_objkey=e2e-date, zbscf_objval=1784764800 (= 2026-07-23). DAL read-back (getContact with withCustomFields) returns the value — the same read the admin edit page renders from.
  • Update: POST again with "id":1, "e2e-date":"2026-09-15" → stored value updated to 1789430400. ✓
  • Admin path (the second open question): mirrored the metabox save exactly — one zeroBS_buildContactMeta() pass over zbsc_-prefixed POST data straight into addUpdateContact() (MetaBoxes3.Contacts.php:329,414) → stored 1785542400 (= 2026-08-01). Single-pass normalisation unaffected. (Code-path simulation, not a browser click-through.)

On trunk (control): the identical HTTP create returns success and echoes the date back, but no wp_zbs_customfields row is written — the exact silent drop this PR fixes (the misleading echo being #22's territory).

That closes out the "Still to do" list, so per the PR description I'll take this off draft.

Two merge notes:

  • The branch currently conflicts with trunk in one file only, tests/php/class-jpcrm-base-integration-testcase.php — production code merges clean, so it's a quick rebase.
  • Overlaps with Fix partial customer updates in legacy API #27, which removes create_customer's first zeroBS_buildContactMeta() pass. This fix is correct independently (idempotence helps every double-normalisation path, not just this endpoint), but whichever lands second should re-test the other's scenario.

@tellyworth
tellyworth marked this pull request as ready for review October 20, 2026 02:23
tellyworth and others added 2 commits November 11, 2026 15:38
# Conflicts:
#	tests/php/class-jpcrm-base-integration-testcase.php
The helper rewrote the customfields settings and the field globals, which
outlive the test: a later company custom field test then saw stale settings
and treated its field as a column. It now records what it changed and
tear_down() puts it back.

Also file doc comments and comment punctuation in the new tests, and the
naming ignore on the second sanitised line, for the PHP lint added since
this PR was opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tellyworth

Copy link
Copy Markdown
Contributor

Brought this up to date with trunk for 6.8.6 (merged trunk in rather than rebasing, so no force-push; it'll be squash-merged).

  • Conflict in tests/php/class-jpcrm-base-integration-testcase.php: trunk added create_contact_owner() where this adds register_custom_field(). Kept both.
  • Test isolation: register_custom_field() rewrote the customfields settings and the field globals, which survive the test. With Save company custom fields and sources on limited field updates #100's Company_Limited_Update_Test now on trunk, running after this PR's API test made it treat its custom field as a column and fail (default order only). The helper now records what it changed and tear_down() restores it.
  • Lint for the phpcs check added to CI since this was opened: file doc comments and comment punctuation in the two new tests, and the naming ignore on the second sanitize_text_field() line.

Suite (216 tests) passes in default, reverse and random order; composer cs and the next-version lint are clean.

@tellyworth tellyworth added this to the 6.8.6 milestone Nov 11, 2026
@tellyworth
tellyworth merged commit 1129b9f into trunk Nov 11, 2026
4 checks passed
tellyworth added a commit that referenced this pull request Nov 17, 2026
…n the field length check

Merging contacts copies a date custom field from the secondary record since
#25. This adds the test for it. The merge passes unset social fields to the
length check as null, so that check now casts to a string first.

Fixes #28.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
tellyworth added a commit that referenced this pull request Nov 17, 2026
…n the field length check (#110)

Merging contacts copies a date custom field from the secondary record since
#25. This adds the test for it. The merge passes unset social fields to the
length check as null, so that check now casts to a string first.

Fixes #28.

Co-authored-by: Claude Fable 5.2 <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.

API create_customer drops date custom fields (double date parse)

3 participants