diff --git a/app/models/spree/product.rb b/app/models/spree/product.rb index a0b9da8dfe..c36d2b58b7 100755 --- a/app/models/spree/product.rb +++ b/app/models/spree/product.rb @@ -168,6 +168,19 @@ module Spree scope :by_producer, -> { joins(variants: :supplier).order('enterprises.name') } scope :by_name, -> { order('spree_products.name') } + # Scope for ordering by stock levels + scope :order_by_stock, lambda { |direction = :asc| + b_value = direction != :asc + on_hand_direction = direction == :asc ? 'ASC' : 'DESC' + + joins(variants: :stock_items) + .group('spree_products.id, spree_products.name') + .order( + Arel.sql("CASE WHEN BOOL_OR(spree_stock_items.backorderable) = #{b_value} THEN 1 END"), + Arel.sql("SUM(spree_stock_items.count_on_hand) #{on_hand_direction}") + ) + } + scope :managed_by, lambda { |user| if user.admin? where(nil) diff --git a/app/views/admin/products_v3/_table.html.haml b/app/views/admin/products_v3/_table.html.haml index 5226461c94..eaa399d36b 100644 --- a/app/views/admin/products_v3/_table.html.haml +++ b/app/views/admin/products_v3/_table.html.haml @@ -59,7 +59,8 @@ %th.align-left.col-unit_scale.with-input= t('admin.products_page.columns.unit_scale') %th.align-left.col-unit.with-input= t('admin.products_page.columns.unit') %th.align-left.col-price.with-input= t('admin.products_page.columns.price') - %th.align-left.col-on_hand.with-input= t('admin.products_page.columns.on_hand') + = render partial: 'spree/admin/shared/stimulus_sortable_header', + locals: { column: :on_hand, sorted: params.dig(:q, :s), default: 'on_hand asc' } %th.align-left.col-producer= t('admin.products_page.columns.producer') %th.align-left.col-category= t('admin.products_page.columns.category') %th.align-left.col-tax_category= t('admin.products_page.columns.tax_category')