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.

19.1 KB
Raw Blame

Exchange Rates

Status: Draft Target: Spree 6.1 Depends on: 6.0-integrations-admin.md (credential surface), 6.0-multi-vendor-marketplace.md (the commission-VAT case that constrains this) Author: Damian + Claude Last updated: 2026-08-17 Tracking: Linear V-3614 · GitHub spree/spree#14610

Summary

Spree stores one explicit amount per currency everywhere money is configured — product prices, price-list overrides, delivery calculators, commission rates — and never converts between them. That is the right answer for what gets charged, and this plan does not change it. It solves the other half: a merchant supporting six currencies types every amount six times, by hand, with no help.

This adds an ExchangeRateProvider that fills fields in, and nothing else. A merchant types 50 PLN, the dashboard offers "≈ 12.50 USD, ≈ 11.60 EUR" as editable suggestions, they adjust 12.50 to 12.99 because round numbers sell, and what is persisted is a plain number they own. The rate feed is never consulted again for that amount. If the provider is unreachable, every screen still works exactly as it does today.

The boundary is the whole design: rates suggest, they never compute a charge. Section "Why never at charge time" explains why that is a legal requirement and not a preference.

Key Decisions (do not deviate without discussion)

  1. Rates fill fields; they never price anything. No Money.default_bank, no exchange_to in any charging path, no conversion at read time. A provider is consulted from a dashboard action and from an explicit merchant-triggered refresh — nowhere else. Adding conversion to a totals or commission path is a breaking change to this plan, not an extension of it.

  2. Every suggested amount is editable before it is saved. A prefill that cannot be overridden is conversion wearing a hat. The merchant reviews and submits; nothing writes on their behalf.

  3. Historical rates are stored, not just the latest. A rate row is (base_currency, currency, rate, effective_on, provider) and rows accumulate. This is required by EU VAT law (below) and is also what makes a suggestion auditable. A single mutable "current rate" row is insufficient and must not be the schema.

  4. Rate lookup is "most recent on or before this date", never "the rate for this date". The ECB publishes only on TARGET working days, so a Saturday has no row. A lookup keyed on exact date silently returns nothing every weekend.

  5. The provider follows the established registry shape, copying Spree.tax_providers / Spree.delivery_rate_providers exactly — including the before: :load_config_initializers empty-array initializer and .concat (never =) for core's own entry. Credentials come from a Spree::Integration subclass declared through self.integration_class, so per-store availability is derived rather than hand-written.

  6. ECB is the bundled default and needs no credentials. No API key, no quota, no attribution, no seller. Keyed commercial providers (Open Exchange Rates and the APILayer family) are extension gems.

  7. No rounding-rule feature in 6.1. Shopify needs rounding rules because it converts and must avoid €9.73 price tags. We hand a merchant a suggestion they then edit, so the human is the rounding rule. Revisit only if a bulk apply path lands (Phase 4).

  8. Nothing in this plan is per-order, per-cart or per-line. The feature operates on configuration screens. If a design discussion reaches "which rate applies to this order", the answer is none — that is the boundary in Decision 1.

Why never at charge time — the constraint that shapes everything

EU VAT Directive 2006/112/EC, Article 91(2), as amended by Directive 2010/45/EU, pins the conversion rate to a single legal instant:

…the exchange rate applicable shall be the latest selling rate recorded, at the time VAT becomes chargeable, on the most representative exchange market or markets of the Member State concerned…

Member States shall accept instead the use of the latest exchange rate published by the European Central Bank at the time the tax becomes chargeable. Conversion between currencies other than the euro shall be made by using the euro exchange rate of each currency.

And Article 230: an invoice may be in any currency, but the VAT amount must be stated in the Member State's national currency, converted by the Article 91 mechanism.

This matters directly because 6.0 charges marketplace commission as a B2B supply with its own VAT (6.0-multi-vendor-marketplace.md, Decision 3). A commission invoice is a legal document. If its VAT figure were derived from a live rate, reprinting a six-month-old invoice would produce a different document than the one issued and filed — the platform would be unable to reproduce its own records under audit.

Three consequences the implementation must honour:

  • The rate, its source and its effective date are persisted alongside any amount derived from them, and never recalculated. (In 6.1 the only such amounts are merchant-typed suggestions, so this is cheap; it becomes load-bearing the moment an invoice document exists.)
  • Historical rates must be queryable, since the anchor is a past instant (Decision 3).
  • The rate source is entity-level configuration, not a per-invoice choice — the ECB method must be applied consistently once adopted.

There is one tension worth recording: the ECB's own page says the reference rates are "published for information purposes only" and that "using the rates for transaction purposes is strongly discouraged." That warning is aimed at using them as a dealing rate, which is exactly what Decision 1 forbids. Using them for VAT conversion is explicitly blessed by the Directive above. The two are not in conflict, but a reader who finds only the ECB disclaimer will think they are.

Industry evidence

The platforms architecturally closest to Spree do not convert at all:

Platform Per-currency amounts Converts Fixed when
Vendure always never in core n/a — write time by construction
Medusa always never in core n/a
Saleor always (channel listings) never in core n/a
Adobe Commerce base + rate table yes display time, cron-refreshed
Shopify optional yes, by default charge time

Vendure is explicit that updating other-currency prices from a rate "would require implementing a custom ProductVariantPriceUpdateStrategy" — conversion is an opt-in extension point, not core behaviour. Saleor's channels each carry exactly one currency and cannot be converted between.

Shopify is the outlier and the instructive one. It converts at the time of the transaction — capture, refund, or chargeback — and openly warns merchants that the delay between authorization and capture "may result in gains or losses." That is defensible for a payment processor that owns the settlement rail. It is the wrong pattern for a platform issuing its own VAT invoices, for the reason in the previous section. Notably, Shopify's subscription flow pins the rate to the first order — i.e. even Shopify freezes the rate where a recurring commitment exists.

The real distinction is not "explicit versus converted" — it is when the number becomes immutable. This plan makes it immutable at write time, like the three headless platforms, and uses rates only to propose it.

Design Details

The rate store

# spree_exchange_rates — one row per (base, currency, day, provider).
# Rows accumulate; nothing is updated in place. A rate that has been read is
# evidence of how an amount was arrived at, and rewriting it destroys that.
class Spree::ExchangeRate < Spree.base_class
  # base_currency : string  — 'EUR' for the ECB feed
  # currency      : string
  # rate          : decimal — precision high enough for thin currencies; NOT (10,2)
  # effective_on  : date    — the feed's own publication date, never fetched_at
  # provider      : string  — the provider class name that wrote it
  # fetched_at    : datetime

  # Most recent on or before — never an exact-date match (Decision 4).
  scope :as_of, ->(date) { where(effective_on: ..date).order(effective_on: :desc) }
end

Unique on (provider, base_currency, currency, effective_on). Global, not store-scoped: a published rate is reference data, like ISO country codes, and two stores reading the same ECB feed on the same day must not produce two answers. Store-level choice of provider is a separate axis (below).

rate precision deserves care. Spree::Money::Rounding documents that Spree's money columns are decimal(_, 2) throughout — that is right for amounts and wrong for a rate. A JPY or IDR rate needs several more places, and rate precision loss compounds through cross-currency derivation.

Cross-currency

The ECB publishes EUR-based rates only, and Article 91 requires that "conversion between currencies other than the euro shall be made by using the euro exchange rate of each currency" — i.e. route through the base, do not invent direct pairs. PLN → USD is (EUR→USD) / (EUR→PLN), computed at read time from two stored rows, never stored as a third row. Storing derived pairs would double the rows and let the two disagree.

The provider

Copies the DeliveryRateProvider shape verbatim — the newest registry in the repo, and the one whose per-store availability is already derived from an integration:

class Spree::ExchangeRateProvider::Base
  # Credentials live on a Spree::Integration subclass; the provider never
  # holds them. Nil means "needs none" — the ECB feed is unauthenticated.
  def self.integration_class = nil

  # Free for providers that declare integration_class; true when none needed.
  def self.available_for_store?(store)
    return true if integration_class.nil?

    store.integrations.active.exists?(type: integration_class)
  end

  def self.base_currency = 'EUR'

  # The currencies this feed carries. Read from the response, never hardcoded:
  # the ECB list has shrunk over the years (29 currencies as of 2026-08, not
  # the 40+ that secondary sources still cite).
  def supported_currencies = raise NotImplementedError

  # @return [Array<Hash>] {currency:, rate:, effective_on:}
  def fetch = raise NotImplementedError
end

Registry wiring, mirroring engine.rb for tax and delivery rates:

  • Environment struct members :exchange_rate_providers and :default_exchange_rate_provider
  • an initializer before: :load_config_initializers setting [], so a provider gem registering from its own initializer is not clobbered
  • core's entry appended in after_initialize with .concat [Spree::ExchangeRateProvider::EuropeanCentralBank] — never =
  • Spree.exchange_rate_providers reader/writer in core/lib/spree/core.rb

Selection follows Spree::Market#tax_provider: a string column, inclusion validated against the registry, resolved with safe_constantize and a hard fallback so an uninstalled gem cannot raise. Provider choice belongs on Spree::Store — it is deployment configuration, and Decision 3's consistency requirement argues against per-market divergence.

Refresh

A Spree::ExchangeRates::RefreshJob fetching the active provider's feed and inserting any rows it does not already have.

This would be the first outbound-HTTP recurring job in the repo — the four existing entries in server/config/recurring.yml are all internal housekeeping. So it must state its own failure behaviour rather than inherit a convention:

  • a failed fetch is logged and leaves existing rows untouched; it never clears them
  • suggestions carry the age of the rate they used, so a stale feed is visible rather than silent
  • no retry storm: once daily matches the ECB's own publication cadence

The engine cannot schedule itself. The recurring entry is a host-app responsibility (server/config/recurring.yml), and belongs in the upgrade manifest's "scheduling cron jobs" step alongside the existing ones.

Where suggestions appear

A dashboard-only affordance beside any per-currency amount group. The three that exist today:

Screen Field Shape
Product prices / price lists Spree::Price rows the grid PriceList#add_products already materializes
Commission rates amounts, bounds shipped 6.0, one input per store currency
Delivery calculators preference :amounts, :hash Spree::Calculator::CurrencyAmounts

The interaction is the same in all three: the merchant fills one currency, a "fill the rest" control proposes the others, every proposed value lands in an editable input, and Save writes what is on screen. The API is not involved in conversion at all — the dashboard asks for rates, computes suggestions client-side, and posts ordinary amounts.

A read-only GET /api/v3/admin/exchange_rates serves the dashboard. There is no conversion endpoint: an endpoint that takes an amount and returns a converted amount would be a charge-time conversion waiting to be called from the wrong place.

Migration Path

Nothing to migrate — this is additive and greenfield. There is no FX scaffolding in the repo today.

Phase 1 — the store. Spree::ExchangeRate + migration, the as_of lookup with cross-currency derivation through the base, and specs covering the weekend gap (Decision 4) and the derived-pair arithmetic. No provider, no UI. Independently useful and independently reviewable.

Phase 2 — the ECB provider. ExchangeRateProvider::Base + EuropeanCentralBank, the registry wiring, the store column, and RefreshJob. VCR-backed specs against the real feed shape. Behind this phase the repo can populate rates and read them, with nothing consuming them yet.

Phase 3 — suggestions in the dashboard. The GET endpoint, and the fill affordance on the three surfaces above, starting with product prices — the highest-volume typing burden and the screen whose grid already exists. Commission rates and delivery calculators follow the same component.

Phase 4 — keyed providers (optional). An Open Exchange Rates gem, proving the integration_class path carries credentials properly.

Deliberately not in scope: a bulk "restate every price in this list from rates" action. That is the point where a rounding-rule feature becomes necessary (Decision 7) and where an unattended job starts writing prices, which needs its own design.

Constraints on Current Work

Applies now, before any of this is implemented:

  • Do not set Money.default_bank, and do not call Money#exchange_to anywhere. The gem's default bank has an empty rate store, so today any conversion attempt raises Money::Bank::UnknownRate — which is the correct behaviour and should stay that way. Spree::Money deliberately exposes no conversion method.
  • New money configuration is born per currency. A new model or preference holding a configurable amount states one per currency (follow Spree::Price, Spree::CommissionRateValue, or Spree::Calculator::CurrencyAmounts), never one amount plus a currency column. Retrofitting is what 6.0-multi-vendor-marketplace.md had to do twice.
  • A stored amount is never derived at read time. If a value can change without anyone editing it, it is not configuration.
  • No conversion endpoint on any API surface, for the reason above.
  • Rate precision is not money precision. Do not reuse decimal(_, 2) or Spree::Money::Rounding for a rate.

Open Questions

  1. Does the marketplace commission invoice exist as a document in 6.1? Article 230's "VAT amount in the national currency" only binds once Spree issues one. If commission invoicing lands, the persisted rate/date/source triple moves from good practice to compliance-critical, and this plan's Phase 1 becomes its dependency.

  2. Store-level or market-level provider choice? This plan says store, on consistency grounds. A group operating separate legal entities per market might reasonably differ — but Decision 3's "applied consistently once adopted" cuts against it. Needs a merchant with the actual problem.

  3. How is a stale rate surfaced? "Rate from 3 days ago" is fine; "from 3 months ago" means the job has been failing silently. Threshold and where it renders are undecided.

  4. Does the ECB's 29-currency list need a documented fallback? A store supporting a currency the ECB does not carry gets no suggestion at all — correct, but the UI should say why rather than showing an empty field.

Related — a bug this research surfaced, not part of this plan

Two multi-currency defects exist in promotions today. They are correctness bugs, not ergonomics, and should not wait on this feature:

  • Spree::Calculator::FlatRate (used by both CreateAdjustment and CreateItemAdjustments) carries a single preferred_amount + preferred_currency and never received the amounts hash the shipping calculators got. On a currency mismatch it returns 0 — so a "20 off" promo on a USD-configured store applies to a EUR order as a silent zero-value discount, not as 20 EUR and not as an ineligible promotion (core/app/models/spree/calculator/flat_rate.rb:16-20).
  • Spree::Promotion::Rules::ItemTotal stores preferred_amount_min / preferred_amount_max as bare decimals with no currency at all, compares them against order.item_total in whatever currency the order carries, and then labels them with that currency for display (item_total.rb:22,25,38-48). "Spend 100, get 20 off" is a different threshold in every currency.

The only current workaround is one promotion per currency gated by Spree::Promotion::Rules::Currency. The fix mirrors what shipping calculators already did — include Spree::Calculator::CurrencyAmounts in FlatRate, and give ItemTotal per-currency thresholds — and is independent of exchange rates entirely.

References