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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add ability to tag customers, products and orders (#12172)
Damian Legawiecddf3a92f00c4
diff --git a/api/app/serializers/spree/v2/storefront/product_serializer.rb b/api/app/serializers/spree/v2/storefront/product_serializer.rbindex 084612031b..da60d2d55c 100644--- a/api/app/serializers/spree/v2/storefront/product_serializer.rb+++ b/api/app/serializers/spree/v2/storefront/product_serializer.rb@@ -48,6 +48,9 @@ module Spreeproduct.localized_slugs_for_store(params[:store])end+ attribute :tags, &:tag_list+ attribute :labels, &:label_list+has_many :variantshas_many :option_typeshas_many :product_propertiesdiff --git a/api/app/serializers/spree/v2/storefront/user_serializer.rb b/api/app/serializers/spree/v2/storefront/user_serializer.rbindex c3f88d400a..9e8fed5402 100644--- a/api/app/serializers/spree/v2/storefront/user_serializer.rb+++ b/api/app/serializers/spree/v2/storefront/user_serializer.rb@@ -6,6 +6,8 @@ module Spreeattributes :email, :first_name, :selected_locale, :last_name, :public_metadata+ attribute :tags, &:tag_list+attribute :store_credits do |user|user.total_available_store_creditend@@ -15,16 +17,16 @@ module Spreeendhas_one :default_billing_address,- id_method_name: :bill_address_id,- object_method_name: :bill_address,- record_type: :address,- serializer: :address+ id_method_name: :bill_address_id,+ object_method_name: :bill_address,+ record_type: :address,+ serializer: :addresshas_one :default_shipping_address,- id_method_name: :ship_address_id,- object_method_name: :ship_address,- record_type: :address,- serializer: :address+ id_method_name: :ship_address_id,+ object_method_name: :ship_address,+ record_type: :address,+ serializer: :addressendendenddiff --git a/api/spec/requests/spree/api/v2/storefront/products_spec.rb b/api/spec/requests/spree/api/v2/storefront/products_spec.rbindex 67163fb5bf..e2325379f5 100644--- a/api/spec/requests/spree/api/v2/storefront/products_spec.rb+++ b/api/spec/requests/spree/api/v2/storefront/products_spec.rb@@ -22,7 +22,7 @@ describe 'API V2 Storefront Products Spec', type: :request dolet!(:new_property) { create(:property) }let!(:product_with_property) { create(:product, stores: [store]) }let!(:product_property) { create(:product_property, property: new_property, product: product_with_property, value: 'Some Value') }- let!(:product_property2) { create(:product_property, property: property, product: product_with_property, value: 'Some Value 2') }+ let!(:product_property2) { create(:product_property, property: property, product: product_with_property, value: 'Some Value 2') }# We need to make sure that the default locale is reset before and after every test casebefore do@@ -64,7 +64,7 @@ describe 'API V2 Storefront Products Spec', type: :request docontext 'when current store is store' dobefore { get "/api/v2/storefront/products?filter[ids]=#{product_with_taxon.id}" }- it 'should return only store taxons ralated to product', aggregate_failures: true do+ it 'returns only store taxons ralated to product', :aggregate_failures doexpect(json_response['data'][0]).to have_relationship(:taxons).with_data([{ 'id' => taxon.id.to_s, 'type' => 'taxon' }])expect(json_response['data'][0]).not_to have_relationship(:taxons).with_data([{ 'id' => taxon2.id.to_s, 'type' => 'taxon' }])end@@ -78,7 +78,7 @@ describe 'API V2 Storefront Products Spec', type: :request doget "/api/v2/storefront/products?filter[ids]=#{product_with_taxon.id}"end- it 'should return only store2 taxons ralated to product', aggregate_failures: true do+ it 'returns only store2 taxons ralated to product', :aggregate_failures doexpect(json_response['data'][0]).to have_relationship(:taxons).with_data([{ 'id' => taxon2.id.to_s, 'type' => 'taxon' }])expect(json_response['data'][0]).not_to have_relationship(:taxons).with_data([{ 'id' => taxon.id.to_s, 'type' => 'taxon' }])end@@ -158,9 +158,9 @@ describe 'API V2 Storefront Products Spec', type: :request docontext 'with specified options' docontext 'with no locale set' do- before {+ before doget "/api/v2/storefront/products?filter[options][#{option_type.name}]=#{option_value.name}&include=option_types,variants.option_values"- }+ endit_behaves_like 'returns 200 HTTP status'@@ -238,6 +238,64 @@ describe 'API V2 Storefront Products Spec', type: :request doendend+ context 'with specified tags' do+ let!(:product_1) { create(:product, tag_list: ['tag_1', 'tag_2']) }+ let!(:product_2) { create(:product, tag_list: ['tag_2']) }+ let!(:product_3) { create(:product, tag_list: ['tag_3']) }++ before do+ get "/api/v2/storefront/products?filter[tags]=#{tags_list}"+ end++ context 'when filtering by tag_1/tag_2 tags' do+ let(:tags_list) { 'tag_1,tag_2' }++ it_behaves_like 'returns 200 HTTP status'++ it 'returns products with specified tags' do+ expect(json_response['data']).to include(have_id(product_1.id.to_s))+ expect(json_response['data']).to include(have_id(product_2.id.to_s))+ expect(json_response['data']).not_to include(have_id(product_3.id.to_s))+ end+ end++ context 'when filtering by tag_2/tag_3 tags' do+ let(:tags_list) { 'tag_2,tag_3' }++ it_behaves_like 'returns 200 HTTP status'++ it 'returns products with specified tags' do+ expect(json_response['data']).to include(have_id(product_1.id.to_s))+ expect(json_response['data']).to include(have_id(product_2.id.to_s))+ expect(json_response['data']).to include(have_id(product_3.id.to_s))+ end+ end++ context 'when filtering by tag_3 tags' do+ let(:tags_list) { 'tag_3' }++ it_behaves_like 'returns 200 HTTP status'++ it 'returns products with specified tags' do+ expect(json_response['data']).not_to include(have_id(product_1.id.to_s))+ expect(json_response['data']).not_to include(have_id(product_2.id.to_s))+ expect(json_response['data']).to include(have_id(product_3.id.to_s))+ end+ end++ context 'when filtering by non-existent tags' do+ let(:tags_list) { 'tag_4,tag5' }++ it_behaves_like 'returns 200 HTTP status'++ it 'returns products with specified tags' do+ expect(json_response['data']).not_to include(have_id(product_1.id.to_s))+ expect(json_response['data']).not_to include(have_id(product_2.id.to_s))+ expect(json_response['data']).not_to include(have_id(product_3.id.to_s))+ end+ end+ end+context 'with multiple specified options' dolet!(:color) { create(:option_type, :color) }let!(:green_color) { create(:option_value, option_type: color, name: 'green') }@@ -511,9 +569,9 @@ describe 'API V2 Storefront Products Spec', type: :request doit 'returns products sorted by name' doexpect(json_response['data'].count).to eq store.products.available.count- expect(json_response['data'].pluck(:id)).to eq store.products.i18n.available- .select("#{Spree::Product.table_name}.*, #{Spree::Product::Translation.table_name}_pl.name")- .order(:name).map(&:id).map(&:to_s)+ expect(json_response['data'].pluck(:id)).to eq store.products.i18n.available.+ select("#{Spree::Product.table_name}.*, #{Spree::Product::Translation.table_name}_pl.name").+ order(:name).map(&:id).map(&:to_s)endendend@@ -537,9 +595,9 @@ describe 'API V2 Storefront Products Spec', type: :request doit 'returns products sorted by name' doexpect(json_response['data'].count).to eq store.products.available.count- expect(json_response['data'].pluck(:id)).to eq store.products.available- .select("#{Spree::Product.table_name}.*, #{Spree::Product::Translation.table_name}_pl.name")- .order(name: :desc).map(&:id).map(&:to_s)+ expect(json_response['data'].pluck(:id)).to eq store.products.available.+ select("#{Spree::Product.table_name}.*, #{Spree::Product::Translation.table_name}_pl.name").+ order(name: :desc).map(&:id).map(&:to_s)endendend@@ -644,7 +702,7 @@ describe 'API V2 Storefront Products Spec', type: :request doendend- let(:skus_array) { json_response['data'].map { |p| p['attributes']['sku']} }+ let(:skus_array) { json_response['data'].map { |p| p['attributes']['sku'] } }let(:available_products_with_master) { products + [product_with_option, in_stock_product, not_backorderable_product, product_with_property] }let(:params) { '' }@@ -699,7 +757,7 @@ describe 'API V2 Storefront Products Spec', type: :request docontext 'sorting by both price and sku' dolet(:skus_array) { json_response['data'].map { |p| p['attributes']['sku'] } }- before { get "/api/v2/storefront/products?sort=-sku,price" }+ before { get '/api/v2/storefront/products?sort=-sku,price' }it_behaves_like 'returns 200 HTTP status'@@ -782,8 +840,8 @@ describe 'API V2 Storefront Products Spec', type: :request docontext 'return filter metadata' dolet!(:option_type2) { create(:option_type) }- let!(:option_type2_value1) { create(:option_value, option_type: option_type2 )}- let!(:option_type2_value2) { create(:option_value, option_type: option_type2 )}+ let!(:option_type2_value1) { create(:option_value, option_type: option_type2) }+ let!(:option_type2_value2) { create(:option_value, option_type: option_type2) }let(:product_with_option_type2) { create(:product, option_types: [option_type2], stores: [store]) }let!(:product_with_option_type2_variant1) { create(:variant, product: product_with_option_type2, option_values: [option_type2_value1]) }@@ -891,9 +949,9 @@ describe 'API V2 Storefront Products Spec', type: :request doendcontext 'when filter by product property is applied' do- before {+ before doget "/api/v2/storefront/products?filter[properties][#{property.filter_param}]=#{product_property.filter_param}"- }+ endit 'returns list of all available filters for products' doexpect(json_response['meta']['filters']['option_types'].count).to eq 2@@ -1158,7 +1216,7 @@ describe 'API V2 Storefront Products Spec', type: :request docontext 'with slug in translated locale' dolet(:store2) { create(:store, default_locale: 'en', supported_locales: 'en,pl,es') }let(:product_with_slug) { create(:product, stores: [store2], slug: default_locale_slug) }- let!(:translation2) { product_with_slug.translations.create(slug: translated_slug, locale: 'es') }+ let!(:translation2) { product_with_slug.translations.create(slug: translated_slug, locale: 'es') }let(:default_locale_slug) { 'test-slug-en' }let(:translated_slug) { 'test-slug-es' }diff --git a/api/spec/serializers/spree/v2/storefront/product_serializer_spec.rb b/api/spec/serializers/spree/v2/storefront/product_serializer_spec.rbnew file mode 100644index 0000000000..ae45a8ca16--- /dev/null+++ b/api/spec/serializers/spree/v2/storefront/product_serializer_spec.rb@@ -0,0 +1,25 @@+require 'spec_helper'++describe Spree::V2::Storefront::ProductSerializer do+ subject { described_class.new(product, params: serializer_params).serializable_hash }++ include_context 'API v2 serializers params'++ let(:product) { create(:product) }++ context 'with tags' do+ before { product.tag_list.add('tag1', 'tag2') }++ it 'returns tags' do+ expect(subject[:data][:attributes][:tags]).to eq ['tag1', 'tag2']+ end+ end++ context 'with labels' do+ before { product.label_list.add('label1', 'label2') }++ it 'returns labels' do+ expect(subject[:data][:attributes][:labels]).to eq ['label1', 'label2']+ end+ end+enddiff --git a/api/spec/serializers/spree/v2/storefront/user_serializer_spec.rb b/api/spec/serializers/spree/v2/storefront/user_serializer_spec.rbindex 6d471cbfa8..af4e67fa9d 100644--- a/api/spec/serializers/spree/v2/storefront/user_serializer_spec.rb+++ b/api/spec/serializers/spree/v2/storefront/user_serializer_spec.rb@@ -7,7 +7,7 @@ describe Spree::V2::Storefront::UserSerializer dolet(:user) { create(:user_with_addresses) }- it { expect(subject.serializable_hash).to be_kind_of(Hash) }+ it { expect(subject.serializable_hash).to be_a(Hash) }it doexpect(subject.serializable_hash).to eq(@@ -22,6 +22,7 @@ describe Spree::V2::Storefront::UserSerializer dolast_name: user.last_name,public_metadata: {},selected_locale: nil,+ tags: [],store_credits: 0},relationships: {@@ -53,14 +54,15 @@ describe Spree::V2::Storefront::UserSerializer doit doexpect(subject.serializable_hash[:data][:attributes]).to eq({- completed_orders: 2,- email: user.email,- first_name: user.first_name,- last_name: user.last_name,- public_metadata: {},- selected_locale: nil,- store_credits: 0.1e3- })+ completed_orders: 2,+ email: user.email,+ first_name: user.first_name,+ last_name: user.last_name,+ public_metadata: {},+ selected_locale: nil,+ store_credits: 0.1e3,+ tags: []+ })endenddiff --git a/bin/sandbox.sh b/bin/sandbox.shindex aeaa0dd792..71581690bd 100755--- a/bin/sandbox.sh+++ b/bin/sandbox.sh@@ -76,6 +76,7 @@ bin/rails db:drop || truebin/rails db:createbin/rails g spree:install --auto-accept --user_class=Spree::User --sample=truebin/rails g spree:emails:install-bin/rails g spree:admin:install+# bin/rails g spree:admin:installbin/rails g spree:auth:installbin/rails g spree_gateway:install+bin/rake acts_as_taggable_on_engine:install:migrationsdiff --git a/core/app/finders/spree/products/find.rb b/core/app/finders/spree/products/find.rbindex f66b2a355b..31ae80c900 100644--- a/core/app/finders/spree/products/find.rb+++ b/core/app/finders/spree/products/find.rb@@ -28,6 +28,7 @@ module Spree@in_stock = params.dig(:filter, :in_stock)@backorderable = params.dig(:filter, :backorderable)@purchasable = params.dig(:filter, :purchasable)+ @tags = params.dig(:filter, :tags).to_s.split(',').compact_blankenddef execute@@ -41,6 +42,7 @@ module Spreeproducts = by_options(products)products = by_option_value_ids(products)products = by_properties(products)+ products = by_tags(products)products = include_deleted(products)products = include_discontinued(products)products = show_only_stock(products)@@ -54,7 +56,7 @@ module Spreeprivateattr_reader :ids, :skus, :price, :currency, :taxons, :concat_taxons, :name, :options, :option_value_ids, :scope,- :sort_by, :deleted, :discontinued, :properties, :store, :in_stock, :backorderable, :purchasable+ :sort_by, :deleted, :discontinued, :properties, :store, :in_stock, :backorderable, :purchasable, :tagsdef ids?ids.present?@@ -194,6 +196,12 @@ module Spreeproducts.where(id: product_ids)end+ def by_tags(products)+ return products if tags.empty?++ products.tagged_with(tags, any: true)+ end+def option_types_count(option_value_ids)Spree::OptionValue.where(id: option_value_ids).diff --git a/core/app/models/concerns/spree/user_methods.rb b/core/app/models/concerns/spree/user_methods.rbindex 6ddbea920d..5c8e7690dc 100644--- a/core/app/models/concerns/spree/user_methods.rb+++ b/core/app/models/concerns/spree/user_methods.rb@@ -16,6 +16,8 @@ module Spreeattr_accessor :use_billing+ acts_as_taggable_on :tags+has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :user_id, dependent: :destroyhas_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'@@ -27,7 +29,7 @@ module Spreehas_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :user_id- self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses]+ self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags]self.whitelisted_ransackable_attributes = %w[id email]def self.with_email(query)diff --git a/core/app/models/spree/order.rb b/core/app/models/spree/order.rbindex 6e1bae2836..22fb5bdea0 100644--- a/core/app/models/spree/order.rb+++ b/core/app/models/spree/order.rb@@ -83,6 +83,8 @@ module Spreeattribute :state_machine_resumed, :boolean+ acts_as_taggable_on :tags+if Spree.user_classbelongs_to :user, class_name: "::#{Spree.user_class}", optional: trueelse@@ -488,10 +490,10 @@ module Spreedef coupon_code=(code)@coupon_code = begin- code.strip.downcase- rescue StandardError- nil- end+ code.strip.downcase+ rescue StandardError+ nil+ endenddef can_add_coupon?diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rbindex 90221a005a..29a517a18e 100644--- a/core/app/models/spree/product.rb+++ b/core/app/models/spree/product.rb@@ -64,6 +64,7 @@ module Spreefriendly_id :slug_candidates, use: [:history, :scoped, :mobility], scope: spree_base_uniqueness_scopeacts_as_paranoidauto_strip_attributes :name+ acts_as_taggable_on :tags, :labels# we need to have this callback before any dependent: :destroy associations# https://github.com/rails/rails/issues/3458@@ -163,7 +164,7 @@ module Spreealias options product_option_types- self.whitelisted_ransackable_associations = %w[taxons stores variants_including_master master variants]+ self.whitelisted_ransackable_associations = %w[taxons stores variants_including_master master variants tags labels]self.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status]self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon price_between]@@ -230,13 +231,11 @@ module Spree## @return [Spree::Variant]def default_variant- @default_variant ||= begin- if Spree::Config[:track_inventory_levels] && available_variant = variants.detect(&:purchasable?)- available_variant- else- has_variants? ? variants.first : find_or_build_master- end- end+ @default_variant ||= if Spree::Config[:track_inventory_levels] && available_variant = variants.detect(&:purchasable?)+ available_variant+ else+ has_variants? ? variants.first : find_or_build_master+ endend# Returns default Variant ID for Product@@ -417,7 +416,7 @@ module Spreedef brand@brand ||= if Spree.use_translations?- taxons.joins(:taxonomy).+ taxons.joins(:taxonomy).join_translation_table(Taxonomy).find_by(Taxonomy.translation_table_alias => { name: Spree.t(:taxonomy_brands_name) })else@@ -599,7 +598,7 @@ module Spreedef remove_taxon(taxon)removed_classifications = classifications.where(taxon: taxon)- removed_classifications.each &:remove_from_list+ removed_classifications.each(&:remove_from_list)enddef discontinue_on_must_be_later_than_make_active_atdiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex 9a14cfb9b7..038f9787b6 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -7,6 +7,7 @@ require 'active_storage/engine'require 'active_merchant'require 'acts_as_list'+require 'acts-as-taggable-on'require 'auto_strip_attributes'require 'awesome_nested_set'require 'cancan'@@ -154,4 +155,4 @@ require 'spree/core/preferences/store'require 'spree/core/preferences/scoped_store'require 'spree/core/preferences/runtime_configuration'-require "spree/core/webhooks"+require 'spree/core/webhooks'diff --git a/core/lib/spree/permitted_attributes.rb b/core/lib/spree/permitted_attributes.rbindex e3702cb054..af6d2539fe 100644--- a/core/lib/spree/permitted_attributes.rb+++ b/core/lib/spree/permitted_attributes.rb@@ -94,7 +94,11 @@ module Spree:option_values_hash, :weight, :height, :width, :depth,:shipping_category_id, :tax_category_id,:cost_currency, :cost_price, :compare_at_price,- { option_type_ids: [], taxon_ids: [] }+ {+ tag_list: [],+ option_type_ids: [],+ taxon_ids: []+ }]@@property_attributes = [:name, :presentation]@@ -147,14 +151,15 @@ module Spree# TODO: Should probably use something like Spree.user_class.attributes@@user_attributes = [:email, :bill_address_id, :ship_address_id, :password, :first_name, :last_name,- :password_confirmation, { public_metadata: {}, private_metadata: {} }, :selected_locale]+ :password_confirmation, :selected_locale,+ { public_metadata: {}, private_metadata: {}, tag_list: [] }]@@variant_attributes = [:name, :presentation, :cost_price, :discontinue_on, :lock_version,:position, :track_inventory,:product_id, :product, :option_values_attributes, :price, :compare_at_price,:weight, :height, :width, :depth, :sku, :barcode, :cost_currency,- :weight_unit, :dimensions_unit,+ :weight_unit, :dimensions_unit,{ options: [:name, :value], option_value_ids: [] }]diff --git a/core/lib/spree/testing_support/common_rake.rb b/core/lib/spree/testing_support/common_rake.rbindex 09c9ccec59..9875cdad9a 100644--- a/core/lib/spree/testing_support/common_rake.rb+++ b/core/lib/spree/testing_support/common_rake.rb@@ -23,6 +23,8 @@ namespace :common dosystem('bin/rails stimulus:install')end+ system('bin/rake acts_as_taggable_on_engine:install:migrations')+Spree::InstallGenerator.start ["--lib_name=#{ENV['LIB_NAME']}",'--auto-accept',diff --git a/core/spec/services/spree/account/update_spec.rb b/core/spec/services/spree/account/update_spec.rbindex 20120ea08d..b4f102a75d 100644--- a/core/spec/services/spree/account/update_spec.rb+++ b/core/spec/services/spree/account/update_spec.rb@@ -108,19 +108,6 @@ module Spreeendendend-- context 'when no params are given' do- let(:user_params) do- {}- end-- it_behaves_like 'user not created'- it_behaves_like 'successful response'-- it 'does not change user data at all' do- expect(value).to have_attributes(user.attributes)- end- endendendenddiff --git a/core/spree_core.gemspec b/core/spree_core.gemspecindex 4a658874b2..035b3f0fd1 100644--- a/core/spree_core.gemspec+++ b/core/spree_core.gemspec@@ -35,6 +35,7 @@ Gem::Specification.new do |s|s.add_dependency 'activemerchant', '~> 1.67's.add_dependency 'acts_as_list', '>= 0.8'+ s.add_dependency 'acts-as-taggable-on's.add_dependency 'auto_strip_attributes', '~> 2.6's.add_dependency 'awesome_nested_set', '~> 3.3', '>= 3.3.1's.add_dependency 'carmen', '>= 1.0'diff --git a/docs/api-reference/storefront.yaml b/docs/api-reference/storefront.yamlindex c365bf06b4..1d770d438b 100644--- a/docs/api-reference/storefront.yaml+++ b/docs/api-reference/storefront.yaml@@ -3199,6 +3199,16 @@ components:localized_slugs:type: objectdescription: Provides product's slugs in other locales+ tags:+ type: array+ items:+ type: string+ description: List of tags associated with the product+ labels:+ type: array+ items:+ type: string+ description: List of labels associated with the productrelationships:type: objectproperties:@@ -3853,6 +3863,11 @@ components:type: numberexample: 3description: Number of placed Orders by this User+ tags:+ type: array+ items:+ type: string+ description: List of tags associated with the userpublic_metadata:type: objectexample:@@ -5329,6 +5344,9 @@ components:selected_locale: 'en'store_credits: 0completed_orders: 0+ tags:+ - VIP+ - supplierpublic_metadata:user_segment: supplierrelationships:@@ -6581,6 +6599,13 @@ components:en: bomber-jacketde: bomberjackefr: blouson+ tags:+ - bomber+ - jacket+ - winter+ labels:+ - new+ - salerelationships:variants:data: