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.

WIP: `Spree::Admin::ProductsController`

Łukasz Adamczykdaca5d08712e
diff --git a/admin/app/controllers/spree/admin/products_controller.rb b/admin/app/controllers/spree/admin/products_controller.rb
new file mode 100644
index 0000000000..660ddc7f76
--- /dev/null
+++ b/admin/app/controllers/spree/admin/products_controller.rb
@@ -0,0 +1,346 @@
+module Spree
+ module Admin
+ class ProductsController < ResourceController
+ include Spree::Admin::StockLocationsHelper
+ include Spree::Admin::BulkOperationsConcern
+
+ helper 'spree/admin/products'
+ helper 'spree/admin/taxons'
+
+ before_action :load_data, except: :index
+ before_action :load_variants_data, only: %i[edit update]
+ before_action :set_product_defaults, only: :new
+
+ before_action :prepare_product_params, only: [:create, :update]
+
+ before_action :strip_stock_items_param, only: [:create, :update]
+
+ new_action.before :build_master_prices
+ new_action.before :build_master_stock_items
+ new_action.before :build_product_properties
+ edit_action.before :build_master_prices
+ edit_action.before :build_master_stock_items
+ edit_action.before :build_product_properties
+ create.after :assign_master_images
+ update.before :skip_updating_status
+ update.before :update_status
+ update.before :remove_empty_params
+ helper_method :clone_object_url
+
+ def show
+ redirect_to action: :edit
+ end
+
+ def update
+ invoke_callbacks(:update, :before)
+
+ if @product.update(permitted_resource_params)
+ set_current_store
+ invoke_callbacks(:update, :after)
+ flash[:success] = flash_message_for(@product, :successfully_updated)
+ redirect_to location_after_save
+ else
+ # Stops people submitting blank slugs, causing errors when they try to
+ # update the product again
+ @product.slug = @product.slug_was if @product.slug.blank?
+ invoke_callbacks(:update, :fails)
+ respond_with(@product) do |format|
+ format.html { render :edit, status: :unprocessable_entity }
+ format.turbo_stream
+ end
+ end
+ end
+
+ def clone
+ clone_result = @product.duplicate
+
+ if clone_result.success?
+ flash[:success] = Spree.t('notice_messages.product_cloned')
+ redirect_to spree.edit_admin_product_path(clone_result.value)
+ else
+ flash[:error] = Spree.t('notice_messages.product_not_cloned', error: clone_result.error.value)
+ redirect_to spree.edit_admin_product_path(@product)
+ end
+ end
+
+ def bulk_modal
+ if params[:kind] == 'set_status'
+ @title = Spree.t('admin.bulk_ops.products.title.set_status', status: params[:status].titleize)
+ @body = Spree.t("admin.bulk_ops.products.body.set_status.#{params[:status]}")
+ else
+ @title = Spree.t("admin.bulk_ops.products.title.#{params[:kind]}")
+ @body = Spree.t("admin.bulk_ops.products.body.#{params[:kind]}")
+ end
+ end
+
+ def bulk_status_update
+ if bulk_collection.update_all(status: params[:status], updated_at: Time.current)
+ product_ids = bulk_collection.ids
+
+ if Spree::Webhooks::Subscriber.any?
+ ::Spree::Products::QueueStatusChangedWebhook.call(
+ ids: product_ids,
+ event: Spree::Product::STATUS_TO_WEBHOOK_EVENT[params[:status]]
+ )
+ end
+
+ invoke_callbacks(:bulk_status_update, :after)
+
+ flash.now[:success] = Spree.t('admin.bulk_ops.products.status_updated', status: params[:status].titleize)
+ else
+ flash.now[:error] = Spree.t('something_went_wrong')
+ end
+ end
+
+ def bulk_add_tags
+ Spree::Tags::BulkAdd.call(tag_names: params[:tags], records: bulk_collection)
+ Spree::Product.bulk_auto_match_taxons(current_store, bulk_collection.ids)
+
+ handle_bulk_operation_response
+ end
+
+ def bulk_remove_tags
+ Spree::Tags::BulkRemove.call(tag_names: params[:tags], records: bulk_collection)
+ Spree::Product.bulk_auto_match_taxons(current_store, bulk_collection.ids)
+
+ handle_bulk_operation_response
+ end
+
+ def bulk_remove_from_taxons
+ taxons = current_store.taxons.accessible_by(current_ability, :manage).where(id: params[:taxon_ids])
+ Spree::Taxons::RemoveProducts.call(taxons: taxons, products: bulk_collection)
+ Spree::Product.bulk_auto_match_taxons(current_store, bulk_collection.ids)
+
+ handle_bulk_operation_response
+ end
+
+ def bulk_add_to_taxons
+ taxons = current_store.taxons.accessible_by(current_ability, :manage).where(id: params[:taxon_ids])
+ Spree::Taxons::AddProducts.call(taxons: taxons, products: bulk_collection)
+ Spree::Product.bulk_auto_match_taxons(current_store, bulk_collection.ids)
+
+ handle_bulk_operation_response
+ end
+
+ def select_options
+ render json: current_store.products.not_archived.accessible_by(current_ability, :index).to_tom_select_json
+ end
+
+ protected
+
+ def find_resource
+ current_store.products.accessible_by(current_ability, :manage).with_deleted.friendly.find(params[:id])
+ end
+
+ def load_data
+ @taxons = Taxon.order(:name)
+ @option_types = OptionType.order(:name)
+ @tax_categories = TaxCategory.order(:name)
+ @shipping_categories = ShippingCategory.order(:name)
+ end
+
+ def load_variants_data
+ return unless @product.has_variants?
+
+ @product_options = {}
+
+ @product.
+ option_values.
+ joins(option_type: :product_option_types).
+ merge(@product.product_option_types).
+ reorder('spree_product_option_types.position').
+ uniq.group_by(&:option_type).each_with_index do |option, index|
+ option_type, option_values = option
+ @product_options[option_type.id] = {
+ name: option_type.presentation,
+ position: index + 1,
+ values: option_values.pluck(:presentation).uniq
+ }
+ end
+
+ @product_stock = {}
+ @product.stock_items.includes(:variant).each do |stock_item|
+ @product_stock[stock_item.variant.human_name] ||= {}
+ @product_stock[stock_item.variant.human_name][stock_item.stock_location_id] = {
+ count_on_hand: stock_item.count_on_hand,
+ backorderable: stock_item.backorderable,
+ id: stock_item.id
+ }
+ end
+
+ @product_prices = {}
+ @product.prices.includes(:variant).each do |price|
+ @product_prices[price.variant.human_name] ||= {}
+ @product_prices[price.variant.human_name][price.currency.downcase] = {
+ id: price.id,
+ amount: price.amount
+ }
+ end
+
+ @product_variant_ids = {}
+
+ @product.variants.includes(:option_values).each do |variant|
+ @product_variant_ids[variant.human_name] = variant.id
+ end
+ end
+
+ def set_product_defaults
+ @product.shipping_category ||= @shipping_categories&.first
+ end
+
+ def skip_updating_status
+ @new_status = params[:product].delete(:status)
+ end
+
+ def update_status
+ return if @new_status == @product.status
+ return if cannot?(:activate, @product) && @new_status&.to_sym == :active
+
+ event_to_fire = @product.status_transitions.find { |transition| transition.from == @product.status && transition.to == @new_status }&.event
+ @product.status_event = event_to_fire if event_to_fire
+ end
+
+ def remove_empty_params
+ reject_empty_params(:tag_list) if can?(:manage_tags, @product)
+ reject_empty_params(:taxon_ids)
+ reject_empty_params(:label_list) if can?(:manage_labels, @product)
+ end
+
+ def reject_empty_params(key)
+ params[:product][key] = params[:product][key].present? ? params[:product][key].reject(&:empty?) : []
+ end
+
+ def prepare_product_params
+ params_service = Spree::Products::PrepareNestedAttributes.new(@product, current_store, permitted_resource_params, current_ability)
+ params[:product] = params_service.call
+ end
+
+ def collection
+ return @collection if @collection.present?
+
+ params[:q] ||= {}
+ params[:q][:deleted_at_null] ||= '1'
+
+ params[:q][:s] ||= 'name asc'
+ params[:q][:status_eq] == 'archived' ? params[:q].delete(:status_not_eq) : params[:q][:status_not_eq] = 'archived'
+
+ params[:q][:taxons_id_null] = '1' if params.dig(:q, :taxons_id_in)&.include?(' ')
+
+ assign_extra_collection_params if respond_to?(:assign_extra_collection_params)
+
+ @collection = super
+
+ # Don't delete params[:q][:deleted_at_null] here because it is used in view to check the
+ # checkbox for 'q[deleted_at_null]'. This also messed with pagination when deleted_at_null is checked.
+ @collection = @collection.with_deleted if params[:q][:deleted_at_null] == '0'
+
+ # The out_of_stock scope groups products - we also need to group it by name coming from product translations
+ # That's because we sort products by name
+ @collection = @collection.group(:name) if params.dig(:q, :out_of_stock_items) == '1'
+
+ # @search needs to be defined as this is passed to search_form_for
+ # Temporarily remove params[:q][:deleted_at_null] from params[:q] to ransack products.
+ # This is to include all products and not just deleted products.
+ @search = @collection.ransack(params[:q].except(:deleted_at_null))
+ @collection = @search.result(distinct: true).
+ for_ordering_with_translations(model_class, :name).
+ includes(product_includes).
+ page(params[:page]).
+ per(params[:per_page] || ENV.fetch('ADMIN_PRODUCTS_PER_PAGE', 25))
+
+ @collection
+ end
+
+ def clone_object_url(resource)
+ clone_admin_product_url resource
+ end
+
+ def permitted_resource_params
+ if cannot?(:activate, @product) && @new_status&.to_sym == :active
+ super.except(:status, :make_active_at).permit!
+ else
+ super
+ end
+ end
+
+ private
+
+ def collection_actions
+ [
+ :index, :bulk_modal, :bulk_status_update,
+ :bulk_add_to_taxons, :bulk_remove_from_taxons,
+ :bulk_add_tags, :bulk_remove_tags
+ ]
+ end
+
+ def update_turbo_stream_enabled?
+ true
+ end
+
+ def variant_stock_includes
+ [:images, { stock_items: :stock_location, option_values: :option_type }]
+ end
+
+ def strip_stock_items_param
+ if params.dig(:product, :track_inventory) == '0'
+ if params.dig(:product, :master_attributes, :stock_items_attributes).present?
+ params[:product][:master_attributes][:stock_items_attributes] = {}
+ end
+ if params.dig(:product, :variants_attributes)
+ params[:product][:variants_attributes].each do |_key, variant|
+ variant[:stock_items_attributes] = {}
+ end
+ end
+ end
+ end
+
+ def build_master_prices
+ return if @product.has_variants?
+
+ current_store.supported_currencies_list.each do |currency|
+ @product.master.prices.build(currency: currency) unless @product.master.prices.find { |price| price.currency == currency }
+ end
+ end
+
+ def build_master_stock_items
+ return if @product.has_variants?
+
+ available_stock_locations_list(master_stock_items_locations_opts).each do |_name, id|
+ @product.master.stock_items.build(stock_location_id: id, count_on_hand: 0) unless @product.master.stock_items.find { |stock_item| stock_item.stock_location_id == id }
+ end
+ end
+
+ def master_stock_items_locations_opts
+ {}
+ end
+
+ def build_product_properties
+ Spree::Property.all.each do |property|
+ @product.product_properties.build(property: property) unless @product.product_properties.find { |product_property| product_property.property_id == property.id }
+ end
+ end
+
+ def assign_master_images
+ return unless @product.master.persisted?
+
+ assets_ids = session[:uploaded_asset_ids]&.split(',')
+ return if assets_ids.blank?
+
+ Spree::Asset.where(id: assets_ids, viewable_id: nil).update_all(viewable_id: @product.master.id, viewable_type: 'Spree::Variant', updated_at: Time.current)
+ session.delete(:uploaded_asset_ids)
+ end
+
+ def product_includes
+ {
+ tax_category: [],
+ stock_items: [:stock_location],
+ variants_including_master: [],
+ shipping_category: [],
+ master: [:prices, :images, :stock_items, :stock_locations],
+ variants: [:prices, :images, :stock_items, :stock_locations],
+ variant_images: [],
+ }
+ end
+ end
+ end
+end
diff --git a/admin/config/locales/en.yml b/admin/config/locales/en.yml
index 67655888dc..bcf0197d95 100644
--- a/admin/config/locales/en.yml
+++ b/admin/config/locales/en.yml
@@ -298,4 +298,28 @@ en:
message_without_taxes: You can use tax services such as TaxJar or setup tax calculation manually
payment_methods:
edit:
- payment_method_configuration: "Payment Method Configuration"
\ No newline at end of file
+ payment_method_configuration: "Payment Method Configuration"
+ bulk_ops:
+ products:
+ title:
+ set_status: Set as %{status}
+ add_to_taxons: Add to taxons
+ remove_from_taxons: Remove from taxons
+ add_tags: Add tags
+ remove_tags: Remove tags
+ add_to_brand: Add to brand
+ remove_from_brand: Remove from brand
+ set_size_chart: Set Size Chart
+ set_return_rule: Set Return Rule
+ body:
+ set_status:
+ draft: Setting products to draft will hide them from storefront.
+ ready_for_review: We will notify your partners that these products are ready for review. Your partners will be able to review and publish these products.
+ active: Setting products to active will make those products available on the storefront.
+ archived: Setting products to archived will hide them from storefront.
+ remove_from_taxons: 'Select which taxons to remove the products from:'
+ add_to_taxons: 'Select which taxons to add the products to:'
+ add_to_brand: 'Select which brand to add the products to:'
+ add_tags: 'Select tags to add to the products:'
+ remove_tags: 'Select tags to remove from the products:'
+ set_return_rule: Select return rule for products
\ No newline at end of file
diff --git a/admin/config/routes.rb b/admin/config/routes.rb
index de700818fd..d2481abe75 100644
--- a/admin/config/routes.rb
+++ b/admin/config/routes.rb
@@ -44,7 +44,25 @@ Spree::Core::Engine.add_routes do
resources :webhooks_subscribers
# products
- resources :products
+ resources :products do
+ collection do
+ get :select_options, defaults: { format: :json }
+ post :search
+ get :bulk_modal
+ put :bulk_status_update
+ put :bulk_add_to_taxons
+ put :bulk_remove_from_taxons
+ put :bulk_add_tags
+ put :bulk_remove_tags
+ end
+
+ member do
+ post :clone
+ end
+
+ resources :variants, only: [:edit, :update, :destroy]
+ resources :digitals, only: [:index, :create, :destroy]
+ end
# taxonomies and taxons
resources :taxonomies do
diff --git a/admin/lib/spree/admin/callbacks.rb b/admin/lib/spree/admin/callbacks.rb
index 0b5bb7b359..5aa8cc9132 100644
--- a/admin/lib/spree/admin/callbacks.rb
+++ b/admin/lib/spree/admin/callbacks.rb
@@ -8,8 +8,6 @@ module Spree
module ClassMethods
attr_accessor :callbacks
- protected
-
def new_action
custom_callback(:new_action)
end
diff --git a/admin/spec/controllers/spree/admin/products_controller_spec.rb b/admin/spec/controllers/spree/admin/products_controller_spec.rb
new file mode 100644
index 0000000000..c7e27aeba9
--- /dev/null
+++ b/admin/spec/controllers/spree/admin/products_controller_spec.rb
@@ -0,0 +1,1140 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::ProductsController, type: :controller do
+ stub_authorization!
+
+ before do
+ allow(controller).to receive(:current_ability).and_call_original
+ end
+
+ let(:store) { Spree::Store.default }
+
+ describe 'GET #index' do
+ it 'can find a product by SKU' do
+ product = create(:product, sku: 'ABC123', stores: [store])
+ get :index, params: { q: { sku_start: 'ABC123' } }
+ expect(assigns[:collection]).not_to be_empty
+ expect(assigns[:collection]).to include(product)
+ end
+
+ it 'can find a product by variant sku' do
+ variant = create(:variant, sku: 'ABC123', is_master: false)
+ product = create(:product, stores: [store], variants: [variant])
+ get :index, params: { q: { multi_search: 'ABC123' } }
+ expect(assigns[:collection]).not_to be_empty
+ expect(assigns[:collection]).to include(product)
+ end
+
+ it 'searches by product kind' do
+ shipping_category = create(:shipping_category, name: 'digital')
+ product = create(:product, sku: 'ABC123', stores: [store], shipping_category: shipping_category)
+
+ get :index, params: { q: { shipping_category_id_eq: shipping_category.id.to_s } }
+
+ expect(assigns[:collection]).not_to be_empty
+ expect(assigns[:collection]).to eq([product])
+ end
+
+ it 'searches based on taxons' do
+ category_1 = create(:taxon)
+ category_2 = create(:taxon)
+
+ product_1 = create(:product, stores: [store], taxons: [category_1])
+ product_2 = create(:product, stores: [store], taxons: [category_2])
+
+ get :index, params: { q: { taxons_id_in: [category_1.id, category_2.id] } }
+
+ expect(assigns[:collection]).to contain_exactly(product_1, product_2)
+ end
+
+ it 'searches for products without category' do
+ create(:product, stores: [store], taxons: [create(:taxon)])
+ product = create(:product, stores: [store], taxons: [])
+
+ get :index, params: { q: { taxons_id_in: [' '] } }
+
+ expect(assigns[:collection]).to contain_exactly(product)
+ end
+
+ context 'with views' do
+ render_views
+
+ it 'can perform multi search' do
+ get :index, params: {
+ 'q' => {
+ 'status_eq' => 'active',
+ 'multi_search' => 'anchor',
+ 'classifications_taxon_id_in' => ['8b03b40e-094f-4803-8704-20ac02f9c167', '42e63c13-dbe7-483f-8237-3b0207145fed'],
+ 'shipping_category_id_eq' => '8b03b40e-094f-4803-8704-20ac02f9c167',
+ 'tags_name_in' => ['awesome'],
+ 'deleted_at_null' => '1',
+ 'not_discontinue' => '1'
+ }
+ }
+
+ expect(response).to be_successful
+ end
+ end
+ end
+
+ describe 'POST #create' do
+ subject { post :create, params: { product: product_params } }
+ let(:stock_location) { create(:stock_location) }
+ let(:other_stock_location) { create(:stock_location) }
+
+ context 'without variants' do
+ let(:product_params) do
+ {
+ name: 'Product',
+ sku: 'SKU',
+ barcode: 'BARCODE',
+ weight: 10,
+ height: 10,
+ width: 10,
+ depth: 10,
+ dimensions_unit: 'cm',
+ weight_unit: 'kg'
+ }
+ end
+
+ it 'creates product correctly' do
+ subject
+
+ product = Spree::Product.last
+ expect(product.sku).to eq 'SKU'
+ expect(product.barcode).to eq 'BARCODE'
+ expect(product.weight).to eq 10
+ expect(product.height).to eq 10
+ expect(product.width).to eq 10
+ expect(product.depth).to eq 10
+ expect(product.dimensions_unit).to eq 'cm'
+ expect(product.weight_unit).to eq 'kg'
+ expect(product.stores).to eq [store]
+ end
+
+ context 'with multi-currency pricing' do
+ before do
+ product_params[:master_attributes] = {}
+ product_params[:master_attributes][:prices_attributes] = {
+ '0' => { currency: 'EUR', amount: 10, compare_at_amount: 20 },
+ '1' => { currency: 'USD', amount: 20, compare_at_amount: 30 }
+ }
+ end
+
+ it 'creates product correctly' do
+ subject
+
+ product = Spree::Product.last
+
+ expect(product.master.prices.count).to eq 2
+ expect(product.master.price_in('EUR').amount).to eq 10
+ expect(product.master.price_in('USD').amount).to eq 20
+ expect(product.master.price_in('EUR').compare_at_amount).to eq 20
+ expect(product.master.price_in('USD').compare_at_amount).to eq 30
+ end
+ end
+ end
+
+ context 'with variants' do
+ let!(:option_type) { create(:option_type, name: 'Color', presentation: 'Color') }
+ let(:product_params) do
+ {
+ name: 'Product',
+ variants_attributes: {
+ '0' => {
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 10 },
+ '1': { currency: 'USD', amount: 20 }
+ },
+ stock_items_attributes: {
+ '0' => {
+ count_on_hand: 10,
+ stock_location_id: stock_location.id,
+ }
+ },
+ options: [
+ {
+ name: 'Color',
+ position: 1,
+ value: 'Red'
+ },
+ {
+ name: 'Not existing option',
+ position: 2,
+ value: 'Not existing value'
+ }
+ ]
+ },
+ '3' => {
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 44 },
+ '1': { currency: 'USD', amount: 55 }
+ },
+ stock_items_attributes: {
+ '0' => {
+ count_on_hand: 200,
+ stock_location_id: other_stock_location.id,
+ }
+ },
+ options: [
+ {
+ name: 'Color',
+ position: 1,
+ value: 'Blue'
+ },
+ {
+ name: 'Not existing option',
+ position: 2,
+ value: 'Not existing value2'
+ }
+ ]
+ }
+ }
+ }
+ end
+
+ context 'when track_inventory is false' do
+ before do
+ product_params[:track_inventory] = '0'
+ end
+
+ it 'does not create stock items' do
+ subject
+
+ product = Spree::Product.last
+
+ expect(product.stock_items.reload.count).to eq(0)
+ end
+ end
+
+ context 'when prices are not present' do
+ before do
+ product_params[:variants_attributes]['0'][:prices_attributes] = {
+ '0': { currency: 'PLN', amount: nil },
+ '1': { currency: 'USD', amount: 20 },
+ '2': { currency: 'EUR', amount: 30 }
+ }
+ product_params[:variants_attributes]['3'][:prices_attributes] = {
+ '0': { currency: 'PLN', amount: 44 },
+ '1': { currency: 'USD', amount: 55 },
+ '2': { currency: 'EUR', amount: 66 }
+ }
+ end
+
+ it 'does not create price for that currency' do
+ subject
+
+ product = Spree::Product.last
+ expect(product.variants.count).to eq 2
+
+ variant = product.variants.first
+ expect(variant.prices.reload.count).to eq 2
+
+ pln_price = variant.price_in('PLN')
+ expect(pln_price.amount).to be nil
+ expect(pln_price.persisted?).to be false
+
+ expect(variant.price_in('USD').amount).to eq 20
+ expect(variant.price_in('EUR').amount).to eq 30
+ expect(variant.options_text).to eq 'Color: Red, Not existing option: Not existing value'
+ expect(variant.stock_items.first.count_on_hand).to eq 10
+ expect(variant.stock_items.first.stock_location).to eq stock_location
+
+ other_variant = product.variants.last
+ expect(other_variant.prices.reload.count).to eq 3
+
+ expect(other_variant.price_in('PLN').amount).to eq 44
+ expect(other_variant.price_in('USD').amount).to eq 55
+ expect(other_variant.price_in('EUR').amount).to eq 66
+ expect(other_variant.options_text).to eq 'Color: Blue, Not existing option: Not existing value2'
+ expect(other_variant.stock_items.first.count_on_hand).to eq 200
+ expect(other_variant.stock_items.first.stock_location).to eq other_stock_location
+ end
+ end
+
+ it 'creates product correctly' do
+ subject
+
+ product = Spree::Product.last
+ expect(product.variants.count).to eq 2
+
+ variant = product.variants.first
+ expect(variant.price_in('PLN').amount).to eq 10
+ expect(variant.price_in('USD').amount).to eq 20
+ expect(variant.options_text).to eq 'Color: Red, Not existing option: Not existing value'
+ expect(variant.stock_items.first.count_on_hand).to eq 10
+ expect(variant.stock_items.first.stock_location).to eq stock_location
+
+ other_variant = product.variants.last
+ expect(other_variant.price_in('PLN').amount).to eq 44
+ expect(other_variant.price_in('USD').amount).to eq 55
+ expect(other_variant.options_text).to eq 'Color: Blue, Not existing option: Not existing value2'
+ expect(other_variant.stock_items.first.count_on_hand).to eq 200
+ expect(other_variant.stock_items.first.stock_location).to eq other_stock_location
+ end
+ end
+
+ context 'with stock items' do
+ let(:product_params) do
+ {
+ name: 'Product',
+ master_attributes: {
+ track_inventory: true,
+ stock_items_attributes: {
+ '0' => {
+ count_on_hand: 10,
+ stock_location_id: stock_location.id,
+ backorderable: false
+ },
+ '1' => {
+ count_on_hand: 5,
+ stock_location_id: other_stock_location.id,
+ backorderable: true
+ }
+ }
+ }
+ }
+ end
+
+ it 'correctly assign stock items' do
+ subject
+
+ product = Spree::Product.last
+
+ stock_item = product.master.stock_items.first
+ expect(stock_item.count_on_hand).to eq 10
+ expect(stock_item.stock_location).to eq stock_location
+ expect(stock_item.backorderable).to be false
+
+ other_stock_item = product.master.stock_items.last
+ expect(other_stock_item.count_on_hand).to eq 5
+ expect(other_stock_item.stock_location).to eq other_stock_location
+ expect(other_stock_item.backorderable).to be true
+
+ expect(product.master.track_inventory).to be true
+ end
+ end
+
+ context 'with product properties' do
+ let!(:property_1) { create(:property, name: 'material', presentation: 'Material', kind: 'short_text') }
+ let!(:property_2) { create(:property, name: 'short_description', presentation: 'Short description', kind: 'rich_text') }
+ let!(:property_3) { create(:property, name: 'care', presentation: 'Care', kind: 'rich_text') }
+
+ let(:product_params) do
+ {
+ name: 'Product',
+ product_properties_attributes: {
+ '0' => {
+ property_id: property_1.id,
+ value: 'Wool'
+ },
+ '1' => {
+ property_id: property_2.id,
+ value: 'Short description with some <a href="https://example.com">link</a>'
+ },
+ '2' => {
+ property_id: property_3.id,
+ value: ''
+ }
+ }
+ }
+ end
+
+ it 'creates product properties correctly' do
+ subject
+
+ product = Spree::Product.last
+ expect(product.properties.count).to eq 2
+ expect(product.property('material')).to eq 'Wool'
+ expect(product.property('short_description')).to eq 'Short description with some <a href="https://example.com">link</a>'
+ end
+ end
+
+ context 'with multiple stores' do
+ let(:store_2) { create(:store) }
+
+ let(:product_params) do
+ {
+ name: 'Product',
+ store_ids: [store.id, store_2.id]
+ }
+ end
+
+ it 'assigns product to requests stores plus current store' do
+ subject
+
+ product = Spree::Product.last
+ expect(product.stores).to eq [store, store_2]
+ end
+
+ context 'with empty store_ids' do
+ let(:product_params) do
+ {
+ name: 'Product',
+ store_ids: []
+ }
+ end
+
+ it 'assigns product to current store' do
+ subject
+
+ product = Spree::Product.last
+ expect(product.stores).to eq [store]
+ end
+ end
+ end
+ end
+
+ describe 'PUT #update' do
+ let!(:product) { create(:product, stores: [store], status: 'active') }
+ let(:product_params) { { status: 'draft', make_active_at: Time.current.beginning_of_day } }
+ let(:send_request) do
+ put :update, params: {
+ id: product.to_param,
+ product: product_params
+ }
+ end
+
+ describe 'master variant inventory' do
+ let(:product_params) do
+ {
+ master_attributes: {
+ id: product.master_id,
+ stock_items_attributes: {
+ '0' => {
+ id: product.master.stock_items.first.id,
+ stock_location_id: product.master.stock_items.first.stock_location_id,
+ count_on_hand: 123,
+ backorderable: '1'
+ }
+ }
+ }
+ }
+ end
+
+ it 'updates the stock of the master variant' do
+ send_request
+ expect(product.master.reload.total_on_hand).to eq(123)
+ expect(product.master).to be_backorderable
+ end
+ end
+
+ context 'adding variants to existing product' do
+ let(:stock_location) { create(:stock_location) }
+ let(:other_stock_location) { create(:stock_location) }
+ let(:product_params) do
+ {
+ name: 'Product',
+ variants_attributes: {
+ '0' => {
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 10 },
+ '1': { currency: 'USD', amount: 20 }
+ },
+ stock_items_attributes: {
+ '0' => {
+ count_on_hand: 10,
+ stock_location_id: stock_location.id,
+ }
+ },
+ options: [
+ {
+ name: 'Color',
+ position: 1,
+ value: 'Red'
+ },
+ {
+ name: 'Not existing option',
+ position: 2,
+ value: 'Not existing value'
+ }
+ ]
+ },
+ '3' => {
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 44 },
+ '1': { currency: 'USD', amount: 55 }
+ },
+ stock_items_attributes: {
+ '0' => {
+ count_on_hand: 200,
+ stock_location_id: other_stock_location.id,
+ }
+ },
+ options: [
+ {
+ name: 'Color',
+ position: 1,
+ value: 'Blue'
+ },
+ {
+ name: 'Not existing option',
+ position: 2,
+ value: 'Not existing value2'
+ }
+ ]
+ }
+ }
+ }
+ end
+
+ it 'creates variants correctly' do
+ send_request
+
+ expect(product.variants.reload.count).to eq 2
+
+ variant = product.variants.first
+ expect(variant.price_in('PLN').amount).to eq 10
+ expect(variant.price_in('USD').amount).to eq 20
+ expect(variant.options_text).to eq 'Color: Red, Not existing option: Not existing value'
+ expect(variant.stock_items.first.count_on_hand).to eq 10
+ expect(variant.stock_items.first.stock_location).to eq stock_location
+
+ other_variant = product.variants.last
+ expect(other_variant.price_in('PLN').amount).to eq 44
+ expect(other_variant.price_in('USD').amount).to eq 55
+ expect(other_variant.options_text).to eq 'Color: Blue, Not existing option: Not existing value2'
+ expect(other_variant.stock_items.first.count_on_hand).to eq 200
+ expect(other_variant.stock_items.first.stock_location).to eq other_stock_location
+ end
+ end
+
+ context 'updating existing variants' do
+ let(:color_option_type) { create(:option_type, name: 'Color', presentation: 'Color', products: [product]) }
+ let(:size_option_type) { create(:option_type, name: 'Size', presentation: 'Size', products: [product]) }
+ let(:red_option_value) { create(:option_value, name: 'Red', option_type: color_option_type) }
+ let(:blue_option_value) { create(:option_value, name: 'Blue', option_type: color_option_type) }
+ let(:small_option_value) { create(:option_value, name: 'Small', option_type: size_option_type) }
+ let(:large_option_value) { create(:option_value, name: 'Large', option_type: size_option_type) }
+
+ let(:variant1) { create(:variant, product: product, option_values: [red_option_value, small_option_value], price: 100) }
+ let(:variant2) { create(:variant, product: product, option_values: [blue_option_value, large_option_value], price: 100) }
+
+ let(:variant1_stock_item) { variant1.stock_items.first }
+ let(:variant2_stock_item) { variant2.stock_items.first }
+
+ let(:product_params) do
+ {
+ name: 'Product',
+ variants_attributes: {
+ '0' => {
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 10, id: variant1.price_in('PLN')&.id },
+ '1': { currency: 'USD', amount: 20, id: variant1.price_in('USD')&.id }
+ },
+ id: variant1.id,
+ stock_items_attributes: {
+ '0' => {
+ id: variant1_stock_item.id,
+ count_on_hand: 10,
+ stock_location_id: variant1_stock_item.stock_location_id,
+ }
+ },
+ options: [
+ {
+ name: 'Color',
+ position: 1,
+ value: 'Red'
+ },
+ {
+ name: 'Size',
+ position: 2,
+ value: 'Small'
+ }
+ ]
+ },
+ '1' => {
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 30, id: variant2.price_in('PLN')&.id },
+ '1': { currency: 'USD', amount: 40, id: variant2.price_in('USD')&.id }
+ },
+ id: variant2.id,
+ stock_items_attributes: {
+ '0' => {
+ id: variant2_stock_item.id,
+ count_on_hand: 20,
+ stock_location_id: variant2_stock_item.stock_location_id,
+ }
+ },
+ options: [
+ {
+ name: 'Color',
+ position: 1,
+ value: 'Blue'
+ },
+ {
+ name: 'Size',
+ position: 2,
+ value: 'Large'
+ }
+ ]
+ }
+ }
+ }
+ end
+
+ it 'updates the variants' do
+ send_request
+
+ expect(variant1.price_in('PLN').amount).to eq 10
+ expect(variant1.price_in('USD').amount).to eq 20
+ expect(variant2.price_in('PLN').amount).to eq 30
+ expect(variant2.price_in('USD').amount).to eq 40
+
+ expect(variant1_stock_item.reload.count_on_hand).to eq 10
+ expect(variant2_stock_item.reload.count_on_hand).to eq 20
+ end
+
+ context 'when product prices were imported' do
+ before do
+ variant1.prices.update_all(set_manually: false)
+ variant2.prices.update_all(set_manually: false)
+ end
+
+ it 'updates prices and marks them as set manually' do
+ send_request
+
+ expect(variant1.price_in('PLN').amount).to eq 10
+ expect(variant1.price_in('PLN')).to be_set_manually
+
+ expect(variant1.price_in('USD').amount).to eq 20
+ expect(variant1.price_in('USD')).to be_set_manually
+
+ expect(variant2.price_in('PLN').amount).to eq 30
+ expect(variant2.price_in('PLN')).to be_set_manually
+
+ expect(variant2.price_in('USD').amount).to eq 40
+ expect(variant2.price_in('USD')).to be_set_manually
+ end
+ end
+
+ context 'updating option types position' do
+ let(:product_params) do
+ {
+ variants_attributes: {
+ '0' => {
+ id: variant1.id,
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 10, id: variant1.price_in('PLN')&.id },
+ '1': { currency: 'USD', amount: 20, id: variant1.price_in('USD')&.id }
+ },
+ options: [
+ {
+ name: 'Size',
+ position: 1,
+ value: 'S'
+ },
+ {
+ name: 'Color',
+ position: 2,
+ value: 'Red'
+ }
+ ]
+ },
+ '1' => {
+ id: variant2.id,
+ prices_attributes: {
+ '0': { currency: 'PLN', amount: 30, id: variant2.price_in('PLN')&.id },
+ '1': { currency: 'USD', amount: 40, id: variant2.price_in('USD')&.id }
+ },
+ options: [
+ {
+ name: 'Size',
+ position: 1,
+ value: 'M'
+ },
+ {
+ name: 'Color',
+ position: 2,
+ value: 'Blue'
+ }
+ ]
+ }
+ }
+ }
+ end
+
+ before do
+ product.product_option_types.find_by(option_type_id: color_option_type.id).update(position: 1)
+ product.product_option_types.find_by(option_type_id: size_option_type.id).update(position: 2)
+ end
+
+ it 'updates the variants' do
+ send_request
+
+ expect(variant1.price_in('PLN').amount).to eq 10
+ expect(variant1.price_in('USD').amount).to eq 20
+ expect(variant2.price_in('PLN').amount).to eq 30
+ expect(variant2.price_in('USD').amount).to eq 40
+
+ expect(product.product_option_types.find_by(option_type_id: size_option_type.id).position).to eq 1
+ expect(product.product_option_types.find_by(option_type_id: color_option_type.id).position).to eq 2
+ end
+ end
+
+ context 'when option was removed' do
+ let(:product_params) do
+ {
+ variants_attributes: {
+ '0' => {
+ id: variant1.id,
+ price: { 'PLN' => 10, 'USD' => 20 },
+ options: [
+ {
+ name: 'Size',
+ position: 1,
+ value: 'S'
+ }
+ ],
+ stock_items_attributes: {
+ '0' => {
+ id: variant1_stock_item.id,
+ count_on_hand: 20,
+ stock_location_id: variant1_stock_item.stock_location_id,
+ }
+ },
+ },
+ '1' => {
+ id: variant2.id,
+ price: { 'PLN' => 30, 'USD' => 40 },
+ stock_items_attributes: {
+ '0' => {
+ id: variant2_stock_item.id,
+ count_on_hand: 20,
+ stock_location_id: variant2_stock_item.stock_location_id,
+ }
+ },
+ options: [
+ {
+ name: 'Size',
+ position: 1,
+ value: 'M'
+ }
+ ]
+ }
+ }
+ }
+ end
+
+ it 'removes the option type from the product' do
+ send_request
+
+ expect(product.option_types.pluck(:name)).to eq(['size'])
+ end
+ end
+
+ context 'when variant is no longer present in the params' do
+ before do
+ product_params[:variants_attributes].delete('0')
+ end
+
+ it 'removes the variant' do
+ send_request
+
+ expect(product.reload.variant_ids).to eq([variant2.id])
+ end
+ end
+ end
+
+ context 'setting track_inventory to false' do
+ let(:product_params) { { track_inventory: false } }
+
+ before do
+ product.update(track_inventory: true)
+ create(:stock_item, count_on_hand: 20, variant: product.master)
+ end
+
+ it 'removes stock items' do
+ expect(product.master.stock_items.reload.count).to be > 0
+
+ send_request
+ expect(product.master.stock_items.reload.count).to eq(0)
+ end
+ end
+
+ context 'with product properties' do
+ let!(:property_1) { create(:property, name: 'material', presentation: 'Material', kind: 'short_text') }
+ let!(:property_2) { create(:property, name: 'short_description', presentation: 'Short description', kind: 'rich_text') }
+ let!(:property_3) { create(:property, name: 'care', presentation: 'Care', kind: 'rich_text') }
+
+ let(:product_property_1) { create(:product_property, product: product, property: property_1, value: 'Wool') }
+ let(:product_property_2) do
+ create(:product_property, product: product, property: property_2, value: 'Short description with some <a href="https://example.com">link</a>')
+ end
+
+ let(:product_params) do
+ {
+ product_properties_attributes: {
+ '0' => {
+ id: product_property_1.id,
+ property_id: property_1.id,
+ value: 'Better Wool'
+ },
+ '1' => {
+ id: product_property_2.id,
+ property_id: property_2.id,
+ value: ''
+ },
+ '2' => {
+ property_id: property_3.id,
+ value: 'new value'
+ }
+ }
+ }
+ end
+
+ it 'updates 1 product property, creates 1 product property and destroys 1 product property' do
+ send_request
+
+ product = Spree::Product.last
+ expect(product.properties.count).to eq 2
+ expect(product.property('material')).to eq 'Better Wool'
+ expect(product.property('short_description')).to be_nil
+ expect(product.property('care')).to eq 'new value'
+ end
+ end
+
+ it 'will successfully update product' do
+ send_request
+ expect(flash[:success]).to eq("Product #{product.name.inspect} has been successfully updated!")
+ expect(product.reload.status).to eq('draft')
+ expect(product.make_active_at).to eq(Time.current.beginning_of_day)
+ end
+
+ describe 'removing last Label and Tag when param not sent' do
+ before do
+ product.update(tag_list: ['Tag 1'], label_list: ['Label 1'])
+ send_request
+ end
+
+ it 'removes tags successfully' do
+ expect(Spree::Product.find(product.id).tag_list).to be_empty
+ end
+
+ it 'removes labels successfully' do
+ expect(Spree::Product.find(product.id).label_list).to be_empty
+ end
+ end
+ end
+
+ describe 'PUT #clone' do
+ subject(:clone_request) { put :clone, params: { id: product.id } }
+
+ let!(:product) { create(:product, name: 'Product to clone', stores: [store], status: 'active') }
+ let(:cloned_product) { Spree::Product.find_by(name: 'COPY OF Product to clone') }
+
+ context 'when cloning succeeds' do
+ it 'redirects to the cloned product page' do
+ clone_request
+
+ expect(flash[:success]).to eq('Product has been cloned')
+ expect(response).to redirect_to(spree.edit_admin_product_path(cloned_product.slug))
+ end
+ end
+
+ context 'when cloning fails' do
+ before do
+ duplicator_service = double(call: nil)
+ expect(Spree::Products::Duplicator).to receive(:new).and_return(duplicator_service)
+ expect(duplicator_service).to receive(:call).with(product: product).and_return(
+ double(:result, success?: false, value: nil, error: double(:error, value: 'Something went wrong'))
+ )
+ end
+
+ it 'responds with an error' do
+ clone_request
+
+ expect(flash[:error]).to eq('Product could not be cloned. Reason: Something went wrong')
+ expect(response).to redirect_to(spree.edit_admin_product_path(product.slug))
+ end
+ end
+ end
+
+ describe 'POST #bulk_status_update' do
+ let(:product) { create(:product, stores: [store], status: status) }
+ let(:status) { :draft }
+ let(:send_request) { put :bulk_status_update, params: { ids: [product.id], status: 'active' }, format: :turbo_stream }
+
+ shared_examples 'updates status to active' do |status|
+ let(:status) { status }
+
+ it 'updates status to active' do
+ expect(product.status).to eq status.to_s
+ send_request
+ expect(product.reload.active?).to be(true)
+ end
+ end
+
+ Spree::Product.state_machine.states.map(&:name).each do |status|
+ context "when product is in #{status} status" do
+ it_behaves_like 'updates status to active', status
+ end
+ end
+ end
+
+ describe 'PUT #bulk_add_tags' do
+ let(:product) { create(:product, stores: [store], status: :active) }
+ let(:product2) { create(:product, stores: [store], status: :active) }
+ let(:send_request) do
+ put :bulk_add_tags, params: { ids: [product.id, product2.id], tags: ['tag1', 'tag2', 'tag3'] }, format: :turbo_stream
+ end
+
+ it 'adds tags to products' do
+ send_request
+ expect(product.reload.tag_list).to eq(['tag1', 'tag2', 'tag3'])
+ expect(product2.reload.tag_list).to eq(['tag1', 'tag2', 'tag3'])
+ end
+ end
+
+ describe 'PUT #bulk_remove_tags' do
+ let(:product) { create(:product, stores: [store], status: :active, tag_list: ['tag1', 'tag2', 'tag3']) }
+ let(:product2) { create(:product, stores: [store], status: :active, tag_list: ['tag1', 'tag2', 'tag3']) }
+ let(:send_request) do
+ put :bulk_remove_tags, params: { ids: [product.id, product2.id], tags: ['tag1', 'tag2', 'tag3'] }, format: :turbo_stream
+ end
+
+ it 'removes tags from products' do
+ send_request
+ expect(product.reload.tag_list).to eq([])
+ expect(product2.reload.tag_list).to eq([])
+ end
+ end
+
+ describe 'PUR #bulk_remove_from_taxons' do
+ let(:product_ids) { [product.id, product3.id] }
+ let(:taxon_ids) { [category.id, category2.id, category3.id] }
+
+ let(:product) { create(:product, stores: [store], status: :active, taxons: [category, category2]) }
+ let(:product2) { create(:product, stores: [store], status: :active, taxons: [category]) }
+ let(:product3) { create(:product, stores: [store], status: :active, taxons: [category, category3]) }
+ let(:product4) { create(:product, stores: [store], status: :active, taxons: [category, category2]) }
+
+ let!(:category) { create(:taxon) }
+ let!(:category2) { create(:taxon) }
+ let!(:category3) { create(:taxon) }
+
+ let(:send_request) do
+ put :bulk_remove_from_taxons, params: { ids: product_ids, taxon_ids: taxon_ids }, format: :turbo_stream
+ end
+
+ it { expect { send_request }.to change { product.reload.taxons } }
+
+ it 'unassigns the category properly' do
+ send_request
+ expect(product.reload.taxons).to eq []
+ expect(product3.reload.taxons).to eq []
+ end
+
+ it 'touches the products' do
+ product_old_updated_at = product.updated_at
+ product3_old_updated_at = product3.updated_at
+
+ send_request
+
+ expect(product.reload.updated_at).not_to eq(product_old_updated_at)
+ expect(product3.reload.updated_at).not_to eq(product3_old_updated_at)
+ end
+
+ it 'touches the taxons' do
+ category_old_updated_at = category.reload.updated_at
+ category2_old_updated_at = category2.reload.updated_at
+ category3_old_updated_at = category3.reload.updated_at
+
+ send_request
+
+ expect(category.reload.updated_at).not_to eq(category_old_updated_at)
+ expect(category2.reload.updated_at).not_to eq(category2_old_updated_at)
+ expect(category3.reload.updated_at).not_to eq(category3_old_updated_at)
+ end
+
+ it 'reassigns the positions of existing products on the taxon list' do
+ send_request
+
+ expect(product2.reload.classifications.last.position).to eq(1)
+
+ expect(product4.reload.classifications.find_by(taxon_id: category.id).position).to eq(2)
+ expect(product4.reload.classifications.find_by(taxon_id: category2.id).position).to eq(1)
+ end
+
+ context 'for empty list of taxons and products' do
+ let(:product_ids) { [] }
+ let(:taxon_ids) { [] }
+
+ it 'changes nothing' do
+ send_request
+
+ expect(product.reload.taxons).to contain_exactly(category, category2)
+ expect(product3.reload.taxons).to contain_exactly(category, category3)
+ end
+ end
+
+ describe 'auto matching taxons' do
+ let(:product_ids) { [product, product2, product3, product4].pluck(:id) }
+
+ let!(:product) { create(:product, stores: [store], status: :active) }
+ let!(:product2) { create(:product, stores: [store], status: :active) }
+ let!(:product3) { create(:product, stores: [store], status: :archived) }
+ let!(:product4) { create(:product, stores: [store], status: :draft, deleted_at: Time.current) }
+
+ before do
+ Spree::Taxon.delete_all
+ end
+
+ context 'on a store with automatic taxons' do
+ let!(:taxon_1) { create(:automatic_taxon) }
+ let!(:taxon_2) { create(:taxon) }
+
+ it 'auto matches taxons in bulk' do
+ expect { send_request }.
+ to have_enqueued_job(Spree::Products::AutoMatchTaxonsJob).
+ on_queue(Spree.queues.taxons).
+ exactly(:twice)
+
+ jobs = Spree::Products::AutoMatchTaxonsJob.queue_adapter.enqueued_jobs.last(2)
+ expect(jobs.map { |job| job['arguments'] }).to contain_exactly(
+ [product.id],
+ [product2.id]
+ )
+ end
+ end
+
+ context 'on a store without any automatic taxons' do
+ let!(:taxon_1) { create(:taxon) }
+
+ it 'skips auto matching taxons' do
+ expect { send_request }.to_not have_enqueued_job(Spree::Products::AutoMatchTaxonsJob)
+ end
+ end
+ end
+ end
+
+ describe 'PUT #bulk_add_to_taxons' do
+ let(:product_ids) { [product.id, product2.id] }
+ let(:taxon_ids) { [category.id] }
+
+ let(:product) { create(:product, stores: [store], status: :active) }
+ let(:product2) { create(:product, stores: [store], status: :active) }
+
+ let(:category) { create(:taxon) }
+
+ let(:send_request) do
+ put :bulk_add_to_taxons, params: { ids: product_ids, taxon_ids: taxon_ids }, format: :turbo_stream
+ end
+
+ it { expect { send_request }.to change { product.reload.taxons } }
+
+ it 'assigns the category properly' do
+ send_request
+ expect(product.reload.taxons).to contain_exactly(category)
+ expect(product2.reload.taxons).to contain_exactly(category)
+ end
+
+ it 'assigns the product positions on the taxon list' do
+ send_request
+
+ expect(product.reload.classifications.last.position).to eq(1)
+ expect(product2.reload.classifications.last.position).to eq(2)
+ end
+
+ it 'touches the products' do
+ product_old_updated_at = product.updated_at
+ product2_old_updated_at = product2.updated_at
+
+ send_request
+
+ expect(product.reload.updated_at).not_to eq(product_old_updated_at)
+ expect(product2.reload.updated_at).not_to eq(product2_old_updated_at)
+ end
+
+ it 'touches the taxons' do
+ category_old_updated_at = category.reload.updated_at
+
+ send_request
+
+ expect(category.reload.updated_at).not_to eq(category_old_updated_at)
+ end
+
+ context 'for empty list of taxons and products' do
+ let(:product_ids) { [] }
+ let(:taxon_ids) { [] }
+
+ it 'changes nothing' do
+ send_request
+ expect(product.reload.taxons).to be_empty
+ end
+ end
+
+ describe 'auto matching taxons' do
+ let(:product_ids) { [product, product2, product3, product4].pluck(:id) }
+
+ let!(:product3) { create(:product, stores: [store], status: :archived) }
+ let!(:product4) { create(:product, stores: [store], status: :draft, deleted_at: Time.current) }
+
+ before do
+ product
+ product2
+
+ Spree::Taxon.delete_all
+ end
+
+ context 'on a store with automatic taxons' do
+ let!(:taxon_1) { create(:automatic_taxon) }
+ let!(:taxon_2) { create(:taxon) }
+
+ it 'auto matches taxons in bulk' do
+ expect { send_request }.
+ to have_enqueued_job(Spree::Products::AutoMatchTaxonsJob).
+ on_queue(Spree.queues.taxons).
+ exactly(:twice)
+
+ jobs = Spree::Products::AutoMatchTaxonsJob.queue_adapter.enqueued_jobs.last(2)
+ expect(jobs.map { |job| job['arguments'] }).to contain_exactly(
+ [product.id],
+ [product2.id]
+ )
+ end
+ end
+
+ context 'on a store without any automatic taxons' do
+ let!(:taxon_1) { create(:taxon) }
+
+ it 'skips auto matching taxons' do
+ expect { send_request }.to_not have_enqueued_job(Spree::Products::AutoMatchTaxonsJob)
+ end
+ end
+ end
+ end
+
+ describe 'GET #bulk_modal' do
+ context 'as admin' do
+ it 'renders modal' do
+ get :bulk_modal
+
+ expect(response).to render_template('bulk_modal')
+ end
+ end
+ end
+
+ describe 'in_stock/out_of_stock' do
+ let!(:in_stock_product) { create(:product) }
+ let!(:in_stock_variant) { create(:variant, product: in_stock_product) }
+
+ let!(:out_of_stock_product) { create(:product) }
+ let!(:out_of_stock_variant) { create(:variant, product: out_of_stock_product) }
+
+ before do
+ in_stock_product.stock_items.update(count_on_hand: 10, backorderable: false)
+ out_of_stock_product.stock_items.update(count_on_hand: 0, backorderable: false)
+ end
+
+ it 'returns only in stock products' do
+ get :index, params: { q: { in_stock_items: 1 } }
+ expect(assigns(:products).to_a).to eq([in_stock_product])
+ end
+
+ it 'returns only out of stock products' do
+ get :index, params: { q: { out_of_stock_items: 1 } }
+ expect(assigns(:products).to_a).to eq([out_of_stock_product])
+ end
+ end
+end
diff --git a/core/app/jobs/spree/products/queue_status_changed_webhook_job.rb b/core/app/jobs/spree/products/queue_status_changed_webhook_job.rb
new file mode 100644
index 0000000000..5bc0484eeb
--- /dev/null
+++ b/core/app/jobs/spree/products/queue_status_changed_webhook_job.rb
@@ -0,0 +1,12 @@
+module Spree
+ module Products
+ class QueueStatusChangedWebhookJob < Spree::BaseJob
+ queue_as Spree.queues.webhooks
+
+ def perform(product_id, event)
+ product = Spree::Product.find(product_id)
+ product.queue_webhooks_requests!("product.#{event}")
+ end
+ end
+ end
+end
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index 8e0f8536a3..e82905f220 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -36,6 +36,12 @@ module Spree
default_variant_id tax_category default_variant
purchasable? in_stock? backorderable? has_variants?]
+ STATUS_TO_WEBHOOK_EVENT = {
+ 'active' => 'activated',
+ 'draft' => 'drafted',
+ 'archived' => 'archived'
+ }.freeze
+
TRANSLATABLE_FIELDS = %i[name description slug meta_description meta_keywords meta_title].freeze
translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
diff --git a/core/app/services/spree/products/prepare_nested_attributes.rb b/core/app/services/spree/products/prepare_nested_attributes.rb
new file mode 100644
index 0000000000..5c0bda7c4a
--- /dev/null
+++ b/core/app/services/spree/products/prepare_nested_attributes.rb
@@ -0,0 +1,153 @@
+module Spree
+ module Products
+ class PrepareNestedAttributes
+ def initialize(product, store, params, ability)
+ @product = product
+ @store = store
+ @params = params
+ @ability = ability
+ end
+
+ def call
+ if params[:variants_attributes]
+ params[:variants_attributes].each do |key, variant_params|
+ existing_variant = variant_params[:id].presence && @product.variants.find_by(id: variant_params[:id])
+ variants_to_remove.delete(variant_params[:id]) if variant_params[:id].present?
+
+ variant_params.delete(:prices_attributes) unless can_update_prices?
+
+ variant_params[:option_value_variants_attributes] = update_option_value_variants(variant_params.delete(:options), existing_variant)
+
+ variant_params.delete(:stock_items_attributes) unless can_update_stock_items?
+
+ params[:variants_attributes].delete(key) if variant_params.blank?
+ end
+ params[:variants_attributes] = params[:variants_attributes].merge(removed_variants_attributes)
+
+ params[:product_option_types_attributes] = product_option_types_params.merge(removed_product_option_types_attributes)
+ elsif params[:master_attributes]
+ params[:master_attributes].delete(:stock_items_attributes) unless can_update_stock_items?
+ end
+
+ params.delete(:variants_attributes) if params[:variants_attributes].blank?
+
+ # mark resource properties to be removed
+ # when value is left blank
+ if params[:product_properties_attributes].present?
+ params[:product_properties_attributes].each do |key, product_property_params|
+ next unless product_property_params[:id].present?
+ next if product_property_params[:value].present?
+
+ # https://api.rubyonrails.org/v7.1.3.4/classes/ActiveRecord/NestedAttributes/ClassMethods.html
+ params[:product_properties_attributes][key]['_destroy'] = '1'
+ end
+ end
+
+ # ensure there is at least one store
+ params[:store_ids] = [store.id] if params[:store_ids].blank?
+
+ params
+ end
+
+ private
+
+ attr_reader :product, :store, :params, :ability
+
+ delegate :can?, :cannot?, to: :ability
+
+ def product_option_types_params
+ @product_option_types_params ||= {}
+ end
+
+ def product_option_types_to_remove
+ @product_option_types_to_remove ||= product.product_option_type_ids
+ end
+
+ def variants_to_remove
+ @variants_to_remove ||= product.variant_ids
+ end
+
+ def can_update_prices?
+ @can_update_prices ||= product.new_record? || can?(:manage, Spree::Price.new(variant_id: product.default_variant.id))
+ end
+
+ def can_manage_option_types?
+ @can_manage_option_types ||= product.new_record? || can?(:manage_option_types, product)
+ end
+
+ def can_update_stock_items?
+ @can_update_stock_items ||= product.new_record? || can?(:manage, Spree::StockItem.new(variant_id: product.default_variant.id))
+ end
+
+ def can_remove_variants?
+ @can_remove_variants ||= product.persisted? && can?(:destroy, product.default_variant)
+ end
+
+ def removed_variants_attributes
+ return {} unless can_remove_variants?
+
+ attributes = {}
+ last_index = params[:variants_attributes].keys.map(&:to_i).max
+ variants_to_remove.each_with_index do |variant_id, index|
+ attributes[(index + last_index + 1).to_s] = { id: variant_id, _destroy: '1' }
+ end
+
+ attributes
+ end
+
+ def removed_product_option_types_attributes
+ return {} unless can_manage_option_types?
+
+ attributes = {}
+ last_index = product_option_types_params.keys.map(&:to_i).max
+ product_option_types_to_remove.each_with_index do |product_option_type_id, index|
+ attributes[(last_index + index + 1).to_s] = { id: product_option_type_id, _destroy: '1' }
+ end
+
+ attributes
+ end
+
+ def update_option_value_variants(option_value_params, existing_variant)
+ return {} unless option_value_params.present?
+ return {} unless can_manage_option_types?
+
+ option_value_variant_params = {}
+
+ option_value_params.each_with_index do |opt, index|
+ option_type = Spree::OptionType.where(name: opt[:name].parameterize).first_or_initialize do |o|
+ o.name = o.presentation = opt[:name]
+ o.save!
+ end
+ option_value = option_type.option_values.where(name: opt[:value].parameterize).first_or_initialize do |o|
+ o.name = o.presentation = opt[:value]
+ o.save!
+ end
+
+ existing_option_value_variant = existing_variant&.option_value_variants&.find { |ovv| ovv.option_value_id == option_value.id }
+
+ option_value_variant_params[index] = { id: existing_option_value_variant&.id, option_value_id: option_value.id }.compact_blank
+
+ next if product_option_types_params.find { |_i, v| v[:option_type_id] == option_type.id }
+
+ existing_product_option_type = @product.product_option_types.find { |pot| pot.option_type_id == option_type.id }
+
+ if existing_product_option_type
+ product_option_types_to_remove.delete(existing_product_option_type.id)
+ product_option_types_params[opt[:position]] = {
+ id: existing_product_option_type.id,
+ position: opt[:position],
+ option_type_id: option_type.id
+ }
+ else
+ product_option_types_params[opt[:position]] = {
+ option_type_id: option_type.id,
+ position: opt[:position]
+ }
+ end
+ end
+
+ option_value_variant_params
+ end
+ end
+ end
+end
diff --git a/core/app/services/spree/products/queue_status_changed_webhook.rb b/core/app/services/spree/products/queue_status_changed_webhook.rb
new file mode 100644
index 0000000000..dbdb176357
--- /dev/null
+++ b/core/app/services/spree/products/queue_status_changed_webhook.rb
@@ -0,0 +1,17 @@
+module Spree
+ module Products
+ class QueueStatusChangedWebhook
+ def self.call(ids:, event:)
+ return false if ids.blank? || event.blank?
+
+ # for ActiveJob 7.1+
+ if ActiveJob.respond_to?(:perform_all_later)
+ jobs = ids.map { |id| Spree::Products::QueueStatusChangedWebhookJob.new(id, event) }
+ ActiveJob.perform_all_later(jobs)
+ else
+ ids.each { |id| Spree::Products::QueueStatusChangedWebhookJob.perform_later(id, event) }
+ end
+ end
+ end
+ end
+end
diff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rb
index 44447ef7df..c4b3122a21 100644
--- a/core/lib/spree/core.rb
+++ b/core/lib/spree/core.rb
@@ -92,7 +92,8 @@ module Spree
variants: :default,
taxons: :default,
stock_location_stock_items: :default,
- coupon_codes: :default
+ coupon_codes: :default,
+ webhooks: :default
)
end