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 support for importing metafields in Product CSV importer (#13228)
Damian Legawiec5e08e3bb7128
diff --git a/admin/app/views/spree/admin/imports/_mapping.html.erb b/admin/app/views/spree/admin/imports/_mapping.html.erbindex 60861c9076..db8f642c72 100644--- a/admin/app/views/spree/admin/imports/_mapping.html.erb+++ b/admin/app/views/spree/admin/imports/_mapping.html.erb@@ -3,8 +3,7 @@<%= render 'spree/admin/imports/mapping_icon', mapping: mapping %></div><div class="text-wrap w-40 px-2 py-3">- <%= @import.import_schema.fields.find { |field| field[:name] == mapping.schema_field }[:label] %>-+ <%= mapping.schema_field_label %><code class="ml-2"><%= mapping.schema_field %></code></div><div class="w-50 px-2 py-3">diff --git a/core/app/models/spree/import.rb b/core/app/models/spree/import.rbindex 86da885cdd..27b84880b4 100644--- a/core/app/models/spree/import.rb+++ b/core/app/models/spree/import.rb@@ -69,19 +69,26 @@ module Spree#preference :delimiter, :string, default: ','+ # Returns true if the import is in mapping state+ # @return [Boolean]def mapping?status == 'mapping'end+ # Returns true if the import is processing or completed mapping+ # @return [Boolean]def processing?['processing', 'completed_mapping'].include?(status)end+ # Returns true if the import is complete+ # @return [Boolean]def complete?status == 'completed'end- # eg. Spree::Exports::Products => Spree::Product+ # Returns the model class for the import+ # @return [Class]def model_classif type == 'Spree::Imports::Customers'Spree.user_class@@ -90,34 +97,64 @@ module Spreeendend+ # Returns the import schema for the import+ # @return [Spree::ImportSchema]def import_schema"Spree::ImportSchemas::#{type.demodulize}".safe_constantize.newend+ # Returns the row processor class for the import+ # @return [Class]def row_processor_class"Spree::ImportRowProcessors::#{type.demodulize.singularize}".safe_constantizeend+ # Returns the fields for the import schema+ # If model supports metafields, it will include the metafield definitions for this model+ # @return [Array<Hash>]def schema_fields- import_schema.fields+ base_fields = import_schema.fields++ # Dynamically add metafield definitions if the model supports metafields+ if model_class_supports_metafields?+ metafield_fields = metafield_definitions_for_model.map do |definition|+ {+ name: definition.csv_header_name,+ label: definition.name+ }+ end+ base_fields + metafield_fields+ else+ base_fields+ endend+ # Returns the file columns that are not mapped+ # @return [Array<String>]def unmapped_file_columnscsv_headers.reject { |header| mappings.mapped.exists?(file_column: header) }end+ # Returns the required fields for the import schema+ # @return [Array<String>]def required_fieldsimport_schema.required_fieldsend+ # Returns the mapped fields for the import schema+ # @return [Array<String>]def mapped_fields@mapped_fields ||= mappings.mapped.where(schema_field: required_fields)end+ # Returns true if the mapping is done+ # @return [Boolean]def mapping_done?mapped_fields.count == required_fields.countend+ # Returns the display name for the import+ # @return [String]def display_name"#{Spree.t(type.demodulize.pluralize.downcase)} #{number}"end@@ -153,10 +190,14 @@ module Spreeendend+ # Creates rows asynchronously+ # @return [void]def create_rows_asyncSpree::Imports::CreateRowsJob.set(wait: 2.seconds).perform_later(id)end+ # Processes rows asynchronously+ # @return [void]def process_rows_asyncSpree::Imports::ProcessRowsJob.perform_later(id)end@@ -173,19 +214,27 @@ module Spreebroadcast_update_to "import_#{id}_loader", target: 'loader', partial: 'spree/admin/imports/loader', locals: { import: self }end+ # Returns the current ability for the import+ # @return [Spree::Ability]def current_ability@current_ability ||= Spree::Dependencies.ability_class.constantize.new(user, { store: store })endclass << self+ # Returns the available types for the import+ # @return [Array<Class>]def available_typesRails.application.config.spree.import_typesend+ # Returns the available models for the import+ # @return [Array<Class>]def available_modelsavailable_types.map(&:model_class)end+ # Returns the type for the model+ # @return [Class]def type_for_model(model)available_types.find { |type| type.model_class.to_s == model.to_s }end@@ -214,5 +263,17 @@ module Spreeerrors.add(:attachment, :content_type) unless attachment.content_type.in?(%w[text/csv])end++ def model_class_supports_metafields?+ return false unless model_class.present?++ model_class.included_modules.include?(Spree::Metafields)+ end++ def metafield_definitions_for_model+ return [] unless model_class.present?++ Spree::MetafieldDefinition.for_resource_type(model_class.name)+ endendenddiff --git a/core/app/models/spree/import_mapping.rb b/core/app/models/spree/import_mapping.rbindex dcc9a99f54..36cea06a64 100644--- a/core/app/models/spree/import_mapping.rb+++ b/core/app/models/spree/import_mapping.rb@@ -3,7 +3,7 @@ module Spree## Associations#- belongs_to :import+ belongs_to :import, class_name: 'Spree::Import', inverse_of: :mappings, required: true## Validations@@ -18,16 +18,29 @@ module Spreescope :required, -> { where(schema_field: import.required_fields) }scope :mapped, -> { where.not(file_column: [nil, '']) }+ # Returns true if the mapping is required+ # @return [Boolean]def required?import.required_fields.include?(schema_field)end+ # Returns true if the mapping has a file column+ # @return [Boolean]def mapped?file_column.present?enddef try_to_auto_assign_file_column(csv_headers)- self.file_column = csv_headers.find { |header| header.parameterize.downcase.strip == schema_field.parameterize.downcase.strip }+ self.file_column = csv_headers.find { |header| header.parameterize.underscore.downcase.strip == schema_field.parameterize.underscore.downcase.strip }+ end++ # Returns the label for the schema field+ # @return [String]+ def schema_field_label+ @schema_field_label ||= begin+ field = import.schema_fields.find { |field| field[:name] == schema_field }+ field[:label] if field.present?+ endendendenddiff --git a/core/app/services/spree/imports/row_processors/product_variant.rb b/core/app/services/spree/imports/row_processors/product_variant.rbindex 670d754682..5d684d8813 100644--- a/core/app/services/spree/imports/row_processors/product_variant.rb+++ b/core/app/services/spree/imports/row_processors/product_variant.rb@@ -60,6 +60,7 @@ module Spreeproduct = assign_attributes_to_product(product)product.save!+ handle_metafields(product)productend@@ -163,6 +164,20 @@ module Spreeendend+ def handle_metafields(product)+ return unless product.class.included_modules.include?(Spree::Metafields)++ metafield_attributes = attributes.select { |key, _value| key.to_s.start_with?('metafield.') }++ metafield_attributes.each do |attribute_key, value|+ next if value.blank?++ # Extract namespace.key from "metafield.namespace.key"+ full_key = attribute_key.to_s.sub(/^metafield\./, '')+ product.set_metafield(full_key, value.to_s.strip)+ end+ end+def to_spree_status(status)case status.strip.downcasewhen 'active'diff --git a/core/spec/fixtures/files/products_import.csv b/core/spec/fixtures/files/products_import.csvindex a436f88c0d..69e31eaecd 100644--- a/core/spec/fixtures/files/products_import.csv+++ b/core/spec/fixtures/files/products_import.csv@@ -1,18 +1,18 @@-slug,sku,name,status,vendor_name,brand_name,description,meta_title,meta_description,meta_keywords,tags,labels,price,compare_at_price,currency,width,height,depth,dimensions_unit,weight,weight_unit,available_on,discontinue_on,track_inventory,inventory_count,inventory_backorderable,tax_category,digital,image1_src,image2_src,image3_src,option1_name,option1_value,option2_name,option2_value,option3_name,option3_value,category1,category2,category3,metafield.properties.fit,metafield.properties.manufacturer,metafield.properties.material-denim-shirt,"",Denim Shirt,draft,,,Adipisci sapiente velit nihil ullam. Placeat cumque ipsa cupiditate velit magni sapiente mollitia dolorum. Veritatis esse illo eos perferendis. Perspiciatis vel iusto odio eveniet quam officia quidem. Fugiat a ipsum tempore optio accusantium autem in fugit.,,,,"","",0.0,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Default,false,,,,,,,,,,Categories -> Men -> Shirts,Categories -> Women,Categories -> Sportswear,Lose,Wannabe,90% Cotton 10% Elastan-denim-shirt,DENIM-SHIRT-XS-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,XS,,-denim-shirt,DENIM-SHIRT-S-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,S,,-denim-shirt,DENIM-SHIRT-M-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,M,,-denim-shirt,DENIM-SHIRT-L-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,L,,-denim-shirt,DENIM-SHIRT-XL-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,XL,,-denim-shirt,DENIM-SHIRT-XS-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,XS,,-denim-shirt,DENIM-SHIRT-S-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,S,,-denim-shirt,DENIM-SHIRT-M-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,M,,-denim-shirt,DENIM-SHIRT-L-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,L,,-denim-shirt,DENIM-SHIRT-XL-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,XL,,-checked-shirt,"",Checked Shirt,draft,,,Et ipsam repudiandae itaque tenetur laborum. Cupiditate nulla blanditiis quia tenetur doloremque possimus explicabo asperiores. Facere adipisci veniam aut nemo magnam.,,,,"","",0.0,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Default,false,,,,,,,,,,Categories -> Men -> Shirts,Categories -> Women,Categories -> Sportswear,Lose,Wannabe,10% Cotton 90% Elastan-checked-shirt,CHECKED-SHIRT-XS-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,XS,,-checked-shirt,CHECKED-SHIRT-S-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,S,,-checked-shirt,CHECKED-SHIRT-M-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,M,,-checked-shirt,CHECKED-SHIRT-L-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,L,,-checked-shirt,CHECKED-SHIRT-XL-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,XL,,\ No newline at end of file+slug,sku,name,status,vendor_name,brand_name,description,meta_title,meta_description,meta_keywords,tags,labels,price,compare_at_price,currency,width,height,depth,dimensions_unit,weight,weight_unit,available_on,discontinue_on,track_inventory,inventory_count,inventory_backorderable,tax_category,digital,image1_src,image2_src,image3_src,option1_name,option1_value,option2_name,option2_value,option3_name,option3_value,category1,category2,category3,metafield.properties.fit,metafield.properties.manufacturer,metafield.properties.material,metafield.custom.brand,metafield.custom.material+denim-shirt,"",Denim Shirt,draft,,,Adipisci sapiente velit nihil ullam. Placeat cumque ipsa cupiditate velit magni sapiente mollitia dolorum. Veritatis esse illo eos perferendis. Perspiciatis vel iusto odio eveniet quam officia quidem. Fugiat a ipsum tempore optio accusantium autem in fugit.,,,,"","",0.0,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Default,false,,,,,,,,,,Categories -> Men -> Shirts,Categories -> Women,Categories -> Sportswear,Lose,Wannabe,90% Cotton 10% Elastan,,+denim-shirt,DENIM-SHIRT-XS-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,XS,,,,,+denim-shirt,DENIM-SHIRT-S-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,S,,,,,+denim-shirt,DENIM-SHIRT-M-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,M,,,,,+denim-shirt,DENIM-SHIRT-L-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,L,,,,,+denim-shirt,DENIM-SHIRT-XL-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,XL,,,,,+denim-shirt,DENIM-SHIRT-XS-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,XS,,,,,+denim-shirt,DENIM-SHIRT-S-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,S,,,,,+denim-shirt,DENIM-SHIRT-M-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,M,,,,,+denim-shirt,DENIM-SHIRT-L-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,L,,,,,+denim-shirt,DENIM-SHIRT-XL-LIGHT-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Light Blue,Size,XL,,,,,+checked-shirt,"",Checked Shirt,draft,,,Et ipsam repudiandae itaque tenetur laborum. Cupiditate nulla blanditiis quia tenetur doloremque possimus explicabo asperiores. Facere adipisci veniam aut nemo magnam.,,,,"","",0.0,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Default,false,,,,,,,,,,Categories -> Men -> Shirts,Categories -> Women,Categories -> Sportswear,Lose,Wannabe,10% Cotton 90% Elastan,,+checked-shirt,CHECKED-SHIRT-XS-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,XS,,,,,+checked-shirt,CHECKED-SHIRT-S-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,S,,,,,+checked-shirt,CHECKED-SHIRT-M-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,M,,,,,+checked-shirt,CHECKED-SHIRT-L-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,L,,,,,+checked-shirt,CHECKED-SHIRT-XL-RED,,,,,,,,,,,22.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:54,,true,100,true,Clothing,false,,,,Color,Red,Size,XL,,,,,\ No newline at end of filediff --git a/core/spec/models/spree/import_mapping_spec.rb b/core/spec/models/spree/import_mapping_spec.rbnew file mode 100644index 0000000000..31b335ac73--- /dev/null+++ b/core/spec/models/spree/import_mapping_spec.rb@@ -0,0 +1,189 @@+require 'spec_helper'++RSpec.describe Spree::ImportMapping, type: :model do+ let(:store) { @default_store }+ let(:user) { create(:admin_user) }+ let(:import) { create(:product_import, owner: store, user: user) }++ describe 'Associations' do+ it { is_expected.to belong_to(:import) }+ end++ describe 'Validations' do+ describe 'presence validations' do+ it 'validates presence of import' do+ mapping = build(:import_mapping, import: nil)+ expect(mapping).not_to be_valid+ expect(mapping.errors[:import]).to include("can't be blank")+ end++ it 'validates presence of schema_field' do+ mapping = build(:import_mapping, schema_field: nil)+ expect(mapping).not_to be_valid+ expect(mapping.errors[:schema_field]).to include("can't be blank")+ end+ end++ describe 'uniqueness validations' do+ let!(:existing_mapping) { create(:import_mapping, import: import, schema_field: 'slug') }++ it 'validates uniqueness of schema_field scoped to import_id' do+ duplicate_mapping = build(:import_mapping, import: import, schema_field: 'slug')+ expect(duplicate_mapping).not_to be_valid+ expect(duplicate_mapping.errors[:schema_field]).to include('has already been taken')+ end++ it 'allows same schema_field for different imports' do+ other_import = create(:product_import, owner: store, user: user)+ duplicate_mapping = build(:import_mapping, import: other_import, schema_field: 'slug')+ expect(duplicate_mapping).to be_valid+ end++ it 'validates uniqueness of file_column scoped to import_id' do+ existing_mapping.update!(file_column: 'product_name')+ duplicate_mapping = build(:import_mapping, import: import, file_column: 'product_name')+ expect(duplicate_mapping).not_to be_valid+ expect(duplicate_mapping.errors[:file_column]).to include('has already been taken')+ end++ it 'allows blank file_column' do+ mapping = build(:import_mapping, import: import, schema_field: 'description', file_column: nil)+ expect(mapping).to be_valid+ end++ it 'allows same file_column for different imports' do+ other_import = create(:product_import, owner: store, user: user)+ mapping = build(:import_mapping, import: other_import, schema_field: 'sku', file_column: 'name')+ expect(mapping).to be_valid+ end+ end+ end++ describe '#required?' do+ context 'when schema_field is a required field' do+ let(:mapping) { build(:import_mapping, import: import, schema_field: 'slug') }++ it 'returns true' do+ expect(mapping.required?).to be true+ end+ end++ context 'when schema_field is not a required field' do+ let(:mapping) { build(:import_mapping, import: import, schema_field: 'description') }++ it 'returns false' do+ expect(mapping.required?).to be false+ end+ end+ end++ describe '#mapped?' do+ context 'when file_column is present' do+ let(:mapping) { build(:import_mapping, import: import, file_column: 'product_name') }++ it 'returns true' do+ expect(mapping.mapped?).to be true+ end+ end++ context 'when file_column is blank' do+ let(:mapping) { build(:import_mapping, import: import, file_column: nil) }++ it 'returns false' do+ expect(mapping.mapped?).to be false+ end++ it 'returns false when file_column is empty string' do+ mapping.file_column = ''+ expect(mapping.mapped?).to be false+ end+ end+ end++ describe '#try_to_auto_assign_file_column' do+ let(:mapping) { create(:import_mapping, import: import, schema_field: 'slug', file_column: nil) }+ let(:csv_headers) { ['Product Name', 'Slug', 'SKU', 'Price'] }++ context 'when exact match exists' do+ it 'assigns the matching file column' do+ mapping.try_to_auto_assign_file_column(csv_headers)+ expect(mapping.file_column).to eq('Slug')+ end+ end++ context 'when case-insensitive match exists' do+ let(:csv_headers) { ['product name', 'SLUG', 'sku', 'price'] }++ it 'assigns the matching file column' do+ mapping.try_to_auto_assign_file_column(csv_headers)+ expect(mapping.file_column).to eq('SLUG')+ end+ end++ context 'when parameterized match exists' do+ let(:mapping) { build(:import_mapping, import: import, schema_field: 'product_name', file_column: nil) }+ let(:csv_headers) { ['Product Name', 'Slug', 'SKU'] }++ it 'assigns the matching file column' do+ mapping.try_to_auto_assign_file_column(csv_headers)+ expect(mapping.file_column).to eq('Product Name')+ end+ end++ context 'when no match exists' do+ let(:csv_headers) { ['Product Name', 'Title', 'SKU', 'Price'] }++ it 'does not assign a file column' do+ mapping.try_to_auto_assign_file_column(csv_headers)+ expect(mapping.file_column).to be_nil+ end+ end++ context 'when file_column is already set' do+ let(:mapping) { build(:import_mapping, import: import, schema_field: 'slug', file_column: 'custom_column') }+ let(:csv_headers) { ['Slug', 'SKU'] }++ it 'overwrites with matching column' do+ mapping.try_to_auto_assign_file_column(csv_headers)+ expect(mapping.file_column).to eq('Slug')+ end+ end+ end++ describe '#schema_field_label' do+ context 'when schema_field exists in import schema' do+ let(:mapping) { build(:import_mapping, import: import, schema_field: 'slug') }++ it 'returns the label for the schema field' do+ expect(mapping.schema_field_label).to eq('Slug')+ end+ end++ context 'when schema_field is a metafield' do+ let!(:metafield_definition) do+ create(:metafield_definition,+ namespace: 'properties',+ key: 'manufacturer',+ name: 'Manufacturer',+ resource_type: 'Spree::Product')+ end+ let(:mapping) do+ create(:import_mapping,+ import: import,+ schema_field: 'metafield.properties.manufacturer')+ end++ it 'returns the metafield definition name' do+ expect(mapping.schema_field_label).to eq('Manufacturer')+ end+ end++ context 'when schema_field does not exist in import schema' do+ let(:mapping) { build(:import_mapping, import: import, schema_field: 'non_existent_field') }++ it 'returns nil' do+ expect(mapping.schema_field_label).to be_nil+ end+ end+ end+enddiff --git a/core/spec/models/spree/import_spec.rb b/core/spec/models/spree/import_spec.rbindex ba74891b1a..39b38835f9 100644--- a/core/spec/models/spree/import_spec.rb+++ b/core/spec/models/spree/import_spec.rb@@ -181,7 +181,9 @@ RSpec.describe Spree::Import, :job, type: :model do'category3','metafield.properties.fit','metafield.properties.manufacturer',- 'metafield.properties.material'+ 'metafield.properties.material',+ 'metafield.custom.brand',+ 'metafield.custom.material'])end@@ -196,6 +198,92 @@ RSpec.describe Spree::Import, :job, type: :model doendend+ describe '#schema_fields' do+ context 'when model supports metafields' do+ let!(:metafield_definition1) do+ create(:metafield_definition,+ namespace: 'properties',+ key: 'manufacturer',+ name: 'Manufacturer',+ resource_type: 'Spree::Product')+ end+ let!(:metafield_definition2) do+ create(:metafield_definition,+ namespace: 'custom',+ key: 'brand',+ name: 'Brand',+ resource_type: 'Spree::Product')+ end++ before do+ import.type = 'Spree::Imports::Products'+ end++ it 'returns base fields from schema' do+ base_fields = import.schema_fields.select { |f| !f[:name].start_with?('metafield.') }+ expect(base_fields).to include(+ { name: 'slug', label: 'Slug', required: true },+ { name: 'sku', label: 'SKU', required: true },+ { name: 'name', label: 'Name', required: true }+ )+ end++ it 'includes metafield fields' do+ metafield_fields = import.schema_fields.select { |f| f[:name].start_with?('metafield.') }+ expect(metafield_fields).to include(+ { name: 'metafield.properties.manufacturer', label: 'Manufacturer' },+ { name: 'metafield.custom.brand', label: 'Brand' }+ )+ end++ it 'combines base fields and metafield fields' do+ all_fields = import.schema_fields+ base_field_count = Spree::ImportSchemas::Products::FIELDS.count+ metafield_count = 2++ expect(all_fields.count).to eq(base_field_count + metafield_count)+ end++ it 'has correct structure for metafield fields' do+ metafield_field = import.schema_fields.find { |f| f[:name] == 'metafield.properties.manufacturer' }+ expect(metafield_field).to eq(+ { name: 'metafield.properties.manufacturer', label: 'Manufacturer' }+ )+ end+ end++ context 'when model does not support metafields' do+ before do+ import.type = 'Spree::Imports::Products'+ # Mock model_class to return a class that doesn't include Metafields+ allow(import).to receive(:model_class).and_return(double('ModelClass', included_modules: []))+ end++ it 'returns only base fields from schema' do+ fields = import.schema_fields+ expect(fields).to eq(Spree::ImportSchemas::Products::FIELDS)+ end++ it 'does not include any metafield fields' do+ metafield_fields = import.schema_fields.select { |f| f[:name].start_with?('metafield.') }+ expect(metafield_fields).to be_empty+ end+ end++ context 'when model supports metafields but has no metafield definitions' do+ before do+ import.type = 'Spree::Imports::Products'+ # Ensure no metafield definitions exist+ Spree::MetafieldDefinition.where(resource_type: 'Spree::Product').destroy_all+ end++ it 'returns only base fields' do+ fields = import.schema_fields+ expect(fields).to eq(Spree::ImportSchemas::Products::FIELDS)+ end+ end+ end+describe '#create_mappings' dobefore { import.save! }diff --git a/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/core/spec/services/spree/imports/row_processors/product_variant_spec.rbindex 4f9c48e55d..9c1956a1a9 100644--- a/core/spec/services/spree/imports/row_processors/product_variant_spec.rb+++ b/core/spec/services/spree/imports/row_processors/product_variant_spec.rb@@ -333,4 +333,113 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doexpect(variant.sku).to eq 'NEW-MISSING-SHIRT-SKU'endend++ context 'with metafields' do+ let!(:brand_metafield_definition) do+ create(:metafield_definition,+ namespace: 'custom',+ key: 'brand',+ name: 'Brand',+ resource_type: 'Spree::Product',+ metafield_type: 'Spree::Metafields::ShortText')+ end++ let!(:material_metafield_definition) do+ create(:metafield_definition,+ namespace: 'custom',+ key: 'material',+ name: 'Material',+ resource_type: 'Spree::Product',+ metafield_type: 'Spree::Metafields::ShortText')+ end++ let(:row_data) do+ base_data = csv_row_hash(+ 'slug' => 'denim-shirt',+ 'name' => 'Denim Shirt',+ 'status' => 'active',+ 'price' => '62.99',+ 'currency' => 'USD'+ )+ # Add metafield keys directly to the hash+ base_data.merge(+ 'metafield.custom.brand' => 'Awesome Brand',+ 'metafield.custom.material' => 'Cotton'+ )+ end++ # Override the top-level before to create mappings after metafield definitions exist+ before do+ import.create_mappings+ end++ it 'creates mappings for metafields automatically' do+ expect(import.mappings.where(schema_field: 'metafield.custom.brand').exists?).to be true+ expect(import.mappings.where(schema_field: 'metafield.custom.material').exists?).to be true+ end++ it 'auto-assigns file_column for metafield mappings when CSV headers match' do+ # Verify CSV headers include metafield keys+ expect(import.csv_headers).to include('metafield.custom.brand', 'metafield.custom.material')++ brand_mapping = import.mappings.find_by(schema_field: 'metafield.custom.brand')+ material_mapping = import.mappings.find_by(schema_field: 'metafield.custom.material')++ expect(brand_mapping.file_column).to eq('metafield.custom.brand')+ expect(material_mapping.file_column).to eq('metafield.custom.material')+ expect(brand_mapping.mapped?).to be true+ expect(material_mapping.mapped?).to be true+ end++ it 'sets metafields on the product' do+ product = variant.product++ expect(product).to be_persisted+ expect(product.has_metafield?('custom.brand')).to be true+ expect(product.has_metafield?('custom.material')).to be true+ expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'+ expect(product.get_metafield('custom.material').value).to eq 'Cotton'+ end++ context 'when updating an existing product with metafields' do+ let!(:existing_product) do+ p = create(:product, slug: 'denim-shirt', name: 'Denim Shirt', stores: [store])+ p.set_metafield('custom.brand', 'Old Brand')+ p.set_metafield('custom.material', 'Old Material')+ p+ end++ it 'updates existing metafields' do+ product = variant.product++ expect(product.id).to eq existing_product.id+ expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'+ expect(product.get_metafield('custom.material').value).to eq 'Cotton'+ end+ end++ context 'when metafield value is blank' do+ let(:row_data) do+ base_data = csv_row_hash(+ 'slug' => 'denim-shirt',+ 'name' => 'Denim Shirt',+ 'status' => 'active',+ 'price' => '62.99',+ 'currency' => 'USD'+ )+ base_data.merge(+ 'metafield.custom.brand' => 'Awesome Brand',+ 'metafield.custom.material' => ''+ )+ end++ it 'skips blank metafield values' do+ product = variant.product++ expect(product.has_metafield?('custom.brand')).to be true+ expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'+ expect(product.has_metafield?('custom.material')).to be false+ end+ end+ endend