Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Introduce `spree_money_field`

Damian Legawiec37ff1249313c
diff --git a/admin/app/javascript/spree/admin/application.js b/admin/app/javascript/spree/admin/application.js
index 305ebb2ce0..f736fb2c52 100644
--- a/admin/app/javascript/spree/admin/application.js
+++ b/admin/app/javascript/spree/admin/application.js
@@ -61,6 +61,7 @@ import FontPickerController from 'spree/admin/controllers/font_picker_controller
import HighlightController from 'spree/admin/controllers/highlight_controller'
import ImportFormController from 'spree/admin/controllers/import_form_controller'
import MediaFormController from 'spree/admin/controllers/media_form_controller'
+import MoneyFieldController from 'spree/admin/controllers/money_field_controller'
import MultiInputController from 'spree/admin/controllers/multi_input_controller'
import MultiTomSelectController from 'spree/admin/controllers/multi_tom_select_controller'
import OrderBillingAddressController from 'spree/admin/controllers/order_billing_address_controller'
@@ -128,6 +129,7 @@ application.register('font-picker', FontPickerController)
application.register('highlight', HighlightController)
application.register('import-form', ImportFormController)
application.register('media-form', MediaFormController)
+application.register('money-field', MoneyFieldController)
application.register('multi-input', MultiInputController)
application.register('multi-tom-select', MultiTomSelectController)
application.register('nested-form', RailsNestedForm)
diff --git a/admin/app/javascript/spree/admin/controllers/money_field_controller.js b/admin/app/javascript/spree/admin/controllers/money_field_controller.js
new file mode 100644
index 0000000000..92b5e4f6d7
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/money_field_controller.js
@@ -0,0 +1,150 @@
+import { Controller } from '@hotwired/stimulus'
+
+/**
+ * MoneyFieldController
+ *
+ * A Stimulus controller for locale-aware money/price input fields.
+ * Handles formatting for display and normalizing values before form submission.
+ *
+ * Features:
+ * - Displays amounts in the user's locale format (e.g., "1.234,56" for German, "1,234.56" for English)
+ * - Normalizes values to standard decimal format (with "." as decimal separator) before form submission
+ * - Supports optional currency symbol display
+ *
+ * Usage:
+ * <input type="text"
+ * data-controller="money-field"
+ * data-money-field-locale-value="de"
+ * data-money-field-decimal-separator-value=","
+ * data-money-field-thousands-separator-value="."
+ * inputmode="decimal">
+ *
+ * Values:
+ * - locale: The locale to use for formatting (e.g., "en", "de", "pl")
+ * - decimalSeparator: The decimal separator for the locale (e.g., "." for en, "," for de/pl)
+ * - thousandsSeparator: The thousands separator for the locale (e.g., "," for en, "." for de/pl)
+ */
+export default class extends Controller {
+ static values = {
+ locale: { type: String, default: 'en' },
+ decimalSeparator: { type: String, default: '.' },
+ thousandsSeparator: { type: String, default: ',' }
+ }
+
+ connect() {
+ this.form = this.element.closest('form')
+
+ if (this.form) {
+ this.boundNormalizeBeforeSubmit = this.normalizeBeforeSubmit.bind(this)
+ this.form.addEventListener('submit', this.boundNormalizeBeforeSubmit)
+ }
+
+ // Format the initial value for display
+ this.formatForDisplay()
+ }
+
+ disconnect() {
+ if (this.form && this.boundNormalizeBeforeSubmit) {
+ this.form.removeEventListener('submit', this.boundNormalizeBeforeSubmit)
+ }
+ }
+
+ /**
+ * Called on blur to format the value for display
+ */
+ format() {
+ this.formatForDisplay()
+ }
+
+ /**
+ * Formats the current value for display in the user's locale format
+ */
+ formatForDisplay() {
+ const normalizedValue = this.normalizeValue(this.element.value)
+ if (normalizedValue === '' || normalizedValue === null) {
+ return
+ }
+
+ const number = parseFloat(normalizedValue)
+ if (!Number.isFinite(number)) {
+ return
+ }
+
+ this.element.value = this.formatNumber(number)
+ }
+
+ /**
+ * Formats a number for display using the configured locale
+ * @param {number} number - The number to format
+ * @returns {string} The formatted number string
+ */
+ formatNumber(number) {
+ return number.toLocaleString(this.localeValue, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ useGrouping: false // Disable thousands separator for cleaner input
+ })
+ }
+
+ /**
+ * Normalizes the input value to standard decimal format (with "." as decimal separator)
+ * Automatically detects the format based on the input pattern.
+ * @param {string} value - The value to normalize
+ * @returns {string} The normalized value
+ */
+ normalizeValue(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-2 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 = '.'
+ }
+ }
+
+ // Remove thousands separators
+ stringValue = stringValue.split(thousandsSeparator).join('')
+
+ // Replace decimal separator with standard "."
+ if (decimalSeparator !== '.') {
+ stringValue = stringValue.replace(decimalSeparator, '.')
+ }
+
+ // Remove any non-numeric characters except "." and "-"
+ stringValue = stringValue.replace(/[^0-9.\-]/g, '')
+
+ return stringValue
+ }
+
+ /**
+ * Normalizes the value before form submission
+ * @param {Event} event - The form submit event
+ */
+ normalizeBeforeSubmit(event) {
+ const normalizedValue = this.normalizeValue(this.element.value)
+ this.element.value = normalizedValue
+ }
+}
diff --git a/admin/app/javascript/spree/admin/controllers/variants_form_controller.js b/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
index c6318fc575..0b981b7f1e 100644
--- a/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
+++ b/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
@@ -33,6 +33,7 @@ export default class extends CheckboxSelectAll {
prices: Object,
currentCurrency: String,
currencies: Array,
+ currencyFormats: Object,
variantIds: Object,
currentStockLocationId: String,
stockLocations: Array,
@@ -70,6 +71,19 @@ 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() {
@@ -416,7 +430,7 @@ export default class extends CheckboxSelectAll {
pricesVariation.delete(null)
if (pricesVariation.size === 0) {
- parentPriceEl.value = this.formatNumber(this.priceForVariant(variantName, currency).amount)
+ parentPriceEl.value = this.formatNumber(this.priceForVariant(variantName, currency).amount, currency)
parentPriceEl.placeholder = ''
return
}
@@ -425,9 +439,9 @@ export default class extends CheckboxSelectAll {
if (minPrice !== maxPrice) {
parentPriceEl.value = null
- parentPriceEl.placeholder = `${this.formatNumber(minPrice)} - ${this.formatNumber(maxPrice)}`
+ parentPriceEl.placeholder = `${this.formatNumber(minPrice, currency)} - ${this.formatNumber(maxPrice, currency)}`
} else {
- parentPriceEl.value = this.formatNumber(minPrice)
+ parentPriceEl.value = this.formatNumber(minPrice, currency)
parentPriceEl.placeholder = ''
}
}
@@ -713,7 +727,7 @@ export default class extends CheckboxSelectAll {
}
const existingPrice = this.priceForVariant(internalName, currency)
- priceInput.value = this.formatNumber(existingPrice.amount)
+ priceInput.value = this.formatNumber(existingPrice.amount, currency)
currencyInput.value = currency
if (existingPrice.id) {
idInput.value = existingPrice.id
@@ -1134,13 +1148,94 @@ export default class extends CheckboxSelectAll {
}
}
- formatNumber(value) {
+ formatNumber(value, currency = null) {
if (value === null) return ''
if (typeof value === 'string' && value.trim() === '') return ''
const number = Number(value)
if (!Number.isFinite(number)) return ''
- return number.toLocaleString(this.localeValue)
+ // 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 formatting
+ return number.toLocaleString(this.localeValue, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ useGrouping: false
+ })
+ }
+
+ /**
+ * 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 = '.'
+ }
+ }
+
+ // Remove thousands separators
+ stringValue = stringValue.split(thousandsSeparator).join('')
+
+ // Replace decimal separator with standard "."
+ if (decimalSeparator !== '.') {
+ stringValue = stringValue.replace(decimalSeparator, '.')
+ }
+
+ // Remove any non-numeric characters except "." and "-"
+ stringValue = stringValue.replace(/[^0-9.\-]/g, '')
+
+ return stringValue
+ }
+
+ /**
+ * 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/admin/app/models/spree/admin/form_builder.rb b/admin/app/models/spree/admin/form_builder.rb
index 3bb5100f0d..64272c6cd8 100644
--- a/admin/app/models/spree/admin/form_builder.rb
+++ b/admin/app/models/spree/admin/form_builder.rb
@@ -68,6 +68,68 @@ module Spree
end
end
+ # Create a money/currency field with Spree form styling and locale-aware formatting
+ #
+ # This field displays amounts in the user's locale format (e.g., "1.234,56" for German)
+ # and normalizes values to standard decimal format before form submission.
+ #
+ # @param method [Symbol] the field name
+ # @param options [Hash] field options including:
+ # - :currency [String] the currency code (e.g., 'USD', 'EUR', 'PLN') - used for symbol display
+ # - :value [BigDecimal, Float, String] the value to display (will be formatted for locale)
+ # - other options from {#spree_text_field}
+ # @return [String] HTML string containing the complete form group with money field
+ def spree_money_field(method, options = {})
+ currency = options.delete(:currency)
+ prepend = options.delete(:prepend)
+ append = options.delete(:append)
+
+ # Get currency object for formatting
+ currency_obj = currency.present? ? ::Money::Currency.find(currency) : nil
+
+ # Use currency symbol as append if currency is provided and no append specified
+ if currency_obj.present? && append.nil?
+ append = currency_obj.symbol
+ end
+
+ # Get decimal/thousands separators from currency or fall back to I18n locale
+ locale = I18n.locale
+ if currency_obj.present?
+ decimal_separator = currency_obj.decimal_mark
+ thousands_separator = currency_obj.thousands_separator
+ else
+ decimal_separator = I18n.t(:'number.currency.format.separator', default: '.')
+ thousands_separator = I18n.t(:'number.currency.format.delimiter', default: ',')
+ end
+
+ # Format the value for display if present
+ if options[:value].present?
+ options[:value] = format_money_value(options[:value], decimal_separator)
+ elsif @object.respond_to?(method) && @object.send(method).present?
+ options[:value] = format_money_value(@object.send(method), decimal_separator)
+ end
+
+ options[:class] ||= 'form-input'
+ options[:inputmode] = 'decimal'
+ options[:data] ||= {}
+ options[:data][:controller] = 'money-field'
+ options[:data][:money_field_locale_value] = locale
+ options[:data][:money_field_decimal_separator_value] = decimal_separator
+ options[:data][:money_field_thousands_separator_value] = thousands_separator
+ options[:data][:action] = 'blur->money-field#format'
+
+ if prepend.present? || append.present?
+ options[:class] = 'border-0 focus:ring-0 focus:outline-none text-base grow'
+ options[:class] += ' pl-0' if prepend.present?
+ end
+
+ @template.content_tag(:div, class: 'form-group') do
+ spree_label(method, options) +
+ wrap_with_input_group(@template.text_field(@object_name, method, objectify_options(options)), prepend, append) +
+ @template.error_message_on(@object_name, method) + spree_field_help(method, options.merge(class: 'form-text mt-2'))
+ end
+ end
+
# Create an email field with Spree form styling
#
# @param method [Symbol] the field name
@@ -301,6 +363,18 @@ module Spree
@template.raw(translated_label + required_label + help_bubble)
end
+ # Format a money value for display using the given decimal separator
+ #
+ # @param value [BigDecimal, Float, String, nil] the value to format
+ # @param decimal_separator [String] the decimal separator to use (e.g., '.' or ',')
+ # @return [String] the formatted value
+ def format_money_value(value, decimal_separator = '.')
+ return '' if value.blank?
+
+ number = value.to_d
+ format('%<amount>.2f', amount: number).tr('.', decimal_separator)
+ end
+
# Wrap a field with an input group if prepend or append is specified
#
# @param field_html [String] the HTML for the field
diff --git a/admin/app/views/spree/admin/gift_card_batches/_form.html.erb b/admin/app/views/spree/admin/gift_card_batches/_form.html.erb
index f3bcc04265..0065ef551b 100644
--- a/admin/app/views/spree/admin/gift_card_batches/_form.html.erb
+++ b/admin/app/views/spree/admin/gift_card_batches/_form.html.erb
@@ -7,7 +7,7 @@
<div class="card-body">
<%= f.spree_text_field :prefix, disabled: f.object.persisted?, label: Spree.t('admin.gift_card_batches.prefix'), autofocus: true %>
- <%= f.spree_number_field :amount, required: true, disabled: f.object.persisted? %>
+ <%= f.spree_money_field :amount, currency: f.object.currency, required: true, disabled: f.object.persisted? %>
<%= f.spree_select :currency, options_for_select(supported_currency_options, f.object.currency), { label: Spree.t(:currency), autocomplete: true } %>
<%= f.spree_number_field :codes_count, required: true, min: 1, max: Spree::Config[:gift_card_batch_limit], label: Spree.t('admin.gift_card_batches.codes_count') %>
<%= f.spree_date_field :expires_at, disabled: f.object.persisted?, help: 'Gift cards will expire after this date.' %>
diff --git a/admin/app/views/spree/admin/gift_cards/_form.html.erb b/admin/app/views/spree/admin/gift_cards/_form.html.erb
index 4d001f7028..c0b926c5f6 100644
--- a/admin/app/views/spree/admin/gift_cards/_form.html.erb
+++ b/admin/app/views/spree/admin/gift_cards/_form.html.erb
@@ -4,7 +4,7 @@
<%= f.spree_text_field :code, required: true, help_bubble: Spree.t('admin.gift_cards.code_help_text'), autofocus: true %>
<% end %>
- <%= f.spree_number_field :amount, required: true %>
+ <%= f.spree_money_field :amount, currency: f.object.currency, required: true %>
<%= f.spree_select :currency, options_for_select(supported_currency_options, f.object.currency), { label: Spree.t(:currency), autocomplete: true }, { disabled: f.object.persisted? } %>
<div class="form-group">
diff --git a/admin/app/views/spree/admin/orders/adjustments/_form.html.erb b/admin/app/views/spree/admin/orders/adjustments/_form.html.erb
index b4b6b21845..e6abbb9b03 100644
--- a/admin/app/views/spree/admin/orders/adjustments/_form.html.erb
+++ b/admin/app/views/spree/admin/orders/adjustments/_form.html.erb
@@ -1,6 +1,6 @@
<%= f.spree_text_field :label, autofocus: true %>
-<%= f.spree_number_field :amount,
- required: true,
- step: 0.01,
- prepend: @order.currency,
- help: Spree.t(:adjustment_amount_help) %>
\ No newline at end of file
+<%= f.spree_money_field :amount,
+ required: true,
+ currency: @order.currency,
+ prepend: @order.currency,
+ help: Spree.t(:adjustment_amount_help) %>
\ No newline at end of file
diff --git a/admin/app/views/spree/admin/payments/new.html.erb b/admin/app/views/spree/admin/payments/new.html.erb
index dd0dcad079..bbfb95fc5a 100644
--- a/admin/app/views/spree/admin/payments/new.html.erb
+++ b/admin/app/views/spree/admin/payments/new.html.erb
@@ -10,12 +10,10 @@
<h5 class="card-title"><%= Spree.t(:new_payment) %></h5>
</div>
<div class="card-body">
- <%= f.spree_number_field :amount,
+ <%= f.spree_money_field :amount,
value: @payment.max_amount,
- max: @payment.max_amount,
- step: '.01',
- required: true,
- append: currency_symbol(@order.currency) %>
+ currency: @order.currency,
+ required: true %>
<%= f.label :payment_method_id, Spree.t(:payment_method) %>
<ul class="list-group mb-6">
diff --git a/admin/app/views/spree/admin/products/form/_variants.html.erb b/admin/app/views/spree/admin/products/form/_variants.html.erb
index fcc9f21dd8..6c501bb4a1 100644
--- a/admin/app/views/spree/admin/products/form/_variants.html.erb
+++ b/admin/app/views/spree/admin/products/form/_variants.html.erb
@@ -5,11 +5,21 @@
</div>
<% option_types_for_select = @option_types.pluck(:presentation, :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 %>
<div
data-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/admin/app/views/spree/admin/refunds/_form.html.erb b/admin/app/views/spree/admin/refunds/_form.html.erb
index 055ea3a742..7f5ed879a3 100644
--- a/admin/app/views/spree/admin/refunds/_form.html.erb
+++ b/admin/app/views/spree/admin/refunds/_form.html.erb
@@ -1,5 +1,5 @@
<% if f.object.new_record? %>
- <%= f.spree_text_field :amount, label: Spree.t(:amount), append: currency_symbol(@order.currency), required: true %>
+ <%= f.spree_money_field :amount, label: Spree.t(:amount), currency: @order.currency, required: true %>
<% end %>
<%= f.spree_collection_select :refund_reason_id, refund_reasons, :id, :name, { include_blank: true, label: Spree.t(:reason), required: true } %>
\ No newline at end of file
diff --git a/admin/app/views/spree/admin/store_credits/_form.html.erb b/admin/app/views/spree/admin/store_credits/_form.html.erb
index 71225ef6f8..4b7aef1a8a 100644
--- a/admin/app/views/spree/admin/store_credits/_form.html.erb
+++ b/admin/app/views/spree/admin/store_credits/_form.html.erb
@@ -1,3 +1,3 @@
-<%= f.spree_number_field :amount, label: Spree.t(:amount), min: 0.01, step: 0.01, required: true, disabled: !f.object.editable? %>
+<%= f.spree_money_field :amount, label: Spree.t(:amount), currency: f.object.currency, required: true, disabled: !f.object.editable? %>
<%= f.spree_select :currency, options_for_select(supported_currency_options, f.object.currency), { label: Spree.t(:currency), autocomplete: true }, { data: { enable_button_target: 'input', store_form_target: 'currency' } } %>
<%= f.spree_text_area :memo %>
diff --git a/admin/app/views/spree/admin/variants/form/_pricing.html.erb b/admin/app/views/spree/admin/variants/form/_pricing.html.erb
index 7bdd4c7104..e93a8ec97d 100644
--- a/admin/app/views/spree/admin/variants/form/_pricing.html.erb
+++ b/admin/app/views/spree/admin/variants/form/_pricing.html.erb
@@ -30,16 +30,16 @@
<tr>
<td><%= price_form.object.currency %></td>
<td>
- <%= price_form.spree_text_field :amount, disabled: !can?(:manage, price_form.object),
- value: price_form.object.amount.present? ? Spree::Money.new(price_form.object.amount, currency: price_form.object.currency, symbol: '').to_s : '',
- append: currency_symbol(price_form.object.currency),
- label: false %>
+ <%= price_form.spree_money_field :amount,
+ disabled: !can?(:manage, price_form.object),
+ currency: price_form.object.currency,
+ label: false %>
</td>
<td>
- <%= price_form.spree_text_field :compare_at_amount, disabled: !can?(:manage, price_form.object),
- value: price_form.object.compare_at_amount.present? ? Spree::Money.new(price_form.object.compare_at_amount, currency: price_form.object.currency, symbol: '').to_s : '',
- append: currency_symbol(price_form.object.currency),
- label: false %>
+ <%= price_form.spree_money_field :compare_at_amount,
+ disabled: !can?(:manage, price_form.object),
+ currency: price_form.object.currency,
+ label: false %>
</td>
</tr>
<% end %>
diff --git a/admin/spec/features/spree/admin/products/products_spec.rb b/admin/spec/features/spree/admin/products/products_spec.rb
index 1def75e3f2..a28b21a8b0 100644
--- a/admin/spec/features/spree/admin/products/products_spec.rb
+++ b/admin/spec/features/spree/admin/products/products_spec.rb
@@ -294,32 +294,32 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="Black/Small"]') do
- within('.column-price') { expect(page).to have_field(with: 10) }
+ within('.column-price') { expect(page).to have_field(with: '10.00') }
within('.column-quantity') { expect(page).to have_field(with: 100) }
end
within('[data-variant-name="Black/Medium"]') do
- within('.column-price') { expect(page).to have_field(with: 11) }
+ within('.column-price') { expect(page).to have_field(with: '11.00') }
within('.column-quantity') { expect(page).to have_field(with: 110) }
end
within('[data-variant-name="Black/Large"]') do
- within('.column-price') { expect(page).to have_field(with: 12) }
+ within('.column-price') { expect(page).to have_field(with: '12.00') }
within('.column-quantity') { expect(page).to have_field(with: 120) }
end
within('[data-variant-name="White/Small"]') do
- within('.column-price') { expect(page).to have_field(with: 20) }
+ within('.column-price') { expect(page).to have_field(with: '20.00') }
within('.column-quantity') { expect(page).to have_field(with: 200) }
end
within('[data-variant-name="White/Medium"]') do
- within('.column-price') { expect(page).to have_field(with: 21) }
+ within('.column-price') { expect(page).to have_field(with: '21.00') }
within('.column-quantity') { expect(page).to have_field(with: 210) }
end
within('[data-variant-name="White/Large"]') do
- within('.column-price') { expect(page).to have_field(with: 22) }
+ within('.column-price') { expect(page).to have_field(with: '22.00') }
within('.column-quantity') { expect(page).to have_field(with: 220) }
end
end
@@ -711,17 +711,17 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="Small"]') do
- within('.column-price') { expect(page).to have_field(with: 10) }
+ within('.column-price') { expect(page).to have_field(with: '10.00') }
within('.column-quantity') { expect(page).to have_field(with: 100) }
end
within('[data-variant-name="Medium"]') do
- within('.column-price') { expect(page).to have_field(with: 11) }
+ within('.column-price') { expect(page).to have_field(with: '11.00') }
within('.column-quantity') { expect(page).to have_field(with: 110) }
end
within('[data-variant-name="Large"]') do
- within('.column-price') { expect(page).to have_field(with: 12) }
+ within('.column-price') { expect(page).to have_field(with: '12.00') }
within('.column-quantity') { expect(page).to have_field(with: 120) }
end
end
@@ -747,12 +747,12 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="Medium"]') do
- within('.column-price') { expect(page).to have_field(with: 11) }
+ within('.column-price') { expect(page).to have_field(with: '11.00') }
within('.column-quantity') { expect(page).to have_field(with: 110) }
end
within('[data-variant-name="Large"]') do
- within('.column-price') { expect(page).to have_field(with: 12) }
+ within('.column-price') { expect(page).to have_field(with: '12.00') }
within('.column-quantity') { expect(page).to have_field(with: 120) }
end
end
@@ -889,12 +889,12 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="White/Cotton"]') do
- within('.column-price') { expect(page).to have_field(with: 20) }
+ within('.column-price') { expect(page).to have_field(with: '20.00') }
within('.column-quantity') { expect(page).to have_field(with: 200) }
end
within('[data-variant-name="White/Polyester"]') do
- within('.column-price') { expect(page).to have_field(with: 21) }
+ within('.column-price') { expect(page).to have_field(with: '21.00') }
within('.column-quantity') { expect(page).to have_field(with: 210) }
end
end
@@ -1037,11 +1037,11 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="Black"]') do
- within('.column-price') { expect(page).to have_field(with: 10) }
+ within('.column-price') { expect(page).to have_field(with: '10.00') }
end
within('[data-variant-name="White"]') do
- within('.column-price') { expect(page).to have_field(with: 11) }
+ within('.column-price') { expect(page).to have_field(with: '11.00') }
end
end
@@ -1053,11 +1053,11 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="Black/Extra Large"]') do
- within('.column-price') { expect(page).to have_field(with: 10) }
+ within('.column-price') { expect(page).to have_field(with: '10.00') }
end
within('[data-variant-name="White/Extra Large"]') do
- within('.column-price') { expect(page).to have_field(with: 11) }
+ within('.column-price') { expect(page).to have_field(with: '11.00') }
end
end
@@ -1068,11 +1068,11 @@ describe 'Products', type: :feature do
within('[data-test-id="product-variants-table"]') do
within('[data-variant-name="Black/Extra Large"]') do
- within('.column-price') { expect(page).to have_field(with: 10) }
+ within('.column-price') { expect(page).to have_field(with: '10.00') }
end
within('[data-variant-name="White/Extra Large"]') do
- within('.column-price') { expect(page).to have_field(with: 11) }
+ within('.column-price') { expect(page).to have_field(with: '11.00') }
end
end
diff --git a/admin/spec/models/spree/admin/form_builder_spec.rb b/admin/spec/models/spree/admin/form_builder_spec.rb
new file mode 100644
index 0000000000..1c07cc63b5
--- /dev/null
+++ b/admin/spec/models/spree/admin/form_builder_spec.rb
@@ -0,0 +1,100 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::FormBuilder do
+ let(:template) { ActionView::Base.new(ActionView::LookupContext.new([]), {}, nil) }
+ let(:object) { Spree::Price.new(amount: 129.99, currency: 'USD') }
+ let(:builder) { described_class.new(:price, object, template, {}) }
+
+ before do
+ allow(template).to receive(:error_message_on).and_return('')
+ end
+
+ describe '#spree_money_field' do
+ context 'with default locale (en)' do
+ before do
+ I18n.locale = :en
+ I18n.backend.store_translations(:en, number: { currency: { format: { separator: '.', delimiter: ',' } } })
+ end
+
+ it 'renders a text field with money-field controller' do
+ result = builder.spree_money_field(:amount, currency: 'USD', label: false)
+
+ expect(result).to include('data-controller="money-field"')
+ expect(result).to include('data-money-field-locale-value="en"')
+ expect(result).to include('data-money-field-decimal-separator-value="."')
+ expect(result).to include('data-money-field-thousands-separator-value=","')
+ end
+
+ it 'formats the value with 2 decimal places' do
+ result = builder.spree_money_field(:amount, currency: 'USD', label: false)
+
+ expect(result).to include('value="129.99"')
+ end
+
+ it 'includes the currency symbol as append' do
+ result = builder.spree_money_field(:amount, currency: 'USD', label: false)
+
+ expect(result).to include('$')
+ end
+
+ it 'sets inputmode to decimal' do
+ result = builder.spree_money_field(:amount, currency: 'USD', label: false)
+
+ expect(result).to include('inputmode="decimal"')
+ end
+
+ it 'includes blur action for formatting' do
+ result = builder.spree_money_field(:amount, currency: 'USD', label: false)
+
+ expect(result).to include('blur-&gt;money-field#format')
+ end
+ end
+
+ context 'with PLN currency' do
+ it 'uses currency decimal mark (comma for PLN)' do
+ result = builder.spree_money_field(:amount, currency: 'PLN', label: false)
+
+ # PLN uses comma as decimal mark per ISO standard
+ expect(result).to include('data-money-field-decimal-separator-value=","')
+ expect(result).to include('value="129,99"')
+ end
+ end
+
+ context 'with EUR currency' do
+ it 'uses currency decimal mark (comma for EUR)' do
+ result = builder.spree_money_field(:amount, currency: 'EUR', label: false)
+
+ # EUR uses comma as decimal mark per ISO standard
+ expect(result).to include('data-money-field-decimal-separator-value=","')
+ expect(result).to include('data-money-field-thousands-separator-value="."')
+ end
+ end
+
+ context 'with nil amount' do
+ let(:object) { Spree::Price.new(amount: nil, currency: 'USD') }
+
+ it 'does not include a formatted value' do
+ result = builder.spree_money_field(:amount, currency: 'USD', label: false)
+
+ # Should not include a formatted decimal value like "129.99"
+ expect(result).not_to match(/value="\d+\.\d+"/)
+ end
+ end
+
+ context 'with custom append' do
+ it 'uses custom append instead of currency symbol' do
+ result = builder.spree_money_field(:amount, currency: 'USD', append: 'custom', label: false)
+
+ expect(result).to include('custom')
+ end
+ end
+
+ context 'with disabled option' do
+ it 'renders disabled field' do
+ result = builder.spree_money_field(:amount, currency: 'USD', disabled: true, label: false)
+
+ expect(result).to include('disabled="disabled"')
+ end
+ end
+ end
+end
diff --git a/core/config/locales/en.yml b/core/config/locales/en.yml
index e48403ccef..cc2a548cad 100644
--- a/core/config/locales/en.yml
+++ b/core/config/locales/en.yml
@@ -593,6 +593,7 @@ en:
number:
currency:
format:
+ delimiter: ","
separator: "."
percentage:
format: