Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix price localization for product edit screen (#13647)
Damian Legawieca1899f2ec213
diff --git a/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js b/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.jsindex ac14913b09..d65381bd20 100644--- a/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js+++ b/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js@@ -33,7 +33,6 @@ export default class extends CheckboxSelectAll {prices: Object,currentCurrency: String,currencies: Array,- currencyFormats: Object,variantIds: Object,variantPrefixIds: Object,currentStockLocationId: String,@@ -72,19 +71,6 @@ export default class extends CheckboxSelectAll {}this.inventoryFormTarget = document.querySelector('.inventory-form');-- // Add form submit listener to normalize price inputs before submission- this.form = this.element.closest('form')- if (this.form) {- this.boundNormalizePricesBeforeSubmit = this.normalizePricesBeforeSubmit.bind(this)- this.form.addEventListener('submit', this.boundNormalizePricesBeforeSubmit)- }- }-- disconnect() {- if (this.form && this.boundNormalizePricesBeforeSubmit) {- this.form.removeEventListener('submit', this.boundNormalizePricesBeforeSubmit)- }}toggleQuantityTracked() {@@ -388,6 +374,16 @@ export default class extends CheckboxSelectAll {}}+ formatPrice(event) {+ const value = event.target.value+ if (value === '' || value === null) return++ const number = this.parseLocaleNumber(value)+ if (!Number.isFinite(number)) return++ event.target.value = this.formatNumber(number)+ }+replaceBlankWithZero(event) {if (event.target.value === '') {event.target.value = 0@@ -1101,13 +1097,13 @@ export default class extends CheckboxSelectAll {if (existingPrice) {return {...existingPrice,- amount: existingPrice.amount ? parseFloat(existingPrice.amount) : existingPrice.amount+ amount: existingPrice.amount ? this.parseLocaleNumber(existingPrice.amount) : existingPrice.amount}} else {const parentName = variantName.split('/')[0]const parentPrices = Object.entries(this.pricesValue).filter(([internalName, prices]) => internalName.startsWith(parentName) && prices[currency.toLowerCase()] !== undefined)- .map(([_key, prices]) => parseFloat(prices[currency.toLowerCase()].amount))+ .map(([_key, prices]) => this.parseLocaleNumber(prices[currency.toLowerCase()].amount)).sort((priceAmountA, priceAmountB) => priceAmountA - priceAmountB)return {@@ -1125,7 +1121,7 @@ export default class extends CheckboxSelectAll {...this.pricesValue[variantName],[currency.toLowerCase()]: {...existingPrice,- amount: parseFloat(newPrice)+ amount: this.parseLocaleNumber(newPrice)}}}@@ -1149,23 +1145,13 @@ export default class extends CheckboxSelectAll {}}- formatNumber(value, currency = null) {+ formatNumber(value) {if (value === null) return ''if (typeof value === 'string' && value.trim() === '') return ''const number = Number(value)if (!Number.isFinite(number)) return ''- // Use currency-specific decimal mark if available- const currencyCode = currency || this.currentCurrencyValue- const currencyFormat = this.currencyFormatsValue?.[currencyCode]-- if (currencyFormat?.decimal_mark) {- // Format with 2 decimal places and replace . with currency's decimal mark- return number.toFixed(2).replace('.', currencyFormat.decimal_mark)- }-- // Fallback to locale-based formattingreturn number.toLocaleString(this.localeValue, {minimumFractionDigits: 2,maximumFractionDigits: 2,@@ -1173,70 +1159,22 @@ export default class extends CheckboxSelectAll {})}- /**- * Normalizes a locale-formatted number string to standard decimal format- * e.g., "1.234,56" (German) -> "1234.56"- * e.g., "30,99" (Polish) -> "30.99"- * @param {string} value - The locale-formatted number string- * @returns {string} The normalized number string with "." as decimal separator- */- normalizeNumber(value) {- if (value === null || value === undefined) return ''-- let stringValue = String(value).trim()- if (stringValue === '') return ''-- // Detect the decimal separator by finding the last separator character- // This handles both "1,234.56" (en) and "1.234,56" (de/pl) formats- const lastComma = stringValue.lastIndexOf(',')- const lastDot = stringValue.lastIndexOf('.')-- let decimalSeparator = '.'- let thousandsSeparator = ','-- // If comma comes after dot, comma is the decimal separator (European format)- // Also treat comma as decimal if there's no dot and comma has 1-3 digits after it- if (lastComma > lastDot) {- decimalSeparator = ','- thousandsSeparator = '.'- } else if (lastDot === -1 && lastComma !== -1) {- // No dot present, check if comma looks like a decimal separator- // (has 1-3 digits after it, typical for currency)- const afterComma = stringValue.substring(lastComma + 1)- if (/^\d{1,3}$/.test(afterComma)) {- decimalSeparator = ','- thousandsSeparator = '.'- }- }+ parseLocaleNumber(value) {+ if (value === null || value === undefined) return NaN- // Remove thousands separators- stringValue = stringValue.split(thousandsSeparator).join('')+ let str = String(value).trim()+ if (str === '') return NaN- // Replace decimal separator with standard "."- if (decimalSeparator !== '.') {- stringValue = stringValue.replace(decimalSeparator, '.')- }+ const lastComma = str.lastIndexOf(',')+ const lastDot = str.lastIndexOf('.')- // Remove any non-numeric characters except "." and "-"- stringValue = stringValue.replace(/[^0-9.\-]/g, '')+ if (lastComma > lastDot) {+ str = str.replace(/\./g, '').replace(',', '.')+ } else if (lastDot === -1 && lastComma !== -1 && /^\d{1,3}$/.test(str.substring(lastComma + 1))) {+ str = str.replace(',', '.')+ }- return stringValue+ return parseFloat(str)}- /**- * Normalizes all price inputs in the variants form before submission- * @param {Event} event - The form submit event- */- normalizePricesBeforeSubmit(event) {- // Find all price inputs in the variants container- const priceInputs = this.variantsContainerTarget.querySelectorAll(- 'input[data-slot*="[prices_attributes]"][data-slot*="[amount]_input"]'- )-- priceInputs.forEach((input) => {- if (input.value) {- input.value = this.normalizeNumber(input.value)- }- })- }}diff --git a/spree/admin/app/views/spree/admin/products/form/_variants.html.erb b/spree/admin/app/views/spree/admin/products/form/_variants.html.erbindex 2c20a5f64b..c00aedc9f1 100644--- a/spree/admin/app/views/spree/admin/products/form/_variants.html.erb+++ b/spree/admin/app/views/spree/admin/products/form/_variants.html.erb@@ -5,21 +5,11 @@</div><% option_types_for_select = @option_types.map { |ot| [ot.presentation, ot.prefixed_id] } %><div class="card-body p-0">- <%# Build currency format info for JavaScript %>- <% currency_formats = supported_currencies.each_with_object({}) do |currency, hash|- currency_obj = ::Money::Currency.find(currency)- hash[currency.to_s] = {- decimal_mark: currency_obj.decimal_mark,- thousands_separator: currency_obj.thousands_separator,- symbol: currency_obj.symbol- }- end %><divdata-controller="variants-form"class="variants-form"data-action="product-form:toggle-quantity-tracked@window->variants-form#toggleQuantityTracked"data-variants-form-locale-value="<%= I18n.locale %>"- data-variants-form-currency-formats-value="<%= currency_formats.to_json %>"<% if @product.persisted? %> data-variants-form-product-id-value="<%= @product.slug %>" <% end %>data-variants-form-current-currency-value="<%= current_currency %>"data-variants-form-currencies-value="<%= supported_currencies.map(&:to_s).to_json %>"diff --git a/spree/admin/app/views/spree/admin/products/form/variants/_variant_template.html.erb b/spree/admin/app/views/spree/admin/products/form/variants/_variant_template.html.erbindex b2daf62f83..782343ee15 100644--- a/spree/admin/app/views/spree/admin/products/form/variants/_variant_template.html.erb+++ b/spree/admin/app/views/spree/admin/products/form/variants/_variant_template.html.erb@@ -18,7 +18,7 @@<div class="variants-table__body__cell column-price mr-2"><% supported_currencies.each_with_index do |currency, i| %><div class="input-group price-input-container <%= current_currency != currency ? 'hidden' : 'flex' %>" <%= !can_manage_prices ? 'readonly' : '' %>>- <%= text_field_tag "product[variants_attributes][prices_attributes][#{i}][amount]", '', class: 'border-0 focus:ring-0 focus:outline-none', data: { slot: "[prices_attributes][#{currency}][amount]_input", action: 'variants-form#updatePrice', currency: currency.to_s }, readonly: !can_manage_prices %>+ <%= text_field_tag "product[variants_attributes][prices_attributes][#{i}][amount]", '', class: 'border-0 focus:ring-0 focus:outline-none', data: { slot: "[prices_attributes][#{currency}][amount]_input", action: 'variants-form#updatePrice blur->variants-form#formatPrice', currency: currency.to_s }, readonly: !can_manage_prices %><span class="px-3"><%= currency_symbol(currency) %></span></div><%= hidden_field_tag "product[variants_attributes][prices_attributes][#{i}][currency]", currency, data: {slot: "[prices_attributes][#{currency}][currency]_input"} %>diff --git a/spree/admin/spec/features/spree/admin/products/products_spec.rb b/spree/admin/spec/features/spree/admin/products/products_spec.rbindex fffd5eccba..674bf0d308 100644--- a/spree/admin/spec/features/spree/admin/products/products_spec.rb+++ b/spree/admin/spec/features/spree/admin/products/products_spec.rb@@ -211,7 +211,12 @@ describe 'Products', type: :feature docontext 'with non-English locale using comma as decimal separator', js: true dobefore doI18n.backend.store_translations(:de, number: { currency: { format: { separator: ',', delimiter: '.' } } })- allow(store).to receive(:default_locale).and_return('de')+ @original_locale = I18n.locale+ I18n.locale = :de+ end++ after do+ I18n.locale = @original_localeendit 'correctly saves price without multiplying by 100' do@@ -223,6 +228,28 @@ describe 'Products', type: :feature doexpect(page).to have_content('successfully updated')expect(product.reload.price_in('USD').amount).to eq(123.0)end++ it 'correctly saves variant prices without multiplying by 100' do+ visit spree.edit_admin_product_path(product)++ # Add option - Color+ find('[data-variants-form-target="newOptionButtonLabel"]').click+ tom_select('Color', from: 'Option name', create: true)+ select_option_value('Black', index: 0, create: true)+ find('button', text: 'Done').click++ within('[data-test-id="product-variants-table"]') do+ within('[data-variant-name="Black"]') do+ within('.column-price') { find('input').set('29,99') }+ end+ end++ within('#page-header') { click_button 'Update' }+ expect(page).to have_content('successfully updated')++ variant = product.reload.variants.first+ expect(variant.price_in('USD').amount).to eq(29.99)+ endendit 'allows adding new options', js: true do