Repository navigation
fix: tax rate inputs blank with comma-decimal locales - #4555
Conversation
The to_tax_decimals() function returns locale-formatted values (e.g. "18,00" for comma-decimal locales like fr_FR, de_DE). Browsers reject comma-decimal values in <input type="number"> and render the field blank. Use raw float value instead - PHP serializes floats with period decimal regardless of locale. The parse_tax() on the save side already handles locale-aware parsing, so round-tripping works correctly. Fixes #4553 Regression from commit 42ba39d
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughTwo tax rate input value bindings in the tax configuration view are updated to render period-decimal or empty values instead of locale-formatted strings, enabling correct rendering across comma-decimal locales while maintaining ChangesTax config input value binding fix
Estimated code review effort🎯 1 (Trivial) | ⏱️ ~3 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
| 'id' => 'default_tax_1_rate', | ||
| 'class' => 'form-control input-sm', | ||
| 'value' => to_tax_decimals($config['default_tax_1_rate']) | ||
| 'value' => $config['default_tax_1_rate'] !== '' ? (float) $config['default_tax_1_rate'] : '' |
There was a problem hiding this comment.
Here is what claude thinks
he PR's fix is wrong direction. But so is the original code.
Actual bug trace:
tax_config.php inputs have type="number" (lines 54, 79)
Browser type="number" always submits dot-separated values (5.5) regardless of locale
Config.php:812 runs parse_tax(filter_var("5.5", FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION))
filter_var produces "5.5" (unchanged)
parse_tax("5.5") calls NumberFormatter::parse("5.5") with de_DE locale
de_DE locale treats . as thousands separator — parses "5.5" as 5 (stops at dot), drops decimal
Result: 5.5% silently saved as 5%.
The PR's approach (remove to_tax_decimals() from display) doesn't fix this. Display was never the problem — type="number" inputs already ignore locale formatting for submission. Removing to_tax_decimals() just changes what the user sees while the save bug persists.
Correct fix — two options:
Option A — fix the controller, drop parse_tax() for these fields since data comes from type="number" inputs (always dot-decimal):
// Config.php:812-814
'default_tax_1_rate' => (float) filter_var($default_tax_1_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
'default_tax_2_rate' => (float) filter_var($default_tax_2_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
Option B — fix parse_tax() / parse_decimals() to detect dot-decimal input and not misinterpret it through a comma-locale formatter. Harder, fragile.
Option A is right. parse_tax() exists for text inputs where users type locale-formatted numbers (e.g., tax_rates_form.php uses type="text" + to_tax_decimals() display — that's the correct use case). For type="number" inputs, bypassing parse_tax() is correct behavior, not a workaround.
Summary: PR treats symptom, not cause. Fix is in Config.php — drop parse_tax() wrapper for type="number" fields and cast directly to float. Also verify Items.php:700 — check whether those tax percent inputs are type="number" or type="text".
When I inquired about modifying parse_tax instead of removing it, it seems that it has a good point about ambiguity of intent. Here is what it said.
Yes, but tricky.
parse_tax() → parse_decimals() uses NumberFormatter::parse() which is locale-aware by design. Problem: it can't distinguish between:
"5.5" from a type="number" input (always dot = decimal point)
"5.5" typed by a de_DE user (dot = thousands separator, means 5500)
Both arrive as the same string. No way to know intent.
The only clean fix inside parse_decimals() would be: before passing to NumberFormatter, normalize dot-decimal strings to the current locale's format. E.g., for de_DE, convert "5.5" → "5,5" first. But that breaks if a de_DE user types "1.000" meaning one thousand.
Real fix is at the call site — caller must know the input source:
type="number" input → dot is always decimal → use (float) directly
type="text" input → locale-formatted → use parse_tax()
parse_tax() itself is correct for its intended use case (tax_rates_form.php text input). It doesn't need fixing — it needs to not be called on type="number" POST data.
The display fix (using (float) instead of to_tax_decimals()) was correct but incomplete. The save path in Config.php also needed fixing because parse_tax() misinterprets dot-decimal values from type="number" inputs when locale uses comma as decimal separator. Root cause: Browsers submit type="number" inputs as dot-decimal (e.g., "5.5") regardless of locale. With comma-decimal locales like de_DE, parse_tax() treats the dot as thousands separator, causing 5.5 to be saved as 5. Fix: Replace parse_tax() with direct (float) cast for these inputs since type="number" already guarantees dot-decimal format. Includes tests for tax rate handling with various decimal values. Fixes #4553
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/Controllers/ConfigTest.php (1)
312-325: ⚡ Quick winAssert persisted value in empty-string tax-rate test.
This test only checks
success; it won’t catch persistence regressions for empty input. Add an assertion ondefault_tax_1_rate(expected behavior, e.g.0.0) after the POST.Suggested test addition
public function testTaxRate_HandlesEmptyString(): void { $this->resetSession(); $response = $this->post('/config/saveTax', [ 'default_tax_1_rate' => '', 'default_tax_1_name' => 'Tax 1', 'tax_included' => '0', ]); $response->assertStatus(200); $result = json_decode($response->getJSON(), true); $this->assertTrue($result['success']); + + $config = model(Appconfig::class); + $savedRate = $config->get_value('default_tax_1_rate'); + $this->assertEquals(0.0, (float) $savedRate, 'Empty tax rate should persist as 0.0'); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/Controllers/ConfigTest.php` around lines 312 - 325, The test testTaxRate_HandlesEmptyString currently only asserts success; update it to also assert that the empty-string input was persisted as the expected numeric value (e.g. 0.0) for default_tax_1_rate. After the POST in testTaxRate_HandlesEmptyString, retrieve the saved configuration (via the same config endpoint or the Config model/DB retrieval used elsewhere in tests) and add an assertion that default_tax_1_rate equals 0.0 to catch persistence regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/Controllers/Config.php`:
- Around line 811-818: The code is casting sanitized-but-not-validated tax
inputs to float (e.g., default_tax_1_rate, default_tax_2_rate) which can accept
malformed strings; instead, validate the incoming tax-rate strings against the
strict dot-decimal format before casting and persist only if valid. Update the
handler in Config (the method that builds $batch_save_data) to run a validation
step (e.g., regex /^\d+(\.\d+)?$/ or use FILTER_VALIDATE_FLOAT with appropriate
flags) on $default_tax_1_rate and $default_tax_2_rate, return an error response
if validation fails, and only then use (float) cast or sanitized value for the
batch_save_data assignment. Ensure the check is applied to both
default_tax_1_rate and default_tax_2_rate (and any similar tax fields) and keep
the existing comment about parse_tax() unchanged.
---
Nitpick comments:
In `@tests/Controllers/ConfigTest.php`:
- Around line 312-325: The test testTaxRate_HandlesEmptyString currently only
asserts success; update it to also assert that the empty-string input was
persisted as the expected numeric value (e.g. 0.0) for default_tax_1_rate. After
the POST in testTaxRate_HandlesEmptyString, retrieve the saved configuration
(via the same config endpoint or the Config model/DB retrieval used elsewhere in
tests) and add an assertion that default_tax_1_rate equals 0.0 to catch
persistence regressions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: b3175f38-bf69-4762-8d7e-b2d7905d451f
📒 Files selected for processing (2)
app/Controllers/Config.phptests/Controllers/ConfigTest.php
| // Note: parse_tax() is not used here because these inputs use type="number" | ||
| // which always submits dot-decimal values regardless of locale. Using parse_tax() | ||
| // with a comma-decimal locale (e.g., de_DE) would incorrectly interpret the dot | ||
| // as a thousands separator, causing 5.5 to be saved as 5. | ||
| $batch_save_data = [ | ||
| 'default_tax_1_rate' => parse_tax(filter_var($default_tax_1_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)), | ||
| 'default_tax_1_rate' => (float) filter_var($default_tax_1_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), | ||
| 'default_tax_1_name' => $this->request->getPost('default_tax_1_name'), | ||
| 'default_tax_2_rate' => parse_tax(filter_var($default_tax_2_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)), | ||
| 'default_tax_2_rate' => (float) filter_var($default_tax_2_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION), |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In PHP 8.1, how does FILTER_SANITIZE_NUMBER_FLOAT behave with FILTER_FLAG_ALLOW_FRACTION only (without FILTER_FLAG_ALLOW_SCIENTIFIC), especially for inputs like "1e2", "5,5", and "5.5.5"?
💡 Result:
FILTER_SANITIZE_NUMBER_FLOAT in PHP 8.1 is a sanitization filter (not a validator): it removes characters and may return a string result rather than a validated float. The allow-fraction flag only permits the dot character; scientific notation is only permitted when FILTER_FLAG_ALLOW_SCIENTIFIC is used. With FILTER_FLAG_ALLOW_FRACTION only (and no FILTER_FLAG_ALLOW_SCIENTIFIC): 1) Input "1e2" - The 'e'/'E' characters are not allowed by this configuration, so they are stripped out, leaving "12" (and the output is not treated as scientific notation). 2) Input "5,5" - Since FILTER_FLAG_ALLOW_THOUSAND is not provided, commas are not allowed and will be stripped, leaving "55". 3) Input "5.5.5" - With FILTER_FLAG_ALLOW_FRACTION, dots are allowed. The filter allows dot(s) and does not enforce that there is only one decimal point, so multiple dots are preserved/handled as part of the sanitized string rather than being rejected as an invalid float. A related reported issue shows that when using FILTER_FLAG_ALLOW_FRACTION, multiple decimal points may lead to an invalid value being returned as “sanitized”, and the docs for FILTER_SANITIZE_NUMBER_FLOAT describe the behavior as character removal rather than strict numeric validation. What the behavior is based on (authoritative details): - FILTER_SANITIZE_NUMBER_FLOAT “sanitizes” by removing characters except digits, +/-, and optionally '.' (and only allows e/E when FILTER_FLAG_ALLOW_SCIENTIFIC is set) [1]. - The FILTER_FLAG_ALLOW_FRACTION flag “accept[s] dot (.) character”, and the allow-scientific flag separately “accept[s] … scientific notation by allowing the e and E characters” [1]. - Sanitizing filters do not validate the result (there’s an explicit discussion noting sanitizing vs validating, and that FILTER_SANITIZE_NUMBER_FLOAT is not intended to reject invalid numeric forms) [2]. Practical guidance: - If you need strict numeric parsing/validation (e.g., you want "1e2" to be accepted only when you allow scientific notation, and "5.5.5" to be rejected), use FILTER_VALIDATE_FLOAT instead of FILTER_SANITIZE_NUMBER_FLOAT, and combine it with appropriate flags for fraction/scientific/thousand as needed.
Citations:
- 1: https://www.php.net/filter.constants
- 2: https://bugs.php.net/bug.php?edit=2&id=40156
Validate tax-rate format before casting to float in app/Controllers/Config.php (lines 811-818)
FILTER_SANITIZE_NUMBER_FLOATis not a validator; withFILTER_FLAG_ALLOW_FRACTION(and noFILTER_FLAG_ALLOW_SCIENTIFIC), malformed inputs can be sanitized into different numbers (e.g.,1e2→12,5,5→55) and then persisted after the(float)cast.- Validate against the exact dot-decimal format you want to accept (or use
FILTER_VALIDATE_FLOATwith explicit flags) and return an error response on invalid input.
Proposed fix
- $batch_save_data = [
- 'default_tax_1_rate' => (float) filter_var($default_tax_1_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
+ $defaultTax1Rate = trim((string) $default_tax_1_rate);
+ $defaultTax2Rate = trim((string) $default_tax_2_rate);
+ $taxRatePattern = '/^-?(?:\d+|\d*\.\d+)(?:[eE][+\-]?\d+)?$/';
+
+ if (($defaultTax1Rate !== '' && !preg_match($taxRatePattern, $defaultTax1Rate))
+ || ($defaultTax2Rate !== '' && !preg_match($taxRatePattern, $defaultTax2Rate))) {
+ return $this->response->setJSON([
+ 'success' => false,
+ 'message' => lang('Config.saved_unsuccessfully')
+ ]);
+ }
+
+ $batch_save_data = [
+ 'default_tax_1_rate' => $defaultTax1Rate === '' ? 0.0 : (float) $defaultTax1Rate,
'default_tax_1_name' => $this->request->getPost('default_tax_1_name'),
- 'default_tax_2_rate' => (float) filter_var($default_tax_2_rate, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
+ 'default_tax_2_rate' => $defaultTax2Rate === '' ? 0.0 : (float) $defaultTax2Rate,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/Controllers/Config.php` around lines 811 - 818, The code is casting
sanitized-but-not-validated tax inputs to float (e.g., default_tax_1_rate,
default_tax_2_rate) which can accept malformed strings; instead, validate the
incoming tax-rate strings against the strict dot-decimal format before casting
and persist only if valid. Update the handler in Config (the method that builds
$batch_save_data) to run a validation step (e.g., regex /^\d+(\.\d+)?$/ or use
FILTER_VALIDATE_FLOAT with appropriate flags) on $default_tax_1_rate and
$default_tax_2_rate, return an error response if validation fails, and only then
use (float) cast or sanitized value for the batch_save_data assignment. Ensure
the check is applied to both default_tax_1_rate and default_tax_2_rate (and any
similar tax fields) and keep the existing comment about parse_tax() unchanged.
|
I've run into this same issue during the BS5 conversion. I was confident it wouldn't affect the SMTP number field since I've updated this in #4530, and I also assumed the tax rate would always come through in The main advantage of using Given that, my recommendation would be to revert the two fields in So, in 'type' => 'number',
'step' => 'any',
'min' => '0',
'max' => '100',to: 'type' => 'text', |
Good thoughts. I don't feel strongly about how we resolve it as long as comma-as-decimal-separator locales work correctly, we guard against attack vectors, and the solution doesn't introduce accuracy problems. CI4 does allow us to make our own custom callback validation functions. We are already doing this in the code elsewhere. We could make our own solution that accounts for both types of locales, then use it in place of number. My understanding is that there are three types of thousands separators: |
Resolution from PR #4555 review: Revert to text inputs for locale-specific tax rate fields. The type='number' attribute was added in commit 42ba39d, but it caused issues with locale-specific decimal separators. Browsers submit type='number' inputs as dot-decimal regardless of locale, which breaks comma-decimal locales. Solution: Revert to text inputs which use to_tax_decimals() for display and parse_tax() for saving, correctly handling locale-specific formatting. Changes: - tax_config.php: Remove type='number', step, min, max attributes - tax_config.php: Restore to_tax_decimals() for value display - Config.php: Restore parse_tax() for tax rate parsing - ConfigTest.php: Remove tests added for the type='number' approach Fixes #4553
Resolution: Revert type="number" for locale-specific tax rate fieldsBased on the review feedback, I've reverted the approach. The correct solution is to remove the Why this is the right approach:The root problem:
Why the previous PR approach was wrong:
The correct fix:
Changes in this commit:
This restores the original behavior that correctly handles locale-specific decimal separators. @objecttothis Could you review this revised approach? |
|
❌ Staging deployment failed Check the workflow logs for details. |
fix: tax rate inputs blank with comma-decimal locales (opensourcepos#4555)
Summary
Fixes #4553 - Tax rate input fields appear blank when locale uses comma as decimal separator (e.g.,
az_AZ,fr_FR,de_DE).Root Cause
Commit
42ba39d29addedtype='number'to tax rate input fields. Theto_tax_decimals()function formats values using locale-awareNumberFormatter, producing comma-decimal strings (e.g.,"18,00"). Browsers reject comma-decimal values in<input type="number">and display blank fields.Fix
Replace locale-formatted values with raw numeric values for tax rate inputs. PHP serializes floats with period decimals regardless of locale, so
(float)cast produces browser-compatible values.Regression Analysis
I analyzed all changes from commit
42ba39d29:tax_config.phptype='number'to_tax_decimals()email_config.phptype='number'$configvaluesbarcode_config.phptype='number'$configvaluesThe regression is isolated to
tax_config.phponly - all othertype='number'inputs use raw database values unaffected by locale.Testing
Tested with:
en_USlocale (period decimal) - works correctlyaz_AZlocale (comma decimal) - previously showed blank, now works correctlyThe
parse_tax()function on the save side already handles locale-aware parsing, so round-tripping works correctly.Summary by CodeRabbit