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.

Support updating base prices in bulk and embed price bulk editor on product form

Damian Legawieccb7fdb905cea
diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
index 362d395f12..43186c7528 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -22,6 +22,7 @@ import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { adminClient } from '@/client'
+import { BulkPriceEditorDialog } from '@/components/spree/bulk-price-editor/bulk-price-editor-dialog'
import { useConfirm } from '@/components/spree/confirm-dialog'
import { CustomFieldsCard } from '@/components/spree/custom-fields/custom-fields-card'
import { FormActions, useFormSubmitShortcut } from '@/components/spree/form-actions'
@@ -148,6 +149,7 @@ function ProductForm({ product }: { product: Product }) {
const updateProduct = useUpdateProduct()
const deleteProduct = useDeleteProduct()
const hasVariants = (product.variant_count ?? 0) > 0
+ const [editPricesOpen, setEditPricesOpen] = useState(false)
const form = useForm<ProductFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -219,7 +221,19 @@ function ProductForm({ product }: { product: Product }) {
title={product.name}
backTo="products"
badges={<StatusBadge status={product.status} />}
- actions={<FormActions form={form} saveLabel={t('admin.products.save_label')} />}
+ actions={
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setEditPricesOpen(true)}
+ >
+ {t('admin.pages.products.price_lists.edit_prices_cta')}
+ </Button>
+ <FormActions form={form} saveLabel={t('admin.products.save_label')} />
+ </>
+ }
resource={{ id: product.id }}
onDelete={handleDelete}
deleteLabel={t('admin.products.delete_label')}
@@ -253,6 +267,11 @@ function ProductForm({ product }: { product: Product }) {
</>
}
/>
+ <BulkPriceEditorDialog
+ open={editPricesOpen}
+ onOpenChange={setEditPricesOpen}
+ scope={{ kind: 'product', product: { id: product.id, name: product.name } }}
+ />
</form>
)
}
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
index 195ec42489..80bc322c59 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
@@ -67,6 +67,68 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller do
expect(ids).to include(base_price.prefixed_id, other_price.prefixed_id)
end
+ it 'scopes to a single product via q[variant_product_id_eq] (base prices only)' do
+ other_product = create(:product, stores: [store])
+ other_base = other_product.master.prices.find_by!(currency: 'USD', price_list_id: nil)
+
+ get :index,
+ params: {
+ q: { variant_product_id_eq: product.id, price_list_id_null: true }
+ },
+ as: :json
+
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(base_price.prefixed_id)
+ expect(ids).not_to include(list_price.prefixed_id, other_base.prefixed_id)
+ end
+
+ # The `search` Ransack scope ORs the underlying variant's SKU, parent
+ # product name, and option-value presentations into a single subquery,
+ # so the spreadsheet search field can match any of those without
+ # producing duplicate Price rows.
+ describe 'free-text search via q[search]' do
+ let!(:red_option_value) do
+ ot = Spree::OptionType.find_by(name: 'shirt-color') ||
+ create(:option_type, name: 'shirt-color', presentation: 'Color')
+ ot.option_values.find_by(name: 'red') ||
+ create(:option_value, option_type: ot, name: 'red', presentation: 'Red')
+ end
+ let!(:red_variant) do
+ v = create(:variant, product: product, sku: 'TSHIRT-RED-XL')
+ v.option_values << red_option_value
+ v
+ end
+ let!(:red_price) { v_price(red_variant) }
+
+ def v_price(v)
+ v.prices.find_by!(currency: 'USD', price_list_id: nil)
+ end
+
+ it 'matches by SKU substring' do
+ get :index, params: { q: { search: 'TSHIRT' } }, as: :json
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(red_price.prefixed_id)
+ end
+
+ it 'matches by option-value presentation' do
+ get :index, params: { q: { search: 'Red' } }, as: :json
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(red_price.prefixed_id)
+ end
+
+ it 'matches by product name' do
+ product.update!(name: 'Crewneck Sweater')
+ get :index, params: { q: { search: 'crewneck' } }, as: :json
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(red_price.prefixed_id)
+ end
+
+ it 'returns no rows for a short query (under the 3-char floor)' do
+ get :index, params: { q: { search: 'Re' } }, as: :json
+ expect(json_response['data']).to be_empty
+ end
+ end
+
it 'excludes prices from other stores' do
other_store = create(:store)
other_product = create(:product, stores: [other_store])
diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rb
index 48501065f1..91aeb7c893 100644
--- a/spree/core/app/services/spree/prices/bulk_upsert.rb
+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb
@@ -1,18 +1,29 @@
module Spree
module Prices
- # Bulk-writes Spree::Price rows on the unique key
- # `(variant_id, currency, price_list_id)` and sweeps stale
- # placeholder rows in one transaction.
+ # Bulk-writes Spree::Price rows and sweeps stale placeholder rows in
+ # one transaction.
#
- # The unique index on `spree_prices` is partial
- # (`WHERE amount IS NOT NULL`), so `upsert_all` can't see
- # placeholder rows (amount IS NULL) as conflict targets — filling
- # in a placeholder via upsert inserts a sibling row instead of
+ # `spree_prices` is guarded by two partial unique indexes on PG/SQLite
+ # (collapsed to one composite index on MySQL):
+ # - base prices (price_list_id IS NULL): unique on (variant_id, currency)
+ # - overrides (price_list_id IS NOT NULL): unique on (variant_id, currency, price_list_id)
+ # A single `upsert_all` can only target one index, so rows ship in two
+ # batches — base vs override — each routed to the correct ON CONFLICT.
+ #
+ # Both indexes are also partial on `amount IS NOT NULL`, so `upsert_all`
+ # can't see placeholder rows (amount IS NULL) as conflict targets —
+ # filling in a placeholder via upsert inserts a sibling row instead of
# updating. The post-write sweep removes those.
class BulkUpsert
prepend Spree::ServiceModule::Base
- UNIQUE_BY = %i[variant_id currency price_list_id].freeze
+ # Two partial unique indexes guard `spree_prices` on PG/SQLite:
+ # - base prices (price_list_id IS NULL): unique on (variant_id, currency)
+ # - overrides (price_list_id IS NOT NULL): unique on (variant_id, currency, price_list_id)
+ # A single `upsert_all` can only target one index, so base-price rows
+ # and override rows ship in separate batches.
+ BASE_UNIQUE_BY = %i[variant_id currency].freeze
+ OVERRIDE_UNIQUE_BY = %i[variant_id currency price_list_id].freeze
# @param rows [Array<Hash>] each row must carry
# `variant_id`, `currency`, and `amount`; `price_list_id` and
@@ -36,20 +47,25 @@ module Spree
return success(price_count: 0) if affected_keys.empty?
+ base_rows, override_rows = payload.partition { |r| r[:price_list_id].nil? }
+
Spree::Price.transaction do
- # `update_only` lists only domain columns. Rails adds
- # `updated_at` automatically (when `record_timestamps` is on,
- # which it is for `Spree::Price`); listing it explicitly here
- # produces `SET updated_at = …, updated_at = …` on PG and the
- # statement fails with "multiple assignments to same column".
- if payload.any?
- Spree::Price.upsert_all(
- payload,
- update_only: %i[amount compare_at_amount],
- **upsert_opts(UNIQUE_BY)
- )
+ # MySQL treats NULL values as distinct in unique indexes, so
+ # `ON DUPLICATE KEY UPDATE` never fires for base prices —
+ # `upsert_all` would silently insert a sibling row. Route base
+ # rows through a SELECT-then-UPDATE/INSERT path on MySQL only.
+ if base_rows.any? && mysql?
+ upsert_base_rows_for_mysql(base_rows)
+ else
+ upsert_batch(base_rows, BASE_UNIQUE_BY)
end
+ upsert_batch(override_rows, OVERRIDE_UNIQUE_BY)
sweep(affected_keys, clear_rows)
+ # `upsert_all` and `delete_all` both skip AR callbacks, so the
+ # `Price -> Variant -> Product` `touch:` chain never fires —
+ # downstream caches (`cache_key_with_version`) would stay stale.
+ # Re-trigger the chain with one `.touch` per affected variant.
+ touch_variants(affected_keys.map(&:first).uniq)
end
success(price_count: payload.length)
@@ -57,6 +73,21 @@ module Spree
private
+ # `update_only` lists only domain columns. Rails adds `updated_at`
+ # automatically (when `record_timestamps` is on, which it is for
+ # `Spree::Price`); listing it explicitly here produces
+ # `SET updated_at = …, updated_at = …` on PG and the statement fails
+ # with "multiple assignments to same column".
+ def upsert_batch(rows, unique_by)
+ return if rows.empty?
+
+ Spree::Price.upsert_all(
+ rows,
+ update_only: %i[amount compare_at_amount],
+ **upsert_opts(unique_by)
+ )
+ end
+
def build_payload(rows)
now = Time.current
rows.map do |row|
@@ -105,13 +136,66 @@ module Spree
Spree::Price.where(id: doomed_ids).delete_all if doomed_ids.any?
end
+ # Bumps `updated_at` on the affected variants and their parent
+ # products to invalidate `cache_key_with_version`-based caches —
+ # `upsert_all` and `delete_all` skip the `Price -> Variant` and
+ # `Variant -> Product` `touch:` chains otherwise.
+ #
+ # We deliberately bypass AR callbacks: invoking `Variant#touch`
+ # would fire `after_commit :remove_prices_from_master_variant`,
+ # which `delete_all`s the master's prices whenever a non-master
+ # sibling has any prices — wiping exactly the rows the bulk
+ # upsert just persisted on a freshly-created list. `touch_all`
+ # gives us the cache bust without that side effect.
+ def touch_variants(variant_ids)
+ return if variant_ids.empty?
+
+ variants = Spree::Variant.where(id: variant_ids)
+ product_ids = variants.pluck(:product_id).uniq
+ variants.touch_all
+ Spree::Product.where(id: product_ids).touch_all if product_ids.any?
+ end
+
# MySQL infers conflict targets from its own unique indexes and
# rejects an explicit `unique_by`.
def upsert_opts(unique_by)
- return {} if ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ return {} if mysql?
{ unique_by: unique_by }
end
+
+ def mysql?
+ ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ end
+
+ # MySQL-only path: NULLs are distinct in unique indexes, so
+ # `(variant_id, currency, NULL)` doesn't conflict with another
+ # `(variant_id, currency, NULL)` — `upsert_all` would insert a
+ # sibling instead of updating. Look up existing base rows first,
+ # update them one by one, and `insert_all` the rest.
+ def upsert_base_rows_for_mysql(rows)
+ rows_by_key = rows.index_by { |r| [r[:variant_id], r[:currency]] }
+
+ Spree::Price.where(
+ variant_id: rows.map { |r| r[:variant_id] }.uniq,
+ currency: rows.map { |r| r[:currency] }.uniq,
+ price_list_id: nil
+ ).find_each do |price|
+ # The `IN (...)` query can return cross-pairs (e.g. `v=1,c=EUR`
+ # exists in the DB even though the caller only passed `v=1,c=USD`
+ # and `v=2,c=EUR`). Skip rows the caller didn't request.
+ row = rows_by_key.delete([price.variant_id, price.currency])
+ next unless row
+
+ price.update_columns(
+ amount: row[:amount],
+ compare_at_amount: row[:compare_at_amount],
+ updated_at: row[:updated_at]
+ )
+ end
+
+ Spree::Price.insert_all(rows_by_key.values) if rows_by_key.any?
+ end
end
end
end
diff --git a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb
index 73bf1b2125..8e6de9c0e6 100644
--- a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb
+++ b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb
@@ -60,6 +60,75 @@ RSpec.describe Spree::Prices::BulkUpsert do
expect(row.amount).to eq(BigDecimal('4.20'))
end
+ # Regression: a single bulk_upsert call can carry base-price rows
+ # (price_list_id IS NULL) alongside overrides. The unique constraints
+ # live in two separate partial indexes — one keyed on (variant_id,
+ # currency) for base, one on the triple for overrides — so the service
+ # must route each row to the right ON CONFLICT clause. Before the fix,
+ # base rows hit the override index and crashed with RecordNotUnique.
+ it 'updates an existing base price (price_list_id IS NULL)' do
+ base = variant.prices.find_by!(currency: 'USD', price_list_id: nil)
+
+ result = described_class.call(
+ rows: [{ variant_id: variant.id, currency: 'USD', amount: '12.34' }]
+ )
+
+ expect(result).to be_success
+ expect(base.reload.amount).to eq(BigDecimal('12.34'))
+ end
+
+ it 'handles base + override rows in the same call' do
+ base = variant.prices.find_by!(currency: 'USD', price_list_id: nil)
+
+ result = described_class.call(
+ rows: [
+ { variant_id: variant.id, currency: 'USD', amount: '7.77' },
+ { variant_id: variant.id, currency: 'USD', price_list_id: price_list.id, amount: '8.88' }
+ ]
+ )
+
+ expect(result).to be_success
+ expect(result.value).to eq(price_count: 2)
+ expect(base.reload.amount).to eq(BigDecimal('7.77'))
+ expect(override.reload.amount).to eq(BigDecimal('8.88'))
+ end
+
+ it 'touches the variant (and via touch: true, the product) after an upsert' do
+ Timecop.freeze(Time.current.change(usec: 0)) do
+ variant.update_columns(updated_at: 1.day.ago)
+ product.update_columns(updated_at: 1.day.ago)
+
+ described_class.call(
+ rows: [{ variant_id: variant.id, currency: 'USD', amount: '7.77' }]
+ )
+
+ expect(variant.reload.updated_at).to eq(Time.current)
+ expect(product.reload.updated_at).to eq(Time.current)
+ end
+ end
+
+ # Regression: the base-row update loop pulls existing rows via
+ # `WHERE variant_id IN (...) AND currency IN (...)`, which returns
+ # cross-pairs (variant_a + EUR, variant_b + USD) that the caller never
+ # asked about. The loop must skip those instead of crashing on a nil
+ # row when it looks up the request hash.
+ it 'tolerates cross-pair matches in the existing-base-row lookup' do
+ other_variant = create(:variant, product: product)
+ # Seed an unrelated base price the cross-pair `IN` query will catch.
+ create(:price, variant: other_variant, currency: 'EUR', amount: 99.0, price_list_id: nil)
+
+ result = described_class.call(
+ rows: [
+ { variant_id: variant.id, currency: 'USD', amount: '7.77' },
+ { variant_id: other_variant.id, currency: 'USD', amount: '8.88' }
+ ]
+ )
+
+ expect(result).to be_success
+ base = variant.prices.find_by!(currency: 'USD', price_list_id: nil)
+ expect(base.amount).to eq(BigDecimal('7.77'))
+ end
+
it 'drops rows missing variant_id or currency' do
result = described_class.call(rows: [{ amount: '9.99' }])