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.

Bulk editor

Damian Legawiec6160b371cead
diff --git a/admin/app/assets/tailwind/spree/admin/components/_bulk-editor.css b/admin/app/assets/tailwind/spree/admin/components/_bulk-editor.css
new file mode 100644
index 0000000000..c98f7fdff5
--- /dev/null
+++ b/admin/app/assets/tailwind/spree/admin/components/_bulk-editor.css
@@ -0,0 +1,64 @@
+/* Bulk Editor - Spreadsheet-style price editing */
+
+/* Table with collapsed borders */
+[data-bulk-editor-target="table"] {
+ border-collapse: collapse;
+}
+
+/* Table cells with borders */
+[data-bulk-editor-target="table"] td {
+ @apply border border-gray-200;
+}
+
+/* Input cell states */
+[data-bulk-editor-target="cell"] {
+ @apply transition-colors duration-75 cursor-cell caret-transparent border-0;
+}
+
+/* Selected cells - light background, no individual border */
+[data-bulk-editor-target="cell"].selected {
+ @apply bg-blue-50;
+}
+
+/* Focused cell in selection mode */
+[data-bulk-editor-target="cell"]:focus {
+ @apply bg-blue-100;
+}
+
+/* Editing mode - white background, text cursor, visible caret */
+[data-bulk-editor-target="cell"].editing {
+ @apply bg-white cursor-text caret-inherit;
+}
+
+/* Selection overlay - single border around entire selection */
+.selection-overlay {
+ @apply absolute pointer-events-none border-2 border-blue-500 z-10 hidden;
+}
+
+/* Form container needs relative positioning for fill handle */
+[data-controller="bulk-editor"] {
+ @apply relative;
+}
+
+/* Prevent text selection during drag operations */
+[data-controller="bulk-editor"].fill-dragging {
+ @apply select-none cursor-crosshair;
+}
+
+[data-controller="bulk-editor"].fill-dragging [data-bulk-editor-target="cell"] {
+ @apply cursor-crosshair;
+}
+
+/* Fill handle - blue dot at bottom-right corner of focused cell */
+.fill-handle {
+ @apply absolute w-3 h-3 bg-blue-600 border border-white rounded-lg cursor-crosshair z-10 shadow-xs hidden;
+}
+
+.fill-handle:hover {
+ @apply bg-blue-700 scale-125;
+}
+
+/* Keyboard shortcut hints */
+.bulk-editor-shortcuts kbd {
+ @apply px-1.5 py-0.5 text-xs font-mono bg-gray-100 border border-gray-200 rounded;
+}
diff --git a/admin/app/assets/tailwind/spree/admin/index.css b/admin/app/assets/tailwind/spree/admin/index.css
index 09b302378e..e1bde1b372 100644
--- a/admin/app/assets/tailwind/spree/admin/index.css
+++ b/admin/app/assets/tailwind/spree/admin/index.css
@@ -59,6 +59,7 @@
@import "./components/_media-form.css";
@import "./components/_seo-form.css";
@import "./components/_line-items.css";
+@import "./components/_bulk-editor.css";
/* Views */
@import "./views/_dashboard.css";
diff --git a/admin/app/controllers/spree/admin/price_list_products_controller.rb b/admin/app/controllers/spree/admin/price_list_products_controller.rb
new file mode 100644
index 0000000000..03edcae698
--- /dev/null
+++ b/admin/app/controllers/spree/admin/price_list_products_controller.rb
@@ -0,0 +1,31 @@
+module Spree
+ module Admin
+ class PriceListProductsController < ResourceController
+ belongs_to 'spree/price_list', find_by: :id
+
+ # GET /admin/price_lists/:price_list_id/products/bulk_new
+ def bulk_new
+ @price_list = parent
+ @currency = params[:currency] || current_store.default_currency
+ end
+
+ # POST /admin/price_lists/:price_list_id/products/bulk_create.turbo_stream
+ def bulk_create
+ parent.add_products(params[:product_ids])
+
+ flash[:success] = Spree.t(:products_added)
+ end
+
+ # DELETE /admin/price_lists/:price_list_id/products/bulk_destroy.turbo_stream
+ def bulk_destroy
+ parent.remove_products(params[:ids])
+ end
+
+ private
+
+ def model_class
+ Spree::Product
+ end
+ end
+ end
+end
diff --git a/admin/app/controllers/spree/admin/price_lists_controller.rb b/admin/app/controllers/spree/admin/price_lists_controller.rb
new file mode 100644
index 0000000000..228762bd62
--- /dev/null
+++ b/admin/app/controllers/spree/admin/price_lists_controller.rb
@@ -0,0 +1,34 @@
+module Spree
+ module Admin
+ class PriceListsController < ResourceController
+ include ProductsBreadcrumbConcern
+
+ # GET /admin/price_lists/:price_list_id/edit_prices
+ def edit_prices
+ @currency = params[:currency] || current_store.default_currency
+ @prices = @price_list.prices.
+ includes(variant: [:product, { option_values: :option_type }]).
+ where(currency: @currency).
+ joins(variant: :product).
+ order("#{Spree::Product.table_name}.name ASC", "#{Spree::Variant.table_name}.position ASC")
+ end
+
+ private
+
+ def location_after_save
+ spree.admin_price_list_path(@price_list)
+ end
+
+ def update_turbo_stream_enabled?
+ true
+ end
+
+ def permitted_resource_params
+ params.require(:price_list).permit(
+ permitted_price_list_attributes,
+ prices_attributes: [:id, :variant_id, :currency, :amount, :compare_at_amount, :_destroy]
+ )
+ end
+ end
+ end
+end
diff --git a/admin/app/helpers/spree/admin/bulk_editor_helper.rb b/admin/app/helpers/spree/admin/bulk_editor_helper.rb
new file mode 100644
index 0000000000..bf7a5203b2
--- /dev/null
+++ b/admin/app/helpers/spree/admin/bulk_editor_helper.rb
@@ -0,0 +1,41 @@
+module Spree
+ module Admin
+ module BulkEditorHelper
+ # Define the cell actions using Stimulus keyboard event filters
+ # Note: Enter, Escape, Delete, Backspace are handled via keydown->bulk-editor#handleKeydown
+ # since they need special logic for edit mode vs selection mode
+ # @return [String] the cell actions
+ def bulk_editor_cell_actions
+ [
+ 'focus->bulk-editor#onCellFocus',
+ 'blur->bulk-editor#onCellBlur',
+ 'mousedown->bulk-editor#onCellMouseDown',
+ 'mouseenter->bulk-editor#onCellMouseEnter',
+ 'dblclick->bulk-editor#onCellDoubleClick',
+ 'input->bulk-editor#markDirty',
+ 'keydown->bulk-editor#handleKeydown',
+ # Copy/Paste/Fill (Ctrl for Windows/Linux, Meta for Mac)
+ 'keydown.ctrl+c->bulk-editor#copy',
+ 'keydown.meta+c->bulk-editor#copy',
+ 'keydown.ctrl+v->bulk-editor#paste',
+ 'keydown.meta+v->bulk-editor#paste',
+ 'keydown.ctrl+d->bulk-editor#fillDown',
+ 'keydown.meta+d->bulk-editor#fillDown',
+ # Navigation (only works in selection mode)
+ 'keydown.up->bulk-editor#navigateUp',
+ 'keydown.down->bulk-editor#navigateDown',
+ 'keydown.left->bulk-editor#navigateLeft',
+ 'keydown.right->bulk-editor#navigateRight',
+ # Selection
+ 'keydown.shift+up->bulk-editor#selectUp',
+ 'keydown.shift+down->bulk-editor#selectDown',
+ 'keydown.shift+left->bulk-editor#selectLeft',
+ 'keydown.shift+right->bulk-editor#selectRight',
+ # Tab navigation (works in both modes)
+ 'keydown.tab->bulk-editor#navigateRight',
+ 'keydown.shift+tab->bulk-editor#navigateLeft'
+ ].join(' ')
+ end
+ end
+ end
+end
diff --git a/admin/app/javascript/spree/admin/application.js b/admin/app/javascript/spree/admin/application.js
index 0191fb52ad..d8ac4896a5 100644
--- a/admin/app/javascript/spree/admin/application.js
+++ b/admin/app/javascript/spree/admin/application.js
@@ -89,6 +89,7 @@ import TooltipController from 'spree/admin/controllers/tooltip_controller'
import TurboSubmitButtonController from 'spree/admin/controllers/turbo_submit_button_controller'
import UnitSystemController from 'spree/admin/controllers/unit_system_controller'
import VariantsFormController from 'spree/admin/controllers/variants_form_controller'
+import BulkEditorController from 'spree/admin/controllers/bulk_editor_controller'
import AddressAutocompleteController from 'spree/core/controllers/address_autocomplete_controller'
import AddressFormController from 'spree/core/controllers/address_form_controller'
import DisableSubmitButtonController from 'spree/core/controllers/disable_submit_button_controller'
@@ -160,6 +161,7 @@ application.register('turbo-submit-button', TurboSubmitButtonController)
application.register('textarea-autogrow', TextareaAutogrow)
application.register('unit-system', UnitSystemController)
application.register('variants-form', VariantsFormController)
+application.register('bulk-editor', BulkEditorController)
LocalTime.start()
diff --git a/admin/app/javascript/spree/admin/controllers/bulk_editor_controller.js b/admin/app/javascript/spree/admin/controllers/bulk_editor_controller.js
new file mode 100644
index 0000000000..0c168715ec
--- /dev/null
+++ b/admin/app/javascript/spree/admin/controllers/bulk_editor_controller.js
@@ -0,0 +1,770 @@
+import { Controller } from '@hotwired/stimulus'
+
+// Spreadsheet-style bulk editor controller
+// Features:
+// - Multi-cell selection (Shift+Click, Click+Drag)
+// - Copy/Paste (Ctrl+C/Cmd+C, Ctrl+V/Cmd+V)
+// - Fill down (Ctrl+D/Cmd+D or drag fill handle)
+// - Keyboard navigation (Arrow keys, Tab, Enter)
+// - Bulk clear (Delete/Backspace)
+// - Fill handle (blue dot) for dragging values to adjacent cells
+//
+// Usage:
+// <form data-controller="bulk-editor"
+// data-action="keydown.ctrl+a->bulk-editor#selectAll keydown.meta+a->bulk-editor#selectAll">
+// <table data-bulk-editor-target="table">
+// <tr data-bulk-editor-target="row">
+// <td>
+// <input data-bulk-editor-target="cell"
+// data-row="0" data-col="0"
+// data-action="focus->bulk-editor#onCellFocus
+// blur->bulk-editor#onCellBlur
+// keydown.ctrl+c->bulk-editor#copy
+// keydown.meta+c->bulk-editor#copy
+// keydown.ctrl+v->bulk-editor#paste
+// keydown.meta+v->bulk-editor#paste
+// keydown.ctrl+d->bulk-editor#fillDown
+// keydown.meta+d->bulk-editor#fillDown
+// keydown.up->bulk-editor#navigateUp
+// keydown.down->bulk-editor#navigateDown
+// keydown.left->bulk-editor#navigateLeft
+// keydown.right->bulk-editor#navigateRight
+// keydown.shift+up->bulk-editor#selectUp
+// keydown.shift+down->bulk-editor#selectDown
+// keydown.shift+left->bulk-editor#selectLeft
+// keydown.shift+right->bulk-editor#selectRight
+// keydown.tab->bulk-editor#navigateRight
+// keydown.shift+tab->bulk-editor#navigateLeft
+// keydown.enter->bulk-editor#navigateDown
+// keydown->bulk-editor#handleKeydown
+// input->bulk-editor#markDirty">
+//
+// Note: Delete/Backspace keys are handled via handleKeydown since Stimulus
+// doesn't support them as keyboard event filters.
+// </td>
+// </tr>
+// </table>
+// </form>
+//
+export default class extends Controller {
+ static targets = ['table', 'row', 'cell', 'saveButton', 'statusBar']
+
+ connect() {
+ this.dirtyInputs = new Set()
+ this.selectedCells = new Set()
+ this.anchorCell = null // Starting point for range selection
+ this.extendCell = null // Current end point for range selection (Shift+Arrow)
+ this.focusedCell = null
+ this.editingCell = null // Cell currently in edit mode
+ this.isSelecting = false
+ this.isDraggingFillHandle = false
+ this.isMouseOverFillHandle = false
+ this.fillStartCell = null
+ this.copiedValues = []
+
+ // Create fill handle element if not present
+ this.createFillHandle()
+
+ // Make all cells read-only initially (selection mode)
+ this.cellTargets.forEach(cell => {
+ cell.readOnly = true
+ })
+
+ this.boundHandleBeforeUnload = this.handleBeforeUnload.bind(this)
+ this.boundHandleMouseUp = this.handleMouseUp.bind(this)
+ this.boundHandleMouseMove = this.handleMouseMove.bind(this)
+
+ window.addEventListener('beforeunload', this.boundHandleBeforeUnload)
+ document.addEventListener('mouseup', this.boundHandleMouseUp)
+ document.addEventListener('mousemove', this.boundHandleMouseMove)
+ }
+
+ disconnect() {
+ window.removeEventListener('beforeunload', this.boundHandleBeforeUnload)
+ document.removeEventListener('mouseup', this.boundHandleMouseUp)
+ document.removeEventListener('mousemove', this.boundHandleMouseMove)
+ }
+
+ // ==================== Fill Handle ====================
+
+ createFillHandle() {
+ if (this.fillHandle) return
+
+ this.fillHandle = document.createElement('div')
+ this.fillHandle.className = 'fill-handle'
+ this.fillHandle.addEventListener('mousedown', this.onFillHandleMouseDown.bind(this))
+ this.fillHandle.addEventListener('mouseenter', () => { this.isMouseOverFillHandle = true })
+ this.fillHandle.addEventListener('mouseleave', () => { this.isMouseOverFillHandle = false })
+ this.element.appendChild(this.fillHandle)
+ }
+
+ positionFillHandle() {
+ if (!this.fillHandle || !this.focusedCell) {
+ this.hideFillHandle()
+ return
+ }
+
+ const cell = this.focusedCell
+ const cellRect = cell.getBoundingClientRect()
+ const containerRect = this.element.getBoundingClientRect()
+
+ // Position at bottom-right corner of the focused cell
+ this.fillHandle.style.display = 'block'
+ this.fillHandle.style.left = `${cellRect.right - containerRect.left - 4}px`
+ this.fillHandle.style.top = `${cellRect.bottom - containerRect.top - 4}px`
+ }
+
+ hideFillHandle() {
+ if (this.fillHandle) {
+ this.fillHandle.style.display = 'none'
+ }
+ }
+
+ onFillHandleMouseDown(event) {
+ event.preventDefault()
+ event.stopPropagation()
+
+ if (!this.focusedCell) return
+
+ this.isDraggingFillHandle = true
+ this.fillStartCell = this.focusedCell
+ this.fillStartValue = this.focusedCell.value
+
+ // Store the starting selection
+ this.fillStartCoords = this.getCellCoords(this.fillStartCell)
+
+ // Ensure the starting cell is selected
+ this.clearSelection()
+ this.selectCell(this.fillStartCell)
+
+ // Add visual indicator
+ this.element.classList.add('fill-dragging')
+ }
+
+ handleMouseMove(event) {
+ if (!this.isDraggingFillHandle) return
+
+ // Find the cell under the cursor
+ const cellUnderCursor = this.getCellAtPoint(event.clientX, event.clientY)
+ if (!cellUnderCursor) return
+
+ // Select range from start to current (vertical or horizontal)
+ this.clearSelection()
+ this.selectRange(this.fillStartCell, cellUnderCursor)
+ }
+
+ getCellAtPoint(x, y) {
+ // First try using document.elementFromPoint
+ let element = document.elementFromPoint(x, y)
+
+ // Walk up to find a cell target
+ while (element && element !== this.element) {
+ if (this.cellTargets.includes(element)) {
+ return element
+ }
+ element = element.parentElement
+ }
+
+ // Fallback: find closest cell by checking expanded bounding boxes
+ // This handles gaps between cells
+ let closestCell = null
+ let closestDistance = Infinity
+
+ for (const cell of this.cellTargets) {
+ const rect = cell.getBoundingClientRect()
+ // Expand the hit area slightly
+ const padding = 5
+ if (x >= rect.left - padding && x <= rect.right + padding &&
+ y >= rect.top - padding && y <= rect.bottom + padding) {
+ const centerX = rect.left + rect.width / 2
+ const centerY = rect.top + rect.height / 2
+ const distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2))
+ if (distance < closestDistance) {
+ closestDistance = distance
+ closestCell = cell
+ }
+ }
+ }
+
+ return closestCell
+ }
+
+ handleMouseUp() {
+ if (this.isDraggingFillHandle) {
+ this.completeFillDrag()
+ }
+ this.isSelecting = false
+ this.isDraggingFillHandle = false
+ this.element.classList.remove('fill-dragging')
+ }
+
+ completeFillDrag() {
+ if (!this.fillStartCell || this.selectedCells.size < 2) return
+
+ const fillValue = this.fillStartValue
+
+ // Apply value to all selected cells except the start cell
+ this.selectedCells.forEach(cell => {
+ if (cell !== this.fillStartCell) {
+ this.setCellValue(cell, fillValue)
+ }
+ })
+
+ const filledCount = this.selectedCells.size - 1
+ if (filledCount > 0) {
+ this.showNotification(`Filled ${filledCount} cell(s)`)
+ }
+
+ // Clear selection and return focus to the start cell
+ this.clearSelection()
+ this.fillStartCell.focus()
+ this.selectCell(this.fillStartCell)
+ this.anchorCell = this.fillStartCell
+ }
+
+ // ==================== Cell Selection ====================
+
+ onCellFocus(event) {
+ const cell = event.target
+ this.focusedCell = cell
+
+ // Exit edit mode if focusing a different cell
+ if (this.editingCell && this.editingCell !== cell) {
+ this.exitEditMode()
+ }
+
+ if (!event.shiftKey) {
+ this.clearSelection()
+ this.anchorCell = cell
+ this.extendCell = null // Reset extend tracking
+ }
+ this.selectCell(cell)
+ this.positionFillHandle()
+ }
+
+ onCellBlur() {
+ // Delay hiding to allow for fill handle clicks
+ // Use longer delay and check if mouse is over fill handle
+ setTimeout(() => {
+ if (this.isDraggingFillHandle || this.isMouseOverFillHandle) return
+ if (this.cellTargets.includes(document.activeElement)) return
+
+ this.focusedCell = null
+ this.hideFillHandle()
+ }, 150)
+ }
+
+ onCellDoubleClick(event) {
+ const cell = event.target
+ this.enterEditMode(cell)
+ }
+
+ onCellMouseDown(event) {
+ const cell = event.target
+
+ if (event.shiftKey && this.anchorCell) {
+ event.preventDefault()
+ this.selectRange(this.anchorCell, cell)
+ } else {
+ this.clearSelection()
+ this.anchorCell = cell
+ this.selectCell(cell)
+ this.isSelecting = true
+ }
+ }
+
+ onCellMouseEnter(event) {
+ if (!this.isSelecting || !this.anchorCell) return
+ const cell = event.target
+ this.selectRange(this.anchorCell, cell)
+ }
+
+ selectCell(cell) {
+ cell.classList.add('selected')
+ this.selectedCells.add(cell)
+ this.updateStatusBar()
+ this.updateSelectionOverlay()
+ }
+
+ deselectCell(cell) {
+ cell.classList.remove('selected')
+ this.selectedCells.delete(cell)
+ }
+
+ clearSelection() {
+ this.selectedCells.forEach(cell => this.deselectCell(cell))
+ this.selectedCells.clear()
+ this.updateStatusBar()
+ this.hideSelectionOverlay()
+ }
+
+ selectRange(startCell, endCell) {
+ const startCoords = this.getCellCoords(startCell)
+ const endCoords = this.getCellCoords(endCell)
+
+ const minRow = Math.min(startCoords.row, endCoords.row)
+ const maxRow = Math.max(startCoords.row, endCoords.row)
+ const minCol = Math.min(startCoords.col, endCoords.col)
+ const maxCol = Math.max(startCoords.col, endCoords.col)
+
+ // Store selection bounds
+ this.selectionBounds = { minRow, maxRow, minCol, maxCol }
+
+ this.clearSelection()
+
+ this.cellTargets.forEach(cell => {
+ const coords = this.getCellCoords(cell)
+ if (coords.row >= minRow && coords.row <= maxRow &&
+ coords.col >= minCol && coords.col <= maxCol) {
+ cell.classList.add('selected')
+ this.selectedCells.add(cell)
+ }
+ })
+
+ this.updateStatusBar()
+ this.updateSelectionOverlay()
+ }
+
+ // Selection overlay - draws a single border around the entire selection
+ createSelectionOverlay() {
+ if (this.selectionOverlay) return
+
+ this.selectionOverlay = document.createElement('div')
+ this.selectionOverlay.className = 'selection-overlay'
+ this.element.appendChild(this.selectionOverlay)
+ }
+
+ updateSelectionOverlay() {
+ if (this.selectedCells.size === 0) {
+ this.hideSelectionOverlay()
+ return
+ }
+
+ this.createSelectionOverlay()
+
+ // Get bounding rect of all selected cells
+ const cells = Array.from(this.selectedCells)
+ const containerRect = this.element.getBoundingClientRect()
+
+ let minLeft = Infinity, minTop = Infinity
+ let maxRight = -Infinity, maxBottom = -Infinity
+
+ cells.forEach(cell => {
+ const rect = cell.getBoundingClientRect()
+ minLeft = Math.min(minLeft, rect.left)
+ minTop = Math.min(minTop, rect.top)
+ maxRight = Math.max(maxRight, rect.right)
+ maxBottom = Math.max(maxBottom, rect.bottom)
+ })
+
+ // Position overlay relative to container
+ this.selectionOverlay.style.display = 'block'
+ this.selectionOverlay.style.left = `${minLeft - containerRect.left}px`
+ this.selectionOverlay.style.top = `${minTop - containerRect.top}px`
+ this.selectionOverlay.style.width = `${maxRight - minLeft}px`
+ this.selectionOverlay.style.height = `${maxBottom - minTop}px`
+ }
+
+ hideSelectionOverlay() {
+ if (this.selectionOverlay) {
+ this.selectionOverlay.style.display = 'none'
+ }
+ }
+
+ selectAll(event) {
+ event.preventDefault()
+ this.clearSelection()
+ this.cellTargets.forEach(cell => this.selectCell(cell))
+ }
+
+ // ==================== Keyboard Events ====================
+
+ // Handle keys not supported by Stimulus keyboard event filters
+ handleKeydown(event) {
+ const cell = event.target
+
+ // Enter key - toggle edit mode or move down if already editing
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ if (this.editingCell === cell) {
+ // Exit edit mode and move down
+ this.exitEditMode()
+ this.navigate('down')
+ } else {
+ // Enter edit mode
+ this.enterEditMode(cell)
+ }
+ return
+ }
+
+ // Escape key - exit edit mode and revert changes
+ if (event.key === 'Escape') {
+ if (this.editingCell) {
+ event.preventDefault()
+ this.exitEditMode(true) // true = revert to original value
+ }
+ return
+ }
+
+ // If in edit mode, allow normal typing
+ if (this.editingCell === cell) {
+ return
+ }
+
+ // Delete/Backspace - clear selected cells (only in selection mode)
+ if (event.key === 'Delete' || event.key === 'Backspace') {
+ event.preventDefault()
+ this.clearCells(event)
+ return
+ }
+
+ // Start editing on any printable character
+ if (event.key.length === 1 && !event.ctrlKey && !event.metaKey) {
+ this.enterEditMode(cell, true) // true = clear existing value
+ }
+ }
+
+ enterEditMode(cell) {
+ // Exit any existing edit mode
+ if (this.editingCell && this.editingCell !== cell) {
+ this.exitEditMode()
+ }
+
+ this.editingCell = cell
+ this.editingCellOriginalValue = cell.value // Store value for Escape revert
+ cell.readOnly = false
+ cell.classList.add('editing')
+ // Select all text for easy replacement
+ cell.select()
+ }
+
+ exitEditMode(revert = false) {
+ if (!this.editingCell) return
+
+ // Revert value if Escape was pressed
+ if (revert && this.editingCellOriginalValue !== undefined) {
+ this.editingCell.value = this.editingCellOriginalValue
+ }
+
+ this.editingCell.readOnly = true
+ this.editingCell.classList.remove('editing')
+ this.editingCell = null
+ this.editingCellOriginalValue = undefined
+ }
+
+ // ==================== Keyboard Navigation ====================
+
+ navigateUp(event) {
+ if (this.editingCell) return // Allow cursor movement in edit mode
+ event.preventDefault()
+ this.navigate('up')
+ }
+
+ navigateDown(event) {
+ if (this.editingCell) return
+ event.preventDefault()
+ this.navigate('down')
+ }
+
+ navigateLeft(event) {
+ // Tab always navigates (exits edit mode), arrow keys only in selection mode
+ if (this.editingCell && event.key !== 'Tab') return
+ event.preventDefault()
+ this.navigate('left')
+ }
+
+ navigateRight(event) {
+ // Tab always navigates (exits edit mode), arrow keys only in selection mode
+ if (this.editingCell && event.key !== 'Tab') return
+ event.preventDefault()
+ this.navigate('right')
+ }
+
+ selectUp(event) {
+ if (this.editingCell) return
+ event.preventDefault()
+ this.extendSelection('up')
+ }
+
+ selectDown(event) {
+ if (this.editingCell) return
+ event.preventDefault()
+ this.extendSelection('down')
+ }
+
+ selectLeft(event) {
+ if (this.editingCell) return
+ event.preventDefault()
+ this.extendSelection('left')
+ }
+
+ selectRight(event) {
+ if (this.editingCell) return
+ event.preventDefault()
+ this.extendSelection('right')
+ }
+
+ navigate(direction) {
+ const activeCell = document.activeElement
+ if (!this.cellTargets.includes(activeCell)) return
+
+ // Exit edit mode when navigating
+ this.exitEditMode()
+
+ const coords = this.getCellCoords(activeCell)
+ const targetCell = this.getAdjacentCell(coords, direction)
+
+ if (targetCell) {
+ this.clearSelection()
+ this.anchorCell = targetCell
+ this.extendCell = null // Reset extend tracking
+ targetCell.focus()
+ this.selectCell(targetCell)
+ }
+ }
+
+ extendSelection(direction) {
+ const activeCell = document.activeElement
+ if (!this.cellTargets.includes(activeCell)) return
+
+ // Use extendCell if we're continuing a selection, otherwise start from active cell
+ const fromCell = this.extendCell || activeCell
+ const coords = this.getCellCoords(fromCell)
+ const targetCell = this.getAdjacentCell(coords, direction)
+
+ if (targetCell) {
+ // Set anchor if not already set
+ if (!this.anchorCell) {
+ this.anchorCell = activeCell
+ }
+ // Track the extend endpoint
+ this.extendCell = targetCell
+ // Select range from anchor to new extend point
+ this.selectRange(this.anchorCell, targetCell)
+ }
+ }
+
+ getAdjacentCell(coords, direction) {
+ let targetRow = coords.row
+ let targetCol = coords.col
+
+ switch (direction) {
+ case 'up': targetRow--; break
+ case 'down': targetRow++; break
+ case 'left': targetCol--; break
+ case 'right': targetCol++; break
+ }
+
+ return this.getCellAt(targetRow, targetCol)
+ }
+
+ // ==================== Copy / Paste / Fill ====================
+
+ copy(event) {
+ event?.preventDefault()
+ if (this.selectedCells.size === 0) return
+
+ // Store values from selected cells
+ this.copiedValues = Array.from(this.selectedCells).map(cell => ({
+ value: cell.value,
+ coords: this.getCellCoords(cell)
+ }))
+
+ // Sort by row then column for proper paste order
+ this.copiedValues.sort((a, b) => {
+ if (a.coords.row !== b.coords.row) return a.coords.row - b.coords.row
+ return a.coords.col - b.coords.col
+ })
+
+ // Also copy to clipboard
+ if (this.selectedCells.size === 1) {
+ const value = Array.from(this.selectedCells)[0].value
+ navigator.clipboard?.writeText(value)
+ } else {
+ // For multiple cells, create tab-separated values
+ const rows = new Map()
+ this.copiedValues.forEach(({ value, coords }) => {
+ if (!rows.has(coords.row)) rows.set(coords.row, [])
+ rows.get(coords.row).push(value)
+ })
+ const tsv = Array.from(rows.values()).map(row => row.join('\t')).join('\n')
+ navigator.clipboard?.writeText(tsv)
+ }
+
+ this.showNotification(`${this.copiedValues.length} cell(s) copied`)
+ }
+
+ paste(event) {
+ event?.preventDefault()
+ if (this.copiedValues.length === 0) return
+ if (this.selectedCells.size === 0) return
+
+ const targetCells = Array.from(this.selectedCells).sort((a, b) => {
+ const coordsA = this.getCellCoords(a)
+ const coordsB = this.getCellCoords(b)
+ if (coordsA.row !== coordsB.row) return coordsA.row - coordsB.row
+ return coordsA.col - coordsB.col
+ })
+
+ // If single value copied, paste to all selected cells
+ if (this.copiedValues.length === 1) {
+ const value = this.copiedValues[0].value
+ targetCells.forEach(cell => {
+ this.setCellValue(cell, value)
+ })
+ this.showNotification(`Pasted to ${targetCells.length} cell(s)`)
+ return
+ }
+
+ // If multiple values, try to match the pattern
+ const startCell = targetCells[0]
+ const startCoords = this.getCellCoords(startCell)
+ const copyStartCoords = this.copiedValues[0].coords
+
+ this.copiedValues.forEach(copied => {
+ const rowOffset = copied.coords.row - copyStartCoords.row
+ const colOffset = copied.coords.col - copyStartCoords.col
+ const targetCell = this.getCellAt(startCoords.row + rowOffset, startCoords.col + colOffset)
+ if (targetCell) {
+ this.setCellValue(targetCell, copied.value)
+ }
+ })
+
+ this.showNotification(`Pasted ${this.copiedValues.length} cell(s)`)
+ }
+
+ fillDown(event) {
+ event?.preventDefault()
+ if (this.selectedCells.size < 2) return
+
+ // Get selected cells sorted by row
+ const cells = Array.from(this.selectedCells).sort((a, b) => {
+ const coordsA = this.getCellCoords(a)
+ const coordsB = this.getCellCoords(b)
+ if (coordsA.col !== coordsB.col) return coordsA.col - coordsB.col
+ return coordsA.row - coordsB.row
+ })
+
+ // Group by column
+ const columnGroups = new Map()
+ cells.forEach(cell => {
+ const col = this.getCellCoords(cell).col
+ if (!columnGroups.has(col)) {
+ columnGroups.set(col, [])
+ }
+ columnGroups.get(col).push(cell)
+ })
+
+ // Fill each column with the first value in that column
+ let filledCount = 0
+ columnGroups.forEach(columnCells => {
+ if (columnCells.length < 2) return
+ const sourceValue = columnCells[0].value
+ for (let i = 1; i < columnCells.length; i++) {
+ this.setCellValue(columnCells[i], sourceValue)
+ filledCount++
+ }
+ })
+
+ if (filledCount > 0) {
+ this.showNotification(`Filled ${filledCount} cell(s)`)
+ }
+ }
+
+ clearCells(event) {
+ if (this.selectedCells.size > 1) {
+ event.preventDefault()
+ this.selectedCells.forEach(cell => {
+ this.setCellValue(cell, '')
+ })
+ this.showNotification(`Cleared ${this.selectedCells.size} cell(s)`)
+ }
+ }
+
+ setCellValue(cell, value, updateOriginal = false) {
+ cell.value = value
+ // Optionally update the original value so cell doesn't appear dirty
+ if (updateOriginal) {
+ cell.dataset.originalValue = value
+ }
+ cell.dispatchEvent(new Event('input', { bubbles: true }))
+ }
+
+ // ==================== Dirty State Tracking ====================
+
+ markDirty(event) {
+ const input = event.target
+ const originalValue = input.dataset.originalValue ?? ''
+ const currentValue = input.value
+
+ if (currentValue !== originalValue) {
+ this.dirtyInputs.add(input)
+ } else {
+ this.dirtyInputs.delete(input)
+ }
+
+ this.updateSaveButton()
+ }
+
+ updateSaveButton() {
+ if (!this.hasSaveButtonTarget) return
+ // Keep save button always enabled to allow saving
+ }
+
+ handleBeforeUnload(event) {
+ if (this.dirtyInputs.size > 0) {
+ event.preventDefault()
+ event.returnValue = ''
+ }
+ }
+
+ // ==================== Helpers ====================
+
+ getCellCoords(cell) {
+ return {
+ row: parseInt(cell.dataset.row, 10),
+ col: parseInt(cell.dataset.col, 10)
+ }
+ }
+
+ getCellAt(row, col) {
+ return this.cellTargets.find(cell => {
+ const coords = this.getCellCoords(cell)
+ return coords.row === row && coords.col === col
+ })
+ }
+
+ updateStatusBar() {
+ if (!this.hasStatusBarTarget) return
+ const count = this.selectedCells.size
+ if (count > 1) {
+ this.statusBarTarget.textContent = `${count} cells selected`
+ this.statusBarTarget.classList.remove('hidden')
+ } else {
+ this.statusBarTarget.classList.add('hidden')
+ }
+ }
+
+ showNotification(message) {
+ // Use existing toast/notification system if available
+ if (window.Spree?.Admin?.showNotification) {
+ window.Spree.Admin.showNotification(message)
+ return
+ }
+
+ // Fallback: update status bar
+ if (this.hasStatusBarTarget) {
+ this.statusBarTarget.textContent = message
+ this.statusBarTarget.classList.remove('hidden')
+ setTimeout(() => {
+ this.updateStatusBar()
+ }, 2000)
+ }
+ }
+
+ // ==================== Getters ====================
+
+ get isDirty() {
+ return this.dirtyInputs.size > 0
+ }
+}
diff --git a/admin/app/views/spree/admin/price_list_products/_table_row.html.erb b/admin/app/views/spree/admin/price_list_products/_table_row.html.erb
new file mode 100644
index 0000000000..bc482c59e7
--- /dev/null
+++ b/admin/app/views/spree/admin/price_list_products/_table_row.html.erb
@@ -0,0 +1,28 @@
+<tr id="<%= dom_id product %>" data-controller="row-link">
+ <td class="pr-0 w-5">
+ <div class="custom-control form-checkbox ml-1">
+ <%= check_box_tag "ids[]", product.id, false,
+ class: "custom-control-input",
+ id: "ids_#{product.id}",
+ data: { media_form_target: "checkbox", action: "change->media-form#showDeleteButton" } %>
+ <label class="custom-control-label" for="ids_<%= product.id %>"><span></span></label>
+ </div>
+ </td>
+ <td scope="row" class="w-40 py-0 whitespace-normal" data-action="click->row-link#openLink">
+ <%= link_to spree.edit_admin_product_path(product), class: 'flex items-center w-full no-underline h-full py-2', data: { row_link_target: :link, 'turbo-frame': '_top' } do %>
+ <div class="mr-6">
+ <%= render 'spree/admin/shared/product_image', object: product %>
+ </div>
+ <span class="text-gray-900 font-medium">
+ <%= product.name %>
+ </span>
+ <% end %>
+ </td>
+ <%= render 'spree/admin/products/product_status', product: product %>
+ <td class="w-20 cursor-pointer whitespace-normal" data-action="click->row-link#openLink">
+ <%= display_inventory(product) %>
+ </td>
+ <td class="w-10 cursor-pointer" data-action="click->row-link#openLink">
+ <%= display_admin_price(product) %>
+ </td>
+</tr>
diff --git a/admin/app/views/spree/admin/price_list_products/bulk_destroy.turbo_stream.erb b/admin/app/views/spree/admin/price_list_products/bulk_destroy.turbo_stream.erb
new file mode 100644
index 0000000000..1895764b43
--- /dev/null
+++ b/admin/app/views/spree/admin/price_list_products/bulk_destroy.turbo_stream.erb
@@ -0,0 +1,3 @@
+<% params[:ids]&.each do |id| %>
+ <%= turbo_stream.remove("product_#{id}") %>
+<% end %>
\ No newline at end of file
diff --git a/admin/app/views/spree/admin/price_list_products/bulk_new.html.erb b/admin/app/views/spree/admin/price_list_products/bulk_new.html.erb
new file mode 100644
index 0000000000..9f60839ee6
--- /dev/null
+++ b/admin/app/views/spree/admin/price_list_products/bulk_new.html.erb
@@ -0,0 +1,29 @@
+<%= turbo_frame_tag :drawer do %>
+ <div data-controller="search-picker">
+ <%= drawer_header(Spree.t(:add_products)) %>
+
+ <div class="drawer-body border-b">
+ <%= form_with url: spree.search_admin_products_path, method: :post, data: { controller: 'auto-submit' } do |form| %>
+ <%= form.hidden_field :omit_ids, value: @price_list.products.pluck(:id).join(',') %>
+ <%= form.search_field :q, value: params[:q], class: 'form-input w-full', placeholder: Spree.t(:search_products), data: { search_picker_target: :search, action: 'auto-submit#submit' }, autofocus: true %>
+ <% end %>
+ </div>
+
+ <%= form_with url: spree.bulk_create_admin_price_list_products_path(@parent), method: :post do |form| %>
+ <%= form.hidden_field :currency, value: @currency %>
+
+ <div class="drawer-body">
+ <div id="products_search_results" class="search-results overflow-y-auto max-h-96">
+ <p class="text-gray-500 text-center py-8">
+ <%= Spree.t(:type_to_search_products) %>
+ </p>
+ </div>
+ </div>
+
+ <div class="drawer-footer">
+ <%= turbo_save_button_tag Spree.t(:add_selected), class: 'btn btn-primary', disabled: true, data: { search_picker_target: :submit } %>
+ <%= drawer_discard_button %>
+ </div>
+ <% end %>
+ </div>
+<% end %>
diff --git a/admin/app/views/spree/admin/price_list_products/index.html.erb b/admin/app/views/spree/admin/price_list_products/index.html.erb
new file mode 100644
index 0000000000..a036d87d35
--- /dev/null
+++ b/admin/app/views/spree/admin/price_list_products/index.html.erb
@@ -0,0 +1,56 @@
+<%= turbo_frame_tag :price_list_products do %>
+ <div class="card mb-6" data-controller="media-form" data-media-form-delete-url-value="<%= spree.bulk_destroy_admin_price_list_products_path(@parent) %>">
+ <div class="card-header flex justify-between items-center">
+ <h5 class="card-title">
+ <%= Spree.t(:products) %>
+ <span class="badge badge-info ml-2" id="products_count"><%= @price_list.products.distinct.count %></span>
+ </h5>
+ <div class="flex gap-2">
+ <button type="button"
+ data-media-form-target="deleteButton"
+ data-action="media-form#deleteSelected"
+ class="btn btn-sm btn-danger btn-outline hidden">
+ <%= icon('trash') %>
+ <%= Spree.t(:delete_selected) %>
+ </button>
+ <%= link_to Spree.t(:add_products),
+ spree.bulk_new_admin_price_list_products_path(@price_list),
+ class: 'btn btn-sm btn-light',
+ data: { action: 'drawer#open', turbo_frame: :drawer } %>
+ <% if @price_list.prices.any? %>
+ <%= link_to Spree.t(:edit_prices),
+ spree.edit_prices_admin_price_list_path(@price_list),
+ class: 'btn btn-sm btn-primary',
+ data: { turbo_frame: '_top' } %>
+ <% end %>
+ </div>
+ </div>
+
+ <% if @collection.any? %>
+ <div class="table-responsive">
+ <table class="table" id="listing_price_list_products">
+ <thead>
+ <tr>
+ <th scope="col" class="pr-0 w-5"></th>
+ <th scope="col"><%= Spree.t(:name) %></th>
+ <th scope="col" class="text-center"><%= Spree.t(:status) %></th>
+ <th scope="col"><%= Spree.t(:inventory) %></th>
+ <th scope="col"><%= Spree.t(:price) %></th>
+ </tr>
+ </thead>
+ <tbody>
+ <%= render partial: 'table_row', collection: @collection, as: :product %>
+ </tbody>
+ </table>
+ </div>
+
+ <%= render partial: 'spree/admin/shared/index_table_options', locals: { collection: @collection } %>
+ <% else %>
+ <div class="card-body">
+ <p class="text-gray-500 text-center py-8">
+ <%= Spree.t(:no_products_in_price_list) %>
+ </p>
+ </div>
+ <% end %>
+ </div>
+<% end %>
diff --git a/admin/app/views/spree/admin/price_lists/_form.html.erb b/admin/app/views/spree/admin/price_lists/_form.html.erb
new file mode 100644
index 0000000000..14233b6d7d
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/_form.html.erb
@@ -0,0 +1,8 @@
+<div class="card mb-6">
+ <div class="card-body">
+ <%= f.spree_text_field :name, required: true, autofocus: true %>
+ <%= f.spree_text_area :description %>
+ <%= f.spree_date_field :starts_at %>
+ <%= f.spree_date_field :ends_at %>
+ </div>
+</div>
\ No newline at end of file
diff --git a/admin/app/views/spree/admin/price_lists/_table_header.html.erb b/admin/app/views/spree/admin/price_lists/_table_header.html.erb
new file mode 100644
index 0000000000..27dc1e3a9a
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/_table_header.html.erb
@@ -0,0 +1,6 @@
+<tr>
+ <th scope="col"><%= sort_link @search, :name, Spree.t(:name) %></th>
+ <th scope="col"><%= Spree.t(:status) %></th>
+ <th scope="col"><%= Spree.t(:starts_at) %></th>
+ <th scope="col"><%= Spree.t(:ends_at) %></th>
+</tr>
diff --git a/admin/app/views/spree/admin/price_lists/_table_row.html.erb b/admin/app/views/spree/admin/price_lists/_table_row.html.erb
new file mode 100644
index 0000000000..23226fa1e5
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/_table_row.html.erb
@@ -0,0 +1,24 @@
+<tr id="<%= spree_dom_id price_list %>" data-controller="row-link">
+ <td class="w-30 p-0">
+ <%= link_to price_list.name, spree.admin_price_list_path(price_list), class: 'font-bold block py-2 px-4 w-full h-full', data: { row_link_target: :link, turbo_frame: '_top' } %>
+ </td>
+ <td class="w-15 cursor-pointer" data-action="click->row-link#openLink">
+ <span class="badge badge-<%= price_list.active? ? 'success' : (price_list.scheduled? ? 'info' : 'light') %>">
+ <%= price_list.status.humanize %>
+ </span>
+ </td>
+ <td class="w-20 cursor-pointer" data-action="click->row-link#openLink">
+ <% if price_list.starts_at.present? %>
+ <%= spree_date(price_list.starts_at) %>
+ <% else %>
+ <span class="text-gray-400">-</span>
+ <% end %>
+ </td>
+ <td class="w-20 cursor-pointer" data-action="click->row-link#openLink">
+ <% if price_list.ends_at.present? %>
+ <%= spree_date(price_list.ends_at) %>
+ <% else %>
+ <span class="text-gray-400">-</span>
+ <% end %>
+ </td>
+</tr>
diff --git a/admin/app/views/spree/admin/price_lists/edit.html.erb b/admin/app/views/spree/admin/price_lists/edit.html.erb
new file mode 100644
index 0000000000..520a6f47c2
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/edit.html.erb
@@ -0,0 +1 @@
+<%= render 'spree/admin/shared/edit_resource' %>
\ No newline at end of file
diff --git a/admin/app/views/spree/admin/price_lists/edit_prices.html.erb b/admin/app/views/spree/admin/price_lists/edit_prices.html.erb
new file mode 100644
index 0000000000..407af09b24
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/edit_prices.html.erb
@@ -0,0 +1,121 @@
+<% content_for :page_title do %>
+ <%= Spree.t(:edit_prices) %> - <%= @price_list.name %>
+<% end %>
+
+<% content_for :page_actions do %>
+ <%= link_to Spree.t(:back), edit_admin_price_list_path(@price_list), class: 'btn btn-secondary' %>
+<% end %>
+
+<%= form_with model: [:admin, @price_list],
+ method: :patch,
+ data: {
+ controller: 'bulk-editor',
+ action: 'keydown.ctrl+a->bulk-editor#selectAll keydown.meta+a->bulk-editor#selectAll'
+ } do |f| %>
+
+ <div class="card mb-6">
+ <div class="card-header flex justify-between items-center">
+ <div class="flex items-center gap-4">
+ <h5 class="card-title"><%= Spree.t(:prices) %> (<%= @currency %>)</h5>
+ <span class="text-sm text-gray-500 hidden" data-bulk-editor-target="statusBar"></span>
+ </div>
+ <div class="flex gap-2 items-center">
+ <div class="text-xs text-gray-400 hidden lg:block">
+ <kbd class="px-1 py-0.5 bg-gray-100 rounded"><%= icon 'command', class: 'inline w-3 h-3' %>C</kbd> copy
+ <kbd class="px-1 py-0.5 bg-gray-100 rounded ml-2"><%= icon 'command', class: 'inline w-3 h-3' %>V</kbd> paste
+ <kbd class="px-1 py-0.5 bg-gray-100 rounded ml-2"><%= icon 'command', class: 'inline w-3 h-3' %>D</kbd> fill down
+ </div>
+ <%= select_tag :currency,
+ options_for_select(current_store.supported_currencies_list, @currency),
+ class: 'form-select',
+ onchange: "window.Turbo.visit('#{spree.edit_prices_admin_price_list_path(@price_list)}?currency=' + this.value)" %>
+ </div>
+ </div>
+
+ <% if @prices.any? %>
+ <%
+ # Group prices by product for display
+ prices_by_product = @prices.group_by { |price| price.variant.product }
+ row_index = 0
+ %>
+ <div class="overflow-x-auto">
+ <table class="w-full" data-bulk-editor-target="table">
+ <thead class="bg-gray-50 border-b border-gray-200">
+ <tr>
+ <th class="px-4 py-3 text-left text-sm font-medium text-gray-600"><%= Spree.t(:title) %></th>
+ <th class="px-4 py-3 text-left text-sm font-medium text-gray-600"><%= Spree.t(:sku) %></th>
+ <th class="px-4 py-3 text-left text-sm font-medium text-gray-600 w-36"><%= Spree.t(:price) %></th>
+ <th class="px-4 py-3 text-left text-sm font-medium text-gray-600 w-36"><%= Spree.t(:compare_at_price) %></th>
+ </tr>
+ </thead>
+ <tbody>
+ <% prices_by_product.each do |product, prices| %>
+ <%# Product header row %>
+ <tr class="bg-gray-50 border-t border-b border-gray-200">
+ <td colspan="4" class="px-4 py-3">
+ <div class="flex items-center gap-3">
+ <%= render 'spree/admin/shared/product_image', object: product, variant: :mini %>
+ <span class="font-medium text-gray-900"><%= product.name %></span>
+ </div>
+ </td>
+ </tr>
+ <%# Variant rows %>
+ <% prices.each do |price| %>
+ <%= f.fields_for :prices, price, index: row_index do |pf| %>
+ <tr data-bulk-editor-target="row">
+ <td class="pl-14 pr-4 py-2 text-sm text-gray-600"><%= price.variant.options_text.presence %></td>
+ <td class="px-4 py-2 text-sm text-gray-400 font-mono"><%= price.variant.sku %></td>
+ <td class="p-0">
+ <%= pf.hidden_field :id %>
+ <%= pf.hidden_field :variant_id %>
+ <%= pf.hidden_field :currency %>
+ <%= pf.number_field :amount,
+ step: 0.01,
+ placeholder: '0.00',
+ class: 'w-full px-4 py-2 focus:outline-none text-right tabular-nums',
+ data: {
+ bulk_editor_target: 'cell',
+ row: row_index,
+ col: 0,
+ action: bulk_editor_cell_actions,
+ original_value: price.amount
+ } %>
+ </td>
+ <td class="p-0">
+ <%= pf.number_field :compare_at_amount,
+ step: 0.01,
+ placeholder: '0.00',
+ class: 'w-full px-4 py-2 focus:outline-none text-right tabular-nums',
+ data: {
+ bulk_editor_target: 'cell',
+ row: row_index,
+ col: 1,
+ action: bulk_editor_cell_actions,
+ original_value: price.compare_at_amount
+ } %>
+ </td>
+ </tr>
+ <% row_index += 1 %>
+ <% end %>
+ <% end %>
+ <% end %>
+ </tbody>
+ </table>
+ </div>
+ <% else %>
+ <div class="p-8 text-center text-gray-500">
+ <p class="mb-4"><%= Spree.t(:no_products_in_price_list) %></p>
+ <%= link_to Spree.t(:add_products), spree.admin_price_list_path(@price_list), class: 'btn btn-primary' %>
+ </div>
+ <% end %>
+ </div>
+
+ <% if @prices.any? %>
+ <div class="flex gap-3 justify-end">
+ <%= link_to Spree.t(:cancel), spree.admin_price_list_path(@price_list), class: 'btn btn-secondary' %>
+ <%= f.submit Spree.t(:save_changes),
+ class: 'btn btn-primary',
+ data: { bulk_editor_target: 'saveButton' } %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/admin/app/views/spree/admin/price_lists/index.html.erb b/admin/app/views/spree/admin/price_lists/index.html.erb
new file mode 100644
index 0000000000..bb038a30ad
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/index.html.erb
@@ -0,0 +1,12 @@
+<% content_for :page_title do %>
+ <%= Spree.t(:price_lists) %>
+<% end %>
+
+<% content_for :page_actions do %>
+ <%= render_admin_partials(:price_lists_actions_partials) %>
+ <%= link_to_with_icon 'plus', Spree.t(:new_price_list), new_object_url, class: 'btn btn-primary' if can?(:create, Spree::PriceList) %>
+<% end %>
+
+<%= render_admin_partials(:price_lists_header_partials) %>
+
+<%= render 'spree/admin/shared/index_table', sortable: true %>
diff --git a/admin/app/views/spree/admin/price_lists/new.html.erb b/admin/app/views/spree/admin/price_lists/new.html.erb
new file mode 100644
index 0000000000..0fd3668cab
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/new.html.erb
@@ -0,0 +1 @@
+<%= render 'spree/admin/shared/new_resource' %>
\ No newline at end of file
diff --git a/admin/app/views/spree/admin/price_lists/show.html.erb b/admin/app/views/spree/admin/price_lists/show.html.erb
new file mode 100644
index 0000000000..7efcef6064
--- /dev/null
+++ b/admin/app/views/spree/admin/price_lists/show.html.erb
@@ -0,0 +1,14 @@
+<%= content_for :page_title do %>
+ <%= page_header_back_button(spree.admin_price_lists_path) %>
+ <%= @price_list.name %>
+<% end %>
+
+<div class="grid grid-cols-12 gap-6">
+ <div class="col-span-12 lg:col-span-8">
+ <%= turbo_frame_tag :price_list_products, src: spree.admin_price_list_products_path(@price_list) %>
+ </div>
+
+ <div class="col-span-12 lg:col-span-4">
+
+ </div>
+</div>
\ No newline at end of file
diff --git a/admin/config/initializers/spree_admin_navigation.rb b/admin/config/initializers/spree_admin_navigation.rb
index 7240bf376a..bd9139dda5 100644
--- a/admin/config/initializers/spree_admin_navigation.rb
+++ b/admin/config/initializers/spree_admin_navigation.rb
@@ -94,11 +94,19 @@ Rails.application.config.after_initialize do
icon: 'package',
position: 30,
if: -> { can?(:manage, Spree::Product) } do |products|
+
+ # Price Lists
+ products.add :price_lists,
+ label: :price_lists,
+ url: :admin_price_lists_path,
+ position: 10,
+ active: -> { %w[price_lists price_rules].include?(controller_name) },
+ if: -> { can?(:manage, Spree::PriceList) }
# Stock
products.add :stock,
label: :stock,
url: :admin_stock_items_path,
- position: 10,
+ position: 20,
active: -> { %w[stock_items stock_transfers].include?(controller_name) },
if: -> { can?(:manage, Spree::StockItem) || can?(:manage, Spree::StockTransfer) }
@@ -106,7 +114,7 @@ Rails.application.config.after_initialize do
products.add :taxonomies,
label: :taxonomies,
url: :admin_taxonomies_path,
- position: 20,
+ position: 30,
active: -> { %w[taxonomies taxons].include?(controller_name) },
if: -> { can?(:manage, Spree::Taxonomy) && can?(:manage, Spree::Taxon) }
@@ -114,7 +122,7 @@ Rails.application.config.after_initialize do
products.add :options,
label: :options,
url: :admin_option_types_path,
- position: 30,
+ position: 40,
active: -> { %w[option_types option_values].include?(controller_name) },
if: -> { can?(:manage, Spree::OptionType) }
@@ -122,7 +130,7 @@ Rails.application.config.after_initialize do
products.add :properties,
label: :properties,
url: :admin_properties_path,
- position: 40,
+ position: 50,
if: -> { can?(:manage, Spree::Property) && Spree::Config.product_properties_enabled }
end
diff --git a/admin/config/routes.rb b/admin/config/routes.rb
index f100eaa997..9959df9fcf 100644
--- a/admin/config/routes.rb
+++ b/admin/config/routes.rb
@@ -32,6 +32,20 @@ Spree::Core::Engine.add_routes do
# stock
resources :stock_items, only: [:index, :update, :destroy]
resources :stock_transfers, except: [:edit, :update]
+ # price lists
+ resources :price_lists do
+ resources :price_rules, only: [:new, :create, :edit, :update, :destroy]
+ resources :products, only: [:index], controller: 'price_list_products' do
+ collection do
+ get :bulk_new
+ post :bulk_create
+ delete :bulk_destroy
+ end
+ end
+ member do
+ get :edit_prices
+ end
+ end
# taxonomies and taxons
resources :taxonomies do
resources :taxons do
diff --git a/admin/lib/spree/admin/engine.rb b/admin/lib/spree/admin/engine.rb
index 3fcb33877b..e43488f769 100644
--- a/admin/lib/spree/admin/engine.rb
+++ b/admin/lib/spree/admin/engine.rb
@@ -53,6 +53,8 @@ module Spree
:posts_actions_partials,
:posts_filters_partials,
:posts_header_partials,
+ :price_lists_actions_partials,
+ :price_lists_header_partials,
:product_dropdown_partials,
:product_page_title_partials,
:product_form_partials,
diff --git a/admin/spec/controllers/spree/admin/price_list_products_controller_spec.rb b/admin/spec/controllers/spree/admin/price_list_products_controller_spec.rb
new file mode 100644
index 0000000000..43399bb540
--- /dev/null
+++ b/admin/spec/controllers/spree/admin/price_list_products_controller_spec.rb
@@ -0,0 +1,217 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::PriceListProductsController, type: :controller do
+ stub_authorization!
+ render_views
+
+ let(:store) { @default_store }
+ let(:price_list) { create(:price_list, store: store) }
+
+ describe 'GET #index' do
+ subject(:index) { get :index, params: { price_list_id: price_list.id } }
+
+ let(:product1) { create(:product, stores: [store]) }
+ let(:product2) { create(:product, stores: [store]) }
+ let!(:price1) { create(:price, variant: product1.master, price_list: price_list, currency: 'USD', amount: 10.0) }
+ let!(:price2) { create(:price, variant: product2.master, price_list: price_list, currency: 'USD', amount: 20.0) }
+
+ it 'renders the products list' do
+ index
+
+ expect(response).to render_template(:index)
+ end
+
+ it 'assigns the collection' do
+ index
+
+ expect(assigns[:collection]).to contain_exactly(product1, product2)
+ end
+ end
+
+ describe 'GET #bulk_new' do
+ subject(:bulk_new_action) { get :bulk_new, params: { price_list_id: price_list.id } }
+
+ it 'renders the new products drawer' do
+ bulk_new_action
+
+ expect(response).to render_template(:bulk_new)
+ end
+
+ it 'assigns the currency' do
+ bulk_new_action
+
+ expect(assigns[:currency]).to eq(store.default_currency)
+ end
+ end
+
+ describe 'POST #bulk_create' do
+ subject(:bulk_create) { post :bulk_create, params: params }
+
+ let(:product1) { create(:product, stores: [store]) }
+ let(:product2) { create(:product, stores: [store]) }
+ let(:currency) { 'USD' }
+
+ let(:params) do
+ {
+ price_list_id: price_list.id,
+ product_ids: [product1.id, product2.id],
+ currency: currency
+ }
+ end
+
+ it 'creates price records for all variants of the products' do
+ expect { bulk_create }.to change(Spree::Price.for_price_list(price_list), :count).by(2)
+ end
+
+ it 'creates prices with nil amount' do
+ bulk_create
+
+ prices = Spree::Price.for_price_list(price_list)
+ expect(prices.pluck(:amount).uniq).to eq([nil])
+ end
+
+ it 'creates prices with the specified currency' do
+ bulk_create
+
+ prices = Spree::Price.for_price_list(price_list)
+ expect(prices.pluck(:currency).uniq).to eq([currency])
+ end
+
+ it 'redirects to the edit page with a success notice' do
+ bulk_create
+
+ expect(response).to redirect_to(edit_admin_price_list_path(price_list))
+ expect(flash[:notice]).to eq(Spree.t(:products_added))
+ end
+
+ context 'when some products already have prices' do
+ let!(:existing_price) do
+ create(:price, variant: product1.master, price_list: price_list, currency: currency, amount: 99.99)
+ end
+
+ it 'does not overwrite existing prices' do
+ bulk_create
+
+ existing_price.reload
+ expect(existing_price.amount).to eq(99.99)
+ end
+
+ it 'only creates prices for products without existing prices' do
+ expect { bulk_create }.to change(Spree::Price.for_price_list(price_list), :count).by(1)
+ end
+ end
+
+ context 'with product with multiple variants' do
+ let(:product_with_variants) { create(:product, stores: [store]) }
+ let!(:variant1) { create(:variant, product: product_with_variants) }
+ let!(:variant2) { create(:variant, product: product_with_variants) }
+
+ let(:params) do
+ {
+ price_list_id: price_list.id,
+ product_ids: [product_with_variants.id],
+ currency: currency
+ }
+ end
+
+ it 'creates prices for non-master variants only (skips master)' do
+ expect { bulk_create }.to change(Spree::Price.for_price_list(price_list), :count).by(2)
+ end
+ end
+
+ context 'with product with only master variant' do
+ let(:product_master_only) { create(:product, stores: [store]) }
+
+ let(:params) do
+ {
+ price_list_id: price_list.id,
+ product_ids: [product_master_only.id],
+ currency: currency
+ }
+ end
+
+ it 'creates price for master variant' do
+ expect { bulk_create }.to change(Spree::Price.for_price_list(price_list), :count).by(1)
+
+ price = Spree::Price.for_price_list(price_list).last
+ expect(price.variant).to eq(product_master_only.master)
+ end
+ end
+
+ context 'with empty product_ids' do
+ let(:params) { { price_list_id: price_list.id, product_ids: [], currency: currency } }
+
+ it 'does not create any prices' do
+ expect { bulk_create }.not_to change(Spree::Price.for_price_list(price_list), :count)
+ end
+
+ it 'redirects to the edit page' do
+ bulk_create
+
+ expect(response).to redirect_to(edit_admin_price_list_path(price_list))
+ end
+ end
+ end
+
+ describe 'DELETE #bulk_destroy' do
+ subject(:bulk_destroy) { delete :bulk_destroy, params: params }
+
+ let(:product1) { create(:product, stores: [store]) }
+ let(:product2) { create(:product, stores: [store]) }
+ let(:product3) { create(:product, stores: [store]) }
+ let!(:price1) { create(:price, variant: product1.master, price_list: price_list, currency: 'USD', amount: 10.0) }
+ let!(:price2) { create(:price, variant: product2.master, price_list: price_list, currency: 'USD', amount: 20.0) }
+ let!(:price3) { create(:price, variant: product3.master, price_list: price_list, currency: 'USD', amount: 30.0) }
+
+ let(:params) do
+ {
+ price_list_id: price_list.id,
+ ids: [product1.id, product2.id]
+ }
+ end
+
+ it 'removes prices for the selected products' do
+ expect { bulk_destroy }.to change(Spree::Price.for_price_list(price_list), :count).by(-2)
+ end
+
+ it 'does not remove prices for unselected products' do
+ bulk_destroy
+
+ expect(Spree::Price.for_price_list(price_list)).to include(price3)
+ end
+
+ it 'redirects to the edit page with a success notice' do
+ bulk_destroy
+
+ expect(response).to redirect_to(edit_admin_price_list_path(price_list))
+ expect(flash[:notice]).to eq(Spree.t(:products_removed))
+ end
+
+ context 'with product with multiple variants' do
+ let(:product_with_variants) { create(:product, stores: [store]) }
+ let!(:variant1) { create(:variant, product: product_with_variants) }
+ let!(:variant2) { create(:variant, product: product_with_variants) }
+ let!(:variant1_price) { create(:price, variant: variant1, price_list: price_list, currency: 'USD', amount: 10.0) }
+ let!(:variant2_price) { create(:price, variant: variant2, price_list: price_list, currency: 'USD', amount: 20.0) }
+
+ let(:params) do
+ {
+ price_list_id: price_list.id,
+ ids: [product_with_variants.id]
+ }
+ end
+
+ it 'removes prices for all variants of the product' do
+ expect { bulk_destroy }.to change(Spree::Price.for_price_list(price_list), :count).by(-2)
+ end
+ end
+
+ context 'with empty ids' do
+ let(:params) { { price_list_id: price_list.id, ids: [] } }
+
+ it 'does not remove any prices' do
+ expect { bulk_destroy }.not_to change(Spree::Price.for_price_list(price_list), :count)
+ end
+ end
+ end
+end
diff --git a/admin/spec/controllers/spree/admin/price_lists_controller_spec.rb b/admin/spec/controllers/spree/admin/price_lists_controller_spec.rb
new file mode 100644
index 0000000000..a813087df2
--- /dev/null
+++ b/admin/spec/controllers/spree/admin/price_lists_controller_spec.rb
@@ -0,0 +1,147 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::PriceListsController, type: :controller do
+ stub_authorization!
+ render_views
+
+ let(:store) { @default_store }
+ let(:price_list) { create(:price_list, store: store) }
+
+ describe 'GET #index' do
+ subject(:index) { get :index }
+
+ let!(:price_lists) { create_list(:price_list, 3, store: store) }
+
+ it 'renders the list of price lists' do
+ index
+
+ expect(response).to render_template(:index)
+ expect(assigns[:collection]).to contain_exactly(*price_lists)
+ end
+ end
+
+ describe 'GET #edit_prices' do
+ subject(:edit_prices) { get :edit_prices, params: { id: price_list.id, currency: currency } }
+
+ let(:currency) { 'USD' }
+ let(:product) { create(:product, stores: [store]) }
+ let!(:variant) { product.master }
+ let!(:price) { create(:price, variant: variant, price_list: price_list, currency: currency, amount: 10.0) }
+ let!(:other_currency_price) { create(:price, variant: variant, price_list: price_list, currency: 'EUR', amount: 15.0) }
+
+ it 'renders the edit prices page' do
+ edit_prices
+
+ expect(response).to render_template(:edit_prices)
+ end
+
+ it 'assigns prices for the specified currency' do
+ edit_prices
+
+ expect(assigns[:prices]).to include(price)
+ expect(assigns[:prices]).not_to include(other_currency_price)
+ end
+
+ it 'assigns the currency' do
+ edit_prices
+
+ expect(assigns[:currency]).to eq(currency)
+ end
+
+ context 'without currency param' do
+ subject(:edit_prices) { get :edit_prices, params: { id: price_list.id } }
+
+ it 'uses the store default currency' do
+ edit_prices
+
+ expect(assigns[:currency]).to eq(store.default_currency)
+ end
+ end
+ end
+
+ describe 'PUT #update with nested prices_attributes' do
+ subject(:update_price_list) { put :update, params: params }
+
+ let(:product) { create(:product, stores: [store]) }
+ let(:variant) { product.master }
+ let!(:price) { create(:price, variant: variant, price_list: price_list, currency: 'USD', amount: 10.0) }
+
+ let(:params) do
+ {
+ id: price_list.id,
+ price_list: {
+ prices_attributes: {
+ '0' => {
+ id: price.id,
+ variant_id: variant.id,
+ currency: 'USD',
+ amount: '25.99',
+ compare_at_amount: '35.00'
+ }
+ }
+ }
+ }
+ end
+
+ it 'updates the price amount' do
+ update_price_list
+ price.reload
+
+ expect(price.amount).to eq(25.99)
+ end
+
+ it 'updates the compare_at_amount' do
+ update_price_list
+ price.reload
+
+ expect(price.compare_at_amount).to eq(35.00)
+ end
+
+ context 'when updating multiple prices' do
+ let(:product2) { create(:product, stores: [store]) }
+ let(:variant2) { product2.master }
+ let!(:price2) { create(:price, variant: variant2, price_list: price_list, currency: 'USD', amount: 15.0) }
+
+ let(:params) do
+ {
+ id: price_list.id,
+ price_list: {
+ prices_attributes: {
+ '0' => { id: price.id, variant_id: variant.id, currency: 'USD', amount: '25.99' },
+ '1' => { id: price2.id, variant_id: variant2.id, currency: 'USD', amount: '29.99' }
+ }
+ }
+ }
+ end
+
+ it 'updates all prices' do
+ update_price_list
+ price.reload
+ price2.reload
+
+ expect(price.amount).to eq(25.99)
+ expect(price2.amount).to eq(29.99)
+ end
+ end
+
+ context 'when setting amount to blank on existing price' do
+ let(:params) do
+ {
+ id: price_list.id,
+ price_list: {
+ prices_attributes: {
+ '0' => { id: price.id, variant_id: variant.id, currency: 'USD', amount: '' }
+ }
+ }
+ }
+ end
+
+ it 'keeps the price with nil amount' do
+ update_price_list
+ price.reload
+
+ expect(price.amount).to be_nil
+ end
+ end
+ end
+end
diff --git a/core/app/models/spree/price.rb b/core/app/models/spree/price.rb
index 0a06dc2aba..2e0c330c1b 100644
--- a/core/app/models/spree/price.rb
+++ b/core/app/models/spree/price.rb
@@ -20,11 +20,11 @@ module Spree
less_than_or_equal_to: MAXIMUM_AMOUNT
}, if: -> { Spree::Config.allow_empty_price_amount }
- # new behavior
+ # new behavior - prices on a price_list can have nil amounts (placeholder prices)
validates :amount, allow_nil: false, numericality: {
greater_than_or_equal_to: 0,
less_than_or_equal_to: MAXIMUM_AMOUNT
- }, unless: -> { Spree::Config.allow_empty_price_amount }
+ }, unless: -> { Spree::Config.allow_empty_price_amount || price_list_id.present? }
validates :compare_at_amount, allow_nil: true, numericality: {
greater_than_or_equal_to: 0,
@@ -61,7 +61,7 @@ module Spree
end
def amount=(amount)
- self[:amount] = Spree::LocalizedNumber.parse(amount)
+ self[:amount] = amount.blank? ? nil : Spree::LocalizedNumber.parse(amount)
end
def compare_at_money
diff --git a/core/app/models/spree/price_list.rb b/core/app/models/spree/price_list.rb
index 4116a85acb..4eca8a0f2a 100644
--- a/core/app/models/spree/price_list.rb
+++ b/core/app/models/spree/price_list.rb
@@ -3,12 +3,21 @@ module Spree
acts_as_paranoid
acts_as_list scope: :store
+ include Spree::SingleStoreResource
+
MATCH_POLICIES = %w[all any].freeze
belongs_to :store, class_name: 'Spree::Store'
has_many :price_rules, class_name: 'Spree::PriceRule', dependent: :destroy
has_many :prices, class_name: 'Spree::Price', dependent: :destroy_async
+ has_many :variants, -> { where(spree_prices: { deleted_at: nil }) }, through: :prices, source: :variant
+ has_many :products, -> { where(spree_prices: { deleted_at: nil }) }, through: :variants, source: :product
+ alias price_list_products products
+
+ accepts_nested_attributes_for :prices,
+ allow_destroy: true,
+ reject_if: ->(attrs) { attrs['amount'].blank? && attrs['id'].blank? }
validates :name, :store, presence: true
validates :match_policy, presence: true, inclusion: { in: MATCH_POLICIES }
@@ -45,6 +54,10 @@ module Spree
.by_position
end
+ def self.match_policies
+ MATCH_POLICIES.map { |key| [Spree.t(key), key] }
+ end
+
def applicable?(context)
return false unless active_or_scheduled?
return false unless within_date_range?(context.date || Time.current)
@@ -69,6 +82,32 @@ module Spree
active? || scheduled?
end
+ def add_products(product_ids)
+ return if product_ids.blank?
+
+ currencies = store.supported_currencies_list.map(&:iso_code)
+ variant_ids = Spree::Variant.eligible.where(product_id: product_ids).pluck(:id)
+
+ currencies.each do |currency|
+ existing_variant_ids = prices.where(currency: currency).pluck(:variant_id)
+ new_variant_ids = variant_ids - existing_variant_ids
+
+ new_variant_ids.each do |variant_id|
+ prices.create!(
+ variant_id: variant_id,
+ currency: currency,
+ amount: nil
+ )
+ end
+ end
+ end
+
+ def remove_products(product_ids)
+ return if product_ids.blank?
+
+ prices.joins(:variant).where(spree_variants: { product_id: product_ids }).destroy_all
+ end
+
private
def starts_at_before_ends_at
diff --git a/core/app/services/spree/seeds/all.rb b/core/app/services/spree/seeds/all.rb
index 4bc4d10b54..2a60d0cf2a 100644
--- a/core/app/services/spree/seeds/all.rb
+++ b/core/app/services/spree/seeds/all.rb
@@ -4,28 +4,30 @@ module Spree
prepend Spree::ServiceModule::Base
def call
- # GEO
- Countries.call
- States.call
- Zones.call
+ Spree::Events.disable do
+ # GEO
+ Countries.call
+ States.call
+ Zones.call
- # user roles
- Roles.call
+ # user roles
+ Roles.call
- # additional data
- ReturnsEnvironment.call
- ShippingCategories.call
- StoreCreditCategories.call
- TaxCategories.call
- DigitalDelivery.call
+ # additional data
+ ReturnsEnvironment.call
+ ShippingCategories.call
+ StoreCreditCategories.call
+ TaxCategories.call
+ DigitalDelivery.call
- # store & stock location
- Stores.call
- StockLocations.call
- AdminUser.call
+ # store & stock location
+ Stores.call
+ StockLocations.call
+ AdminUser.call
- # add store resources
- PaymentMethods.call
+ # add store resources
+ PaymentMethods.call
+ end
end
end
end
diff --git a/core/config/locales/en.yml b/core/config/locales/en.yml
index 4614d4716b..a576c4c2ba 100644
--- a/core/config/locales/en.yml
+++ b/core/config/locales/en.yml
@@ -651,6 +651,7 @@ en:
add_products: Add Products
add_rule_of_type: Add rule of type
add_section: Add section
+ add_selected: Add Selected
add_selected_products: Add selected products
add_selected_variant: Add selected variant
add_state: Add State
@@ -723,6 +724,9 @@ en:
amount: Amount
analytics: Analytics
and: and
+ and_n_more:
+ one: "...and %{count} more"
+ other: "...and %{count} more"
api_keys: API keys
apis:
platform: Platform API
@@ -1016,6 +1020,7 @@ en:
duplicating: Duplicating
edit: Edit
edit_address: Edit address
+ edit_prices: Edit Prices
edit_refund: Edit refund
editing_resource: Editing %{resource}
editing_rma_reason: Editing RMA Reason
@@ -1436,6 +1441,7 @@ en:
oops: Oops!
no_products_added: No products added
no_products_found: No products found
+ no_products_in_price_list: No products in this price list
no_report_data: No report data
no_resource_found: No %{resource} found
no_results: No results
@@ -1720,6 +1726,8 @@ en:
manual: Manually choose
product_sold_out: This item is sold out
products: Products
+ products_added: Products added
+ products_removed: Products removed
products_cannot_be_shipped: We cannot ship %{product_names} to your current location at the moment. Please change your shipping address or remove %{product_names} from your cart.
products_sort_options:
best_selling: Best Selling
@@ -1916,6 +1924,7 @@ en:
sales_totals: Sales Totals
same_as_shipping_address: Same as shipping address
save_and_continue: Save and Continue
+ save_changes: Save Changes
save_my_address: Save my address
saving: Saving
say_no: 'No'
@@ -1929,6 +1938,7 @@ en:
search_order_number: Order Number
search_results: Search results for '%{keywords}'
search_results_for: Search results for %{query}
+ search_products: Search products
searching: Searching
secure_connection_type: Secure Connection Type
security: Security
@@ -2291,6 +2301,7 @@ en:
twitter: Twitter
type: Type
type_to_search: Type to search
+ type_to_search_products: Type to search for products
unable_to_connect_to_gateway: Unable to connect to gateway.
unable_to_create_reimbursements: Unable to create reimbursements because there are items pending manual intervention.
under_price: Under %{price}
diff --git a/core/db/migrate/20251110120002_add_price_list_id_to_spree_prices.rb b/core/db/migrate/20251110120002_add_price_list_id_to_spree_prices.rb
index 42ff77486d..b04121e1e2 100644
--- a/core/db/migrate/20251110120002_add_price_list_id_to_spree_prices.rb
+++ b/core/db/migrate/20251110120002_add_price_list_id_to_spree_prices.rb
@@ -1,6 +1,6 @@
class AddPriceListIdToSpreePrices < ActiveRecord::Migration[7.0]
def change
add_reference :spree_prices, :price_list, null: true
- add_index :spree_prices, [:variant_id, :currency, :price_list_id], name: 'index_spree_prices_on_variant_currency_price_list'
+ add_index :spree_prices, [:variant_id, :currency, :price_list_id], name: 'index_spree_prices_on_variant_currency_price_list', unique: true
end
end
diff --git a/core/lib/spree/permitted_attributes.rb b/core/lib/spree/permitted_attributes.rb
index c05a547c74..e2868c55d3 100644
--- a/core/lib/spree/permitted_attributes.rb
+++ b/core/lib/spree/permitted_attributes.rb
@@ -36,6 +36,7 @@ module Spree
:policy_attributes,
:post_attributes,
:post_category_attributes,
+ :price_list_attributes,
:product_attributes,
:promotion_attributes,
:promotion_rule_attributes,
@@ -163,6 +164,8 @@ module Spree
@@post_category_attributes = [:title, :slug, :description]
+ @@price_list_attributes = [:name, :description, :match_policy, :starts_at, :ends_at, :status, :position]
+
@@product_properties_attributes = [:property_name, :property_id, :value, :position, :_destroy]
@@product_attributes = [
diff --git a/core/spec/models/spree/price_list_spec.rb b/core/spec/models/spree/price_list_spec.rb
index 9f7ac53aa4..20a36d1334 100644
--- a/core/spec/models/spree/price_list_spec.rb
+++ b/core/spec/models/spree/price_list_spec.rb
@@ -174,4 +174,111 @@ describe Spree::PriceList, type: :model do
expect(price_list.active?).to be false
end
end
+
+ describe '#add_products' do
+ let(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }
+ let(:price_list) { create(:price_list, store: store) }
+ let(:product1) { create(:product, stores: [store]) }
+ let(:product2) { create(:product, stores: [store]) }
+
+ it 'creates prices for all variants of the given products' do
+ expect {
+ price_list.add_products([product1.id, product2.id])
+ }.to change { price_list.prices.count }.by(6) # 2 products * 3 currencies
+ end
+
+ it 'creates prices for all supported currencies' do
+ price_list.add_products([product1.id])
+
+ currencies = price_list.prices.where(variant_id: product1.master.id).pluck(:currency)
+ expect(currencies).to match_array(%w[USD EUR GBP])
+ end
+
+ it 'creates prices with nil amount' do
+ price_list.add_products([product1.id])
+
+ expect(price_list.prices.pluck(:amount).uniq).to eq([nil])
+ end
+
+ it 'does not create duplicate prices for existing variants' do
+ price_list.prices.create!(variant: product1.master, currency: 'USD', amount: nil)
+
+ expect {
+ price_list.add_products([product1.id])
+ }.to change { price_list.prices.count }.by(2) # Only EUR and GBP, not USD
+ end
+
+ it 'handles empty product_ids' do
+ expect {
+ price_list.add_products([])
+ }.not_to change { price_list.prices.count }
+ end
+
+ it 'handles nil product_ids' do
+ expect {
+ price_list.add_products(nil)
+ }.not_to change { price_list.prices.count }
+ end
+
+ context 'with products having multiple variants' do
+ let(:product_with_variants) { create(:product, stores: [store]) }
+ let!(:variant1) { create(:variant, product: product_with_variants) }
+ let!(:variant2) { create(:variant, product: product_with_variants) }
+
+ it 'creates prices for all eligible variants' do
+ eligible_count = Spree::Variant.eligible.where(product_id: product_with_variants.id).count
+
+ expect {
+ price_list.add_products([product_with_variants.id])
+ }.to change { price_list.prices.count }.by(eligible_count * 3) # variants * 3 currencies
+ end
+ end
+ end
+
+ describe '#remove_products' do
+ let(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }
+ let(:price_list) { create(:price_list, store: store) }
+ let(:product1) { create(:product, stores: [store]) }
+ let(:product2) { create(:product, stores: [store]) }
+
+ before do
+ price_list.add_products([product1.id, product2.id])
+ end
+
+ it 'removes all prices for the given products' do
+ expect {
+ price_list.remove_products([product1.id])
+ }.to change { price_list.prices.count }.by(-3) # 1 product * 3 currencies
+ end
+
+ it 'removes prices for all currencies' do
+ price_list.remove_products([product1.id])
+
+ expect(price_list.prices.joins(:variant).where(spree_variants: { product_id: product1.id }).count).to eq(0)
+ end
+
+ it 'does not remove prices for other products' do
+ price_list.remove_products([product1.id])
+
+ expect(price_list.prices.joins(:variant).where(spree_variants: { product_id: product2.id }).count).to eq(3)
+ end
+
+ it 'handles empty product_ids' do
+ expect {
+ price_list.remove_products([])
+ }.not_to change { price_list.prices.count }
+ end
+
+ it 'handles nil product_ids' do
+ expect {
+ price_list.remove_products(nil)
+ }.not_to change { price_list.prices.count }
+ end
+
+ it 'removes prices for multiple products at once' do
+ expect {
+ price_list.remove_products([product1.id, product2.id])
+ }.to change { price_list.prices.count }.by(-6) # 2 products * 3 currencies
+ end
+ end
end