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.

Simplified the money changes and updated specs for exported strings

Damian Legawiec076049db9dab
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 3a1b02f8f8..37c524e26e 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -201,11 +201,8 @@ export interface LineItemUpdateParams {
export interface PaymentCreateParams {
payment_method_id: string
/**
- * Decimal amount. Accept `string` so callers can ship the merchant's
- * raw input verbatim — `Spree::LocalizedNumber.parse` handles
- * locale-aware decoding (comma decimals, grouped digits, etc.) on the
- * backend; `Number()`-coercing on the frontend would mangle inputs
- * like `"1.234,56"` into `NaN`.
+ * Decimal amount as a canonical string (`"1234.56"`: period decimal, no
+ * grouping). The API does not parse localized input; normalize it first.
*/
amount?: string | number
source_id?: string
@@ -1164,11 +1161,8 @@ export interface VariantOptionPair {
export interface VariantPrice {
currency: string
/**
- * Decimal amount. Accept `string` so callers ship the merchant's raw
- * input verbatim — `Spree::LocalizedNumber.parse` on the backend
- * handles locale-aware decoding (comma decimals, grouped digits, etc.);
- * `Number()`-coercing in the frontend mangles inputs like `"1.234,56"`
- * into `NaN`.
+ * Decimal amount as a canonical string (`"1234.56"`: period decimal, no
+ * grouping). The API does not parse localized input; normalize it first.
*/
amount: string | number
compare_at_amount?: string | number | null
diff --git a/packages/dashboard-core/src/products/normalize-money.ts b/packages/dashboard-core/src/products/normalize-money.ts
index 1e126f96b4..6f984291ad 100644
--- a/packages/dashboard-core/src/products/normalize-money.ts
+++ b/packages/dashboard-core/src/products/normalize-money.ts
@@ -4,8 +4,8 @@
// dashboard converts here, in the browser, and never relies on the server to
// parse comma-vs-period. See docs/plans/5.5-client-side-money-normalization.md.
//
-// The locale is the currency's display locale (its market locale, e.g. EUR →
-// `de`), so the same locale drives both display formatting and this parse.
+// The locale is the admin's own (`useMoneyLocale`), the same one the field is
+// displayed in, so a value reads back exactly as it was shown.
/**
* Derives a locale's decimal and group separators via `Intl`. `fr` groups with
diff --git a/packages/dashboard-core/src/products/product-bulk-price-editor.tsx b/packages/dashboard-core/src/products/product-bulk-price-editor.tsx
index 9112a8fab3..d8a0ec90dc 100644
--- a/packages/dashboard-core/src/products/product-bulk-price-editor.tsx
+++ b/packages/dashboard-core/src/products/product-bulk-price-editor.tsx
@@ -25,12 +25,10 @@ interface Props {
* in form state the same way. No server fetch, no edit-tracking map: the
* parent form's `isDirty` is the single source of truth for save gating.
*
- * Amounts are STRINGS, not numbers. The merchant's raw input flows straight
- * through to the API; the backend's `Spree::LocalizedNumber.parse` handles
- * locale-aware parsing (comma decimals, grouped digits, etc.) so the
- * frontend doesn't have to reimplement it. Frontend coercion via `Number()`
- * would silently mangle inputs like `"1.234,56"` into `NaN` and drop the
- * price entirely.
+ * Amounts are STRINGS, not numbers: canonical `"1234.56"` in form state and
+ * on the wire, normalized from the admin's own number format as each cell
+ * commits. `Number()` coercion would lose precision and turn `"1.234,56"`
+ * into `NaN`.
*/
export function ProductBulkPriceEditor({ form, currency, productName }: Props) {
const { t } = useTranslation()
diff --git a/packages/dashboard-core/src/products/product-form-mapping.ts b/packages/dashboard-core/src/products/product-form-mapping.ts
index 600bbe90b9..8f9ed88418 100644
--- a/packages/dashboard-core/src/products/product-form-mapping.ts
+++ b/packages/dashboard-core/src/products/product-form-mapping.ts
@@ -50,10 +50,9 @@ export function variantToFormValues(variant: PanelVariant, position: number): Va
.filter((p) => p.currency != null && p.price_list_id == null)
.map((p) => ({
currency: p.currency as string,
- // Keep amounts as the canonical decimal strings the API returns.
- // The bulk price editor displays them with the locale's decimal
- // separator and ships the raw user input unchanged on submit;
- // `Spree::LocalizedNumber.parse` handles locale-aware parsing.
+ // Keep amounts as the canonical decimal strings the API returns; the
+ // price editor shows them in the admin's number format and normalizes
+ // edits back before they reach the form.
amount: p.amount != null ? String(p.amount) : '',
compare_at_amount: p.compare_at_amount != null ? String(p.compare_at_amount) : null,
})),
diff --git a/packages/dashboard-core/src/products/product-schema.ts b/packages/dashboard-core/src/products/product-schema.ts
index 62ecea3287..4f258bf48a 100644
--- a/packages/dashboard-core/src/products/product-schema.ts
+++ b/packages/dashboard-core/src/products/product-schema.ts
@@ -33,11 +33,8 @@ export const variantOptionPairSchema = z.object({
export type VariantOptionPair = z.infer<typeof variantOptionPairSchema>
-// Form-side prices use raw STRING amounts (the merchant's typed input).
-// The backend's `Spree::LocalizedNumber.parse` handles locale-aware parsing
-// (comma decimals, grouped digits, etc.), so the frontend ships exactly what
-// the merchant typed — no `Number(...)` coercion that mangles `"1.234,56"`
-// into `NaN` and silently drops the price.
+// Form-side prices are canonical decimal STRINGS ("1234.56"), never numbers:
+// `Number(...)` coercion loses precision and turns `"1.234,56"` into `NaN`.
export const variantPriceFormSchema = z.object({
currency: z.string(),
amount: z.string(),
diff --git a/packages/dashboard/e2e/customers.spec.ts b/packages/dashboard/e2e/customers.spec.ts
index 5e99c665ec..003e704f83 100644
--- a/packages/dashboard/e2e/customers.spec.ts
+++ b/packages/dashboard/e2e/customers.spec.ts
@@ -231,9 +231,9 @@ test.describe('customers', () => {
await expect(page.getByText(/40\.00/).first()).toBeVisible({ timeout: 15_000 })
})
- // The Edit dialog locks currency to the credit's currency, so editing an EUR
- // credit must parse the new amount under the EUR market locale too. Issue in
- // EUR, then edit to another comma-decimal value and confirm it round-trips.
+ // Editing an EUR credit reads the new amount in the admin's own number
+ // format. Issue in EUR, then edit to a comma-decimal value and confirm it
+ // round-trips.
test('edits an EUR store credit with a localized amount', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)
diff --git a/packages/dashboard/e2e/helpers.ts b/packages/dashboard/e2e/helpers.ts
index b558544fda..cf8a93cd86 100644
--- a/packages/dashboard/e2e/helpers.ts
+++ b/packages/dashboard/e2e/helpers.ts
@@ -538,3 +538,39 @@ export async function createShippedOrder(page: Page, accessToken: string, quanti
return order as { id: string; number: string }
}
+
+/**
+ * Switches the shared admin account and this browser to a dashboard language
+ * together, and returns a function that hands the account back its previous
+ * language. Call it before `login`, and the returned function in `afterEach`.
+ *
+ * Both must agree: when they differ the auth provider reloads to bring the
+ * browser in line with the account, and a reload during the boot refresh
+ * spends the single-use cookie twice — the loser is bounced to `/`
+ * unauthenticated. Other specs leave the shared account on whatever language
+ * they last saved, so this cannot assume it is unset.
+ */
+export async function switchAdminLocale(page: Page, locale: string): Promise<() => Promise<void>> {
+ const authHeaders = async () => {
+ const creds = getCredentials()
+ const res = await page.request.post('/api/v3/admin/auth/login', {
+ data: { email: creds.admin_email, password: creds.admin_password },
+ })
+ const { token } = (await res.json()) as { token: string }
+ return { Authorization: `Bearer ${token}` }
+ }
+
+ await page.addInitScript((value) => localStorage.setItem('spree-admin-locale', value), locale)
+ const headers = await authHeaders()
+ const me = await page.request.get('/api/v3/admin/me', { headers })
+ const saved = ((await me.json()) as { user: { selected_locale: string | null } }).user
+ .selected_locale
+ await page.request.patch('/api/v3/admin/me', { headers, data: { selected_locale: locale } })
+
+ return async () => {
+ await page.request.patch('/api/v3/admin/me', {
+ headers: await authHeaders(),
+ data: { selected_locale: saved },
+ })
+ }
+}
diff --git a/packages/dashboard/e2e/products-prices-inventory.spec.ts b/packages/dashboard/e2e/products-prices-inventory.spec.ts
index 584a63b38d..9e9423729e 100644
--- a/packages/dashboard/e2e/products-prices-inventory.spec.ts
+++ b/packages/dashboard/e2e/products-prices-inventory.spec.ts
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { expect, type Locator, type Page, test } from '@playwright/test'
-import { getCredentials, gotoIndex, login } from './helpers'
+import { gotoIndex, login, switchAdminLocale } from './helpers'
import { E2E_DIR } from './paths'
import {
addOptionToVariants,
@@ -317,34 +317,10 @@ test.describe('product prices — number format', () => {
})
test.describe('in German', () => {
- let savedLocale: string | null = null
-
- async function authHeaders(page: Page) {
- const creds = getCredentials()
- const res = await page.request.post('/api/v3/admin/auth/login', {
- data: { email: creds.admin_email, password: creds.admin_password },
- })
- const { token } = (await res.json()) as { token: string }
- return { Authorization: `Bearer ${token}` }
- }
-
- // Switch the shared account and the browser together: when they disagree
- // the dashboard reloads mid-boot (see validation-messages.spec.ts).
- async function speakGerman(page: Page): Promise<void> {
- await page.addInitScript(() => localStorage.setItem('spree-admin-locale', 'de'))
- const headers = await authHeaders(page)
- const me = await page.request.get('/api/v3/admin/me', { headers })
- savedLocale = ((await me.json()) as { user: { selected_locale: string | null } }).user
- .selected_locale
- await page.request.patch('/api/v3/admin/me', { headers, data: { selected_locale: 'de' } })
- }
+ let restoreLocale: () => Promise<void> = async () => {}
- test.afterEach(async ({ page }) => {
- const headers = await authHeaders(page)
- await page.request.patch('/api/v3/admin/me', {
- headers,
- data: { selected_locale: savedLocale },
- })
+ test.afterEach(async () => {
+ await restoreLocale()
})
test('a German-speaking admin types every currency with a comma, and repeated saves keep it', async ({
@@ -353,7 +329,7 @@ test.describe('product prices — number format', () => {
const creds = await login(page)
const productName = `E2E Comma ${Date.now()}`
await createProduct(page, creds.store_id, productName)
- await speakGerman(page)
+ restoreLocale = await switchAdminLocale(page, 'de')
await page.reload()
const prices = germanPricesCard(page)
diff --git a/packages/dashboard/e2e/validation-messages.spec.ts b/packages/dashboard/e2e/validation-messages.spec.ts
index 643f9dccbb..725d8c77e2 100644
--- a/packages/dashboard/e2e/validation-messages.spec.ts
+++ b/packages/dashboard/e2e/validation-messages.spec.ts
@@ -1,5 +1,5 @@
import { expect, type Page, test } from '@playwright/test'
-import { getCredentials, gotoIndex, login } from './helpers'
+import { gotoIndex, login, switchAdminLocale } from './helpers'
// Validation copy reaches the merchant by two routes, and this spec pins both:
//
@@ -104,46 +104,16 @@ test.describe('validation messages', () => {
})
test.describe('in the admin’s own language', () => {
- // A German-speaking admin has German in two places: the browser remembers
- // the last choice, and the account carries it across devices. The store
- // itself stays English, so anything still reading the store's locale
- // would show through as English below.
- //
- // Both must agree. When they differ the auth provider reloads to bring
- // the browser in line with the account, and a reload during the boot
- // refresh spends the single-use cookie twice — the loser is bounced to
- // `/` unauthenticated and the test never reaches a store. Other specs in
- // the suite leave the shared account on whatever language they last
- // saved, so this cannot assume it is unset.
- let savedLocale: string | null = null
-
- const authHeaders = async (page: Page) => {
- const creds = getCredentials()
- const res = await page.request.post('/api/v3/admin/auth/login', {
- data: { email: creds.admin_email, password: creds.admin_password },
- })
- const { token } = (await res.json()) as { token: string }
- return { Authorization: `Bearer ${token}` }
- }
+ // A German-speaking admin; the store itself stays English, so anything
+ // still reading the store's locale would show through as English below.
+ let restoreLocale: () => Promise<void>
test.beforeEach(async ({ page }) => {
- await page.addInitScript(() => {
- localStorage.setItem('spree-admin-locale', 'de')
- })
- const headers = await authHeaders(page)
- const me = await page.request.get('/api/v3/admin/me', { headers })
- savedLocale = ((await me.json()) as { user: { selected_locale: string | null } }).user
- .selected_locale
- await page.request.patch('/api/v3/admin/me', { headers, data: { selected_locale: 'de' } })
+ restoreLocale = await switchAdminLocale(page, 'de')
})
- test.afterEach(async ({ page }) => {
- // Hand the shared account back the way it was found.
- const headers = await authHeaders(page)
- await page.request.patch('/api/v3/admin/me', {
- headers,
- data: { selected_locale: savedLocale },
- })
+ test.afterEach(async () => {
+ await restoreLocale()
})
test('a required field is explained in German', async ({ page }) => {
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
index bb2f08297c..1540f5f913 100644
--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
@@ -464,9 +464,9 @@ export function BulkPriceEditor({
// Typing a price into the trailing blank row is what creates the rung.
const promoted = promoteBlankRow(rowId)
const targetId = promoted ?? rowId
- // Normalized on commit, from the currency's market locale, so an edit
+ // Normalized on commit, from the admin's own number format, so an edit
// holds the same canonical `"1234.56"` the API returns. The cell then
- // shows exactly what Save will send (docs/plans/5.5-client-side-money-normalization.md).
+ // shows exactly what Save will send.
const canonical = normalizeMoneyInput(next, moneyLocale) || null
setEdits((prev) => {
diff --git a/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx b/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx
index 030dfe0583..0901ad9e90 100644
--- a/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx
+++ b/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx
@@ -1,12 +1,13 @@
import type { Customer } from '@spree/admin-sdk'
-import { useStore } from '@spree/dashboard-core'
+import { useMoneyLocale, useStore } from '@spree/dashboard-core'
import { Card, CardContent, RelativeTime } from '@spree/dashboard-ui'
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { formatAmount } from '../../../lib/delivery-method-summary'
export function CustomerLifetimeStatsCard({ customer }: { customer: Customer }) {
- const { t, i18n } = useTranslation()
+ const { t } = useTranslation()
+ const moneyLocale = useMoneyLocale()
const { defaultCurrency } = useStore()
const orders = customer.orders_count ?? 0
const totalSpent = Number(customer.total_spent ?? '0')
@@ -15,7 +16,7 @@ export function CustomerLifetimeStatsCard({ customer }: { customer: Customer })
// period-decimal figure into it mixes separators (`1.234,56 €` → `1234.57 €`).
const aovDisplay =
orders > 0 && totalSpent > 0
- ? formatAmount(totalSpent / orders, defaultCurrency, i18n.language)
+ ? formatAmount(totalSpent / orders, defaultCurrency, moneyLocale)
: '—'
return (
diff --git a/packages/dashboard/src/components/spree/orders/order-payments-card.tsx b/packages/dashboard/src/components/spree/orders/order-payments-card.tsx
index f3f99a68ad..ded531ec52 100644
--- a/packages/dashboard/src/components/spree/orders/order-payments-card.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-payments-card.tsx
@@ -285,8 +285,7 @@ function AddPaymentDialog({
: adminClient.orders.payments.create(orderId, {
payment_method_id: paymentMethodId,
...(sourceId ? { source_id: sourceId } : {}),
- // Ship raw merchant input; `Spree::LocalizedNumber.parse` on the
- // backend handles locale-aware decoding (comma decimals etc.).
+ // A number input, so the value is already canonical ("49.5").
...(amount ? { amount } : {}),
}),
)
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/gift-cards.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/gift-cards.tsx
index 870da02fdc..f2c501f695 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/gift-cards.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/gift-cards.tsx
@@ -179,9 +179,8 @@ function CreateGiftCardSheet({
resolver: zodResolver(giftCardCreateFormSchema) as any,
defaultValues: {
code: '',
- // Empty so the input shows its placeholder; the form's `amount` is
- // a STRING — the backend's `Spree::LocalizedNumber.parse` handles
- // locale-aware decoding so the SPA never coerces here.
+ // Empty so the input shows its placeholder; the form's `amount` is a
+ // STRING, never coerced to a number.
amount: '',
currency: defaultCurrency,
expires_at: '',
@@ -294,10 +293,8 @@ function EditGiftCardSheet({
prevGiftCardIdRef.current = giftCard.id
form.reset({
code: giftCard.code,
- // Keep amount as the canonical decimal string the API returns.
- // The merchant's edits flow straight through to the backend; only
- // `Spree::LocalizedNumber.parse` knows how to interpret locale-
- // specific input.
+ // Keep amount as the canonical decimal string the API returns; the
+ // number input hands edits back canonical too.
amount: giftCard.amount != null ? String(giftCard.amount) : '',
currency: giftCard.currency,
expires_at: giftCard.expires_at ?? '',
diff --git a/packages/dashboard/src/schemas/gift-card.ts b/packages/dashboard/src/schemas/gift-card.ts
index 1bd4164a12..68c1371d09 100644
--- a/packages/dashboard/src/schemas/gift-card.ts
+++ b/packages/dashboard/src/schemas/gift-card.ts
@@ -17,11 +17,9 @@ const prefixRequired = () => i18n.t('admin.pages.promotions.gift_cards.validatio
const currencyRequired = () =>
i18n.t('admin.pages.promotions.gift_cards.validation.currency_required')
-// Amounts stay as STRINGS — the merchant's raw input flows straight through
-// to the backend's `Spree::LocalizedNumber.parse`, which handles locale-aware
-// parsing (comma decimals, grouped digits, etc.). Coercing via `Number()`
-// silently mangles `"1.234,56"` into `NaN`. We still validate "is positive"
-// via a lightweight string regex so the form surface stays honest.
+// Amounts stay STRINGS, from a number input that always yields a canonical
+// value ("49.5"); `Number()` coercion would lose precision. "Is positive" is
+// still checked with a lightweight string regex.
const positiveAmountString = z.string().refine(
(s) => {
const n = Number(s.replace(',', '.'))
diff --git a/packages/dashboard/src/schemas/store-credit.ts b/packages/dashboard/src/schemas/store-credit.ts
index a144102956..1397c71feb 100644
--- a/packages/dashboard/src/schemas/store-credit.ts
+++ b/packages/dashboard/src/schemas/store-credit.ts
@@ -7,9 +7,9 @@ const amountPositive = () =>
field: i18n.t('admin.fields.store_credit.amount.label'),
})
-// Amount stays a string end-to-end (form Input value and wire payload). The
-// backend's LocalizedNumber.parse decodes it, so we never Number()-coerce —
-// that would mangle localized input like "1.234,56" to NaN. We only assert the
+// Amount stays a string end-to-end (form Input value and wire payload) and is
+// normalized from the admin's number format on submit, so we never
+// Number()-coerce — that would turn "1.234,56" into NaN. We only assert the
// shape here: at least one non-zero digit (so "0"/"0.00" are rejected as not
// strictly positive), no leading minus, digits/separators/spaces only.
// Authoritative parsing happens server-side.
diff --git a/spree/core/app/models/spree/adjusters/largest_remainder.rb b/spree/core/app/models/spree/adjusters/largest_remainder.rb
index 14195b7b23..3c99fe7f74 100644
--- a/spree/core/app/models/spree/adjusters/largest_remainder.rb
+++ b/spree/core/app/models/spree/adjusters/largest_remainder.rb
@@ -20,6 +20,18 @@ module Spree
end
shares
end
+
+ # Splits an amount across weights in the currency's minor units, so the
+ # shares are amounts that sum exactly to the one given.
+ #
+ # @param amount [BigDecimal]
+ # @param weights [Array<Numeric>] proportional bases (sum must be > 0)
+ # @param currency [String]
+ # @return [Array<BigDecimal>]
+ def apportion(amount, weights, currency)
+ units = Spree::Money::Rounding.to_minor_units(amount, currency)
+ largest_remainder_shares(units, weights).map { |share| Spree::Money::Rounding.from_minor_units(share, currency) }
+ end
end
end
end
diff --git a/spree/core/app/models/spree/adjusters/promotion.rb b/spree/core/app/models/spree/adjusters/promotion.rb
index 0fedc3810f..b633e24ed1 100644
--- a/spree/core/app/models/spree/adjusters/promotion.rb
+++ b/spree/core/app/models/spree/adjusters/promotion.rb
@@ -149,12 +149,10 @@ module Spree
bases_sum = bases.sum
return if bases_sum <= 0
- currency = order.currency
- total_units = Spree::Money::Rounding.to_minor_units([chosen[:amount].abs, bases_sum].min, currency)
- shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(total_units, bases)
+ shares = Spree::Adjusters::LargestRemainder.apportion([chosen[:amount].abs, bases_sum].min, bases, order.currency)
line_items.each_with_index do |line_item, index|
- amount = -Spree::Money::Rounding.from_minor_units(shares[index], currency)
+ amount = -shares[index]
next if amount.zero?
persist_discount(line_item, chosen, amount)
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index bb5bcef20b..39ba5bf3b7 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -895,6 +895,8 @@ module Spree
def capture_at_gateway(payment, amount)
return 0 if amount <= 0
+ # The Money gem's minor units, as gateways have always been sent from
+ # here; amounts that carry their currency replace this (money plan, A2).
units = ::Money.from_amount(amount, payment.currency).cents
result = Spree.payment_capture_workflow.call(payment: payment, amount: units)
raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
diff --git a/spree/core/app/models/spree/payment_method/store_credit.rb b/spree/core/app/models/spree/payment_method/store_credit.rb
index f0034e3025..0c67769240 100644
--- a/spree/core/app/models/spree/payment_method/store_credit.rb
+++ b/spree/core/app/models/spree/payment_method/store_credit.rb
@@ -26,7 +26,7 @@ module Spree
else
action = lambda do |store_credit|
store_credit.authorize(
- BigDecimal(amount_in_cents) / 100,
+ Spree::Money::Rounding.from_hundredths(amount_in_cents),
gateway_options[:currency],
action_originator: gateway_options[:originator]
)
@@ -38,7 +38,7 @@ module Spree
def capture(amount_in_cents, auth_code, gateway_options = {})
action = lambda do |store_credit|
store_credit.capture(
- BigDecimal(amount_in_cents) / 100,
+ Spree::Money::Rounding.from_hundredths(amount_in_cents),
auth_code,
gateway_options[:currency],
action_originator: gateway_options[:originator]
@@ -49,7 +49,7 @@ module Spree
def purchase(amount_in_cents, store_credit, gateway_options = {})
eligible_events = store_credit.store_credit_events.where(
- amount: BigDecimal(amount_in_cents) / 100,
+ amount: Spree::Money::Rounding.from_hundredths(amount_in_cents),
action: Spree::StoreCredit::ELIGIBLE_ACTION
)
event = eligible_events.detect do |eligible_event|
@@ -76,7 +76,7 @@ module Spree
currency = gateway_options[:currency] || store_credit.currency
originator = gateway_options[:originator]
- store_credit.credit(BigDecimal(amount_in_cents) / 100, auth_code, currency, action_originator: originator)
+ store_credit.credit(Spree::Money::Rounding.from_hundredths(amount_in_cents), auth_code, currency, action_originator: originator)
end
handle_action(action, :credit, auth_code)
diff --git a/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb b/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb
index bc8825ab2c..a443560de5 100644
--- a/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb
@@ -26,11 +26,8 @@ module Spree
private
- # The currency's own precision, a dot for the decimal mark and nothing
- # else — "18.00", never "$18.00", "18.0" or "18,00". Fixed rather than
- # localized because the file is read back by the import under the
- # store's locale, not the exporting admin's, and a comma written here
- # would re-import as a hundred times the price.
+ # A plain decimal ("18.00", never "$18.00" or "18,00"): the import reads
+ # the file back and accepts nothing else.
def amount_string(amount)
Spree::Money::Rounding.format(amount, price.currency, unit_price: true)
end
diff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
index bbcb9c0e6c..f8f9ef89c7 100644
--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb
+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
@@ -89,10 +89,9 @@ module Spree
def ensure_decimals!
DECIMAL_FIELDS.each do |column|
- text = attributes[column].to_s.strip
- next if text.empty? || text.match?(Spree::Money::Rounding::CANONICAL_DECIMAL)
-
- raise ArgumentError, I18n.t('spree.import_invalid_number', column: column, value: text)
+ Spree::Money::Rounding.parse_decimal(attributes[column])
+ rescue Spree::Money::InvalidFormat
+ raise ArgumentError, I18n.t('spree.import_invalid_number', column: column, value: attributes[column].to_s.strip)
end
end
diff --git a/spree/core/app/services/spree/orders/discounts/create.rb b/spree/core/app/services/spree/orders/discounts/create.rb
index 90fd2aac90..315885e266 100644
--- a/spree/core/app/services/spree/orders/discounts/create.rb
+++ b/spree/core/app/services/spree/orders/discounts/create.rb
@@ -52,11 +52,10 @@ module Spree
return [] if bases_sum <= 0
total = [amount_for(bases_sum, value, value_type, order.currency), bases_sum].min
- total_units = Spree::Money::Rounding.to_minor_units(total, order.currency)
- shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(total_units, bases)
+ shares = Spree::Adjusters::LargestRemainder.apportion(total, bases, order.currency)
line_items.each_with_index.filter_map do |line_item, index|
- amount = -Spree::Money::Rounding.from_minor_units(shares[index], order.currency)
+ amount = -shares[index]
next if amount.zero?
create_row(order, line_item, label, amount, value, value_type)
diff --git a/spree/core/app/workflows/spree/payments/capture.rb b/spree/core/app/workflows/spree/payments/capture.rb
index acda45f727..294592db89 100644
--- a/spree/core/app/workflows/spree/payments/capture.rb
+++ b/spree/core/app/workflows/spree/payments/capture.rb
@@ -86,6 +86,8 @@ module Spree
if Spree::Payment.where(id: payment.id, status: 'completed').exists?
already_captured = true
else
+ # Read in the Money gem's minor units, as before; the gateway amount
+ # carries its currency once A2 lands (money plan).
payment.capture_events.create!(amount: ::Money.new(@amount, payment.currency).to_d)
# Split before completing, so payment.completed publishes with
# the captured amount and the order recomputes from correct rows.
diff --git a/spree/core/lib/spree/money.rb b/spree/core/lib/spree/money.rb
index d499b081bb..237556c80d 100644
--- a/spree/core/lib/spree/money.rb
+++ b/spree/core/lib/spree/money.rb
@@ -192,6 +192,12 @@ module Spree
quantize(BigDecimal(amount.to_s) * 100, 0).to_i
end
+ # @param hundredths [Integer] as {#to_hundredths} returns
+ # @return [BigDecimal]
+ def from_hundredths(hundredths)
+ BigDecimal(hundredths) / 100
+ end
+
# Whether an amount is missing or zero. Text that is not a number is
# neither, so a malformed value is never mistaken for "nothing to pay".
#
diff --git a/spree/core/lib/tasks/money.rake b/spree/core/lib/tasks/money.rake
index a75e0c1017..6d844b0c5a 100644
--- a/spree/core/lib/tasks/money.rake
+++ b/spree/core/lib/tasks/money.rake
@@ -14,15 +14,17 @@ namespace :spree do
DESC
task audit_capture_events: :environment do
listed = 0
+ # The wrong records were written with the Money gem's exponent, which
+ # differs from ISO 4217 for a few currencies (forint, ariary).
+ codes = ::Money::Currency.all.reject { |currency| currency.exponent == 2 }.map(&:iso_code)
+ in_codes = [Spree::Order, Spree::Cart, Spree::OrderGroup].map { |owner| owner.arel_table[:currency].in(codes) }.reduce(:or)
- Spree::PaymentCaptureEvent.includes(payment: [:order, :cart, :order_group]).find_each do |event|
+ Spree::PaymentCaptureEvent.left_joins(payment: [:order, :cart, :order_group]).where(in_codes)
+ .includes(payment: [:order, :cart, :order_group]).find_each do |event|
payment = event.payment
next if payment.nil?
- # The wrong records were written with the Money gem's exponent, which
- # differs from ISO 4217 for a few currencies (forint, ariary).
- exponent = (::Money::Currency.find(payment.currency) || ::Money::Currency.find('USD')).exponent
- next if exponent == 2
+ exponent = ::Money::Currency.find(payment.currency).exponent
corrected = event.amount * (10**exponent) / 100
puts [
diff --git a/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb b/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb
index 32ede557a8..a804a160d3 100644
--- a/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb
+++ b/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb
@@ -8,6 +8,10 @@ module Spree
def total
10.0
end
+
+ def currency
+ 'USD'
+ end
end
end
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 00371e338b..1f32430b87 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -198,12 +198,6 @@ describe Spree::Product, type: :model do
end
describe '#price_in' do
- # Regression test for #1173
- it 'strips non-price characters' do
- product.default_variant.set_price('USD', '$10')
- expect(product.price_in('USD').amount).to eq(10.0)
- end
-
it 'shows the amount' do
product.default_variant.set_price('USD', 10.55)
expect(product.price_in('USD').display_amount.to_s).to eq('$10.55')
@@ -1407,14 +1401,14 @@ describe Spree::Product, type: :model do
expect(eur_default_variant[slug_idx]).to eq product.slug
expect(eur_default_variant[sku_idx]).to eq product.default_variant.sku
- expect(eur_default_variant[price_idx]).to eq 10.99
+ expect(eur_default_variant[price_idx]).to eq '10.99'
expect(eur_default_variant[currency_idx]).to eq 'EUR'
expect(eur_default_variant[name_idx]).to be_nil
expect(eur_variant[slug_idx]).to eq product.slug
expect(eur_variant[sku_idx]).to eq variant1.sku
- expect(eur_variant[price_idx]).to eq 52.99
- expect(eur_variant[compare_idx]).to eq 62.99
+ expect(eur_variant[price_idx]).to eq '52.99'
+ expect(eur_variant[compare_idx]).to eq '62.99'
expect(eur_variant[currency_idx]).to eq 'EUR'
expect(eur_variant[name_idx]).to be_nil
end
diff --git a/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb
index e0f5b2f13d..73d24ba2b7 100644
--- a/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb
@@ -11,21 +11,25 @@ RSpec.describe Spree::CSV::OrderLineItemPresenter do
describe '#call' do
subject { presenter.call }
+ def money(amount)
+ Spree::Money::Rounding.format(amount, order.currency)
+ end
+
it 'returns array with correct values' do
expect(subject[0]).to eq order.number
expect(subject[1]).to eq order.email
expect(subject[2]).to eq order.status
expect(subject[3]).to eq order.currency
- expect(subject[4]).to eq order.item_total.to_f
- expect(subject[5]).to eq order.shipment_total.to_f
- expect(subject[6]).to eq order.tax_total.to_f
+ expect(subject[4]).to eq money(order.item_total)
+ expect(subject[5]).to eq money(order.delivery_total)
+ expect(subject[6]).to eq money(order.tax_total)
expect(subject[7]).to eq order.included_tax_total.positive?
expect(subject[8]).to eq(order.promo_total.negative? || line_item.promo_total.negative?)
expect(subject[9]).to eq order.has_free_shipping?
- expect(subject[10]).to eq order.promo_total.abs
+ expect(subject[10]).to eq money(order.discount_total.abs)
expect(subject[11]).to eq order.promo_code
- expect(subject[12]).to eq order.payments.store_credits.sum(:amount).abs
- expect(subject[13]).to eq order.total.to_f
+ expect(subject[12]).to eq money(order.payments.store_credits.sum(:amount).abs)
+ expect(subject[13]).to eq money(order.total)
expect(subject[17]).to eq line_item.product_id
expect(subject[18]).to eq line_item.quantity
expect(subject[19]).to eq line_item.sku
diff --git a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
index b0cdfd5190..1a663b3715 100644
--- a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
+++ b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
@@ -443,10 +443,11 @@ module SpreeMeilisearch
# The bound as a plain decimal, or nil for anything else, so a malformed
# or enormous price never reaches the filter expression.
def price_filter_value(value)
- text = value.to_s.strip
- return unless text.length <= 32 && text.match?(Spree::Money::Rounding::CANONICAL_DECIMAL)
+ return if value.to_s.length > 32
- Spree::Money::Rounding.format_decimal(text)
+ Spree::Money::Rounding.format_decimal(Spree::Money::Rounding.parse_decimal(value.to_s))
+ rescue Spree::Money::InvalidFormat
+ nil
end
def format_custom_field_filter_value(value, numeric)