Class: Spree::Import
- Inherits:
-
Object
- Object
- Spree::Import
- Includes:
- HasStatus, NumberIdentifier, SingleStoreResource
- Defined in:
- app/models/spree/import.rb
Direct Known Subclasses
Spree::Imports::Customers, Spree::Imports::PriceListPrices, Spree::Imports::ProductTranslations, Spree::Imports::Products, Spree::Imports::PurchaseOrders
Constant Summary collapse
- SAMPLE_DATA_BASE_URL_TEMPLATE =
Where the downloadable example CSVs are served from — see
sample_csv_url.Pinned to the installed version's tag rather than
main: whether a type has an example is answered by the localdb/sample_data, so pointing elsewhere would let a released install link to a newer, incompatible schema (or a file that has since been removed). 'https://raw.githubusercontent.com/spree/spree/refs/tags/v%<version>s/spree/core/db/sample_data'.freeze
Class Method Summary collapse
-
.available_models ⇒ Array<Class>
Returns the available models for the import.
-
.available_types ⇒ Array<Class>
Returns the available types for the import.
-
.model_class ⇒ Object
eg.
-
.required_scope ⇒ Symbol?
Admin API scope family gating this import type — an import is a bulk write, so an API key needs
write_<required_scope>to create and manage it. -
.sample_csv_filename ⇒ String
eg.
-
.sample_csv_url ⇒ String?
Publicly downloadable example CSV for this import type — the same file
rake spree:load_sample_datafeeds through this very pipeline, so it is a working example rather than a hand-maintained sample that can drift from the schema. - .sample_data_base_url ⇒ String
-
.type_for_model(model) ⇒ Class
Returns the type for the model.
Instance Method Summary collapse
-
#attachment_file_content ⇒ String
Returns the content of the attachment file.
-
#can_be_deleted? ⇒ Boolean
Imports are deletable only while no processing jobs can be in flight — ProcessJob/ProcessGroupJob re-load the record mid-run.
-
#complete! ⇒ Object
deprecated
Deprecated.
Call Spree.import_complete_workflow — removed in 6.3.
-
#complete? ⇒ Boolean
Returns true if the import is complete.
-
#complete_mapping! ⇒ Object
deprecated
Deprecated.
Call Spree.import_complete_mapping_workflow — removed in 6.3.
-
#csv_headers ⇒ Array<String>
Returns the headers of the csv file.
-
#current_ability ⇒ Spree::Ability
The ability the row processors scope-fetch through.
-
#display_name ⇒ String
Returns the display name for the import.
- #event_serializer_class ⇒ Object
-
#fail! ⇒ Object
deprecated
Deprecated.
Set the status — removed in 6.3. Failure was never a step of its own; the controller records the parse error directly.
-
#group_column ⇒ String?
Returns the schema field name used to group rows for parallel processing.
-
#import_schema ⇒ Spree::ImportSchema
Returns the import schema for the import.
-
#large_import? ⇒ Boolean
Returns true if the import has more rows than the large import threshold.
-
#mapped_fields ⇒ Array<String>
Returns the mapped fields for the import schema.
-
#mapping_done? ⇒ Boolean
Returns true if the mapping is done.
-
#model_class ⇒ Class
Returns the model class for the import.
-
#owner ⇒ Spree::Seller, Spree::Store
deprecated
Deprecated.
Read
sellerandstore— removed in 6.3. Kept because the polymorphicownershipped in 5.6 and the v3 serializer still emitsowner_type/owner_idfrom it. -
#owner=(record) ⇒ Object
deprecated
Deprecated.
Assign
seller:orstore:— removed in 6.3. -
#processing? ⇒ Boolean
Returns true if the import is processing or completed mapping.
-
#required_fields ⇒ Array<String>
Returns the required fields for the import schema.
-
#results_page_url ⇒ String?
URL of the wizard/results view for this import — the caller-provided
results_urlwith the wizard's?import=param appended (a no-op for the legacy admin's show URL, whose path already identifies the import). -
#results_url ⇒ Object
Public API name for the
results_urlpreference (read/write symmetry). - #results_url=(value) ⇒ Object
-
#retry_failed_rows ⇒ Object
deprecated
Deprecated.
Call Spree.import_retry_failed_rows_workflow — removed in 6.3. Returns false when there is nothing to retry, as the guarded event did.
-
#row_lookup_cache ⇒ Hash
Per-instance cache shared by row processors within a single processing job.
-
#row_processor_class ⇒ Class
Returns the row processor class for the import.
-
#rows_status_counts ⇒ Hash{String => Integer}
Per-status row counts for API status payloads, memoized so one request issues a single grouped COUNT instead of one per status — and, on a lazily preloaded list, one for every import of the list.
-
#sample_csv_url ⇒ String?
Publicly downloadable example CSV for this import's type, or nil when the type has no sample file.
-
#sample_row ⇒ Hash
First data row as { header => value }, reading a single line of the attached CSV — used by the mapping UI to show example values.
-
#schema_fields ⇒ Array<Hash>
Returns the fields for the import schema If model supports custom_fields, it will include the custom_field definitions for this model.
-
#start_mapping! ⇒ Object
deprecated
Deprecated.
Call the Spree::Imports workflows — removed in 6.3.
-
#start_processing! ⇒ Object
deprecated
Deprecated.
Call Spree.import_start_processing_workflow — removed in 6.3.
-
#template_csv ⇒ String
Header-only CSV for this import's schema — the blank counterpart to
sample_csv_url. -
#template_csv_filename ⇒ String
Suggested filename for
template_csv, e.g. -
#unmapped_file_columns ⇒ Array<String>
Returns the file columns that are not mapped.
Class Method Details
.available_models ⇒ Array<Class>
Returns the available models for the import
431 432 433 |
# File 'app/models/spree/import.rb', line 431 def available_models available_types.map(&:model_class) end |
.available_types ⇒ Array<Class>
Returns the available types for the import
425 426 427 |
# File 'app/models/spree/import.rb', line 425 def available_types Spree.import_types end |
.model_class ⇒ Object
eg. Spree::Imports::Orders => Spree::Order
486 487 488 489 490 491 492 493 494 |
# File 'app/models/spree/import.rb', line 486 def model_class return Spree.customer_class if to_s == 'Spree::Imports::Customers' klass = "Spree::#{to_s.demodulize.singularize}".safe_constantize raise NameError, "Missing model class for #{self}" unless klass klass end |
.required_scope ⇒ Symbol?
Admin API scope family gating this import type — an import is a bulk
write, so an API key needs write_<required_scope> to create and
manage it. Derived from the class name (Spree::Imports::Customers =>
:customers); override in subclasses gated by a different scope.
Returns nil on the base class, so unmapped types are only accessible
to write_all keys.
449 450 451 452 453 |
# File 'app/models/spree/import.rb', line 449 def required_scope return nil if self == Spree::Import to_s.demodulize.underscore.to_sym end |
.sample_csv_filename ⇒ String
eg. Spree::Imports::ProductTranslations => "product_translations.csv"
481 482 483 |
# File 'app/models/spree/import.rb', line 481 def sample_csv_filename "#{api_type}.csv" end |
.sample_csv_url ⇒ String?
Publicly downloadable example CSV for this import type — the same file
rake spree:load_sample_data feeds through this very pipeline, so it is
a working example rather than a hand-maintained sample that can drift
from the schema.
Whether a type has an example is answered by db/sample_data itself,
so adding or removing a CSV there needs no change here; a type with no
sample file returns nil and the UI omits the link. The URL is pinned to
the installed version's tag so the file served always matches the schema
that check was made against.
467 468 469 470 471 472 |
# File 'app/models/spree/import.rb', line 467 def sample_csv_url return nil if self == Spree::Import return nil unless Spree::Core::Engine.root.join('db', 'sample_data', sample_csv_filename).exist? [sample_data_base_url, sample_csv_filename].join('/') end |
.sample_data_base_url ⇒ String
475 476 477 |
# File 'app/models/spree/import.rb', line 475 def sample_data_base_url format(SAMPLE_DATA_BASE_URL_TEMPLATE, version: Spree.version) end |
.type_for_model(model) ⇒ Class
Returns the type for the model
437 438 439 |
# File 'app/models/spree/import.rb', line 437 def type_for_model(model) available_types.find { |type| type.model_class.to_s == model.to_s } end |
Instance Method Details
#attachment_file_content ⇒ String
Returns the content of the attachment file
368 369 370 |
# File 'app/models/spree/import.rb', line 368 def @attachment_file_content ||= .attached? ? .blob.download&.force_encoding('UTF-8') : nil end |
#can_be_deleted? ⇒ Boolean
Imports are deletable only while no processing jobs can be in flight — ProcessJob/ProcessGroupJob re-load the record mid-run.
221 222 223 |
# File 'app/models/spree/import.rb', line 221 def can_be_deleted? %w[pending mapping completed failed].include?(status) end |
#complete! ⇒ Object
Call Spree.import_complete_workflow — removed in 6.3.
185 186 187 188 |
# File 'app/models/spree/import.rb', line 185 def complete! Spree::Deprecation.warn('Spree::Import#complete! is deprecated and will be removed in Spree 6.3. Call Spree.import_complete_workflow instead.') run_pipeline_workflow(Spree.import_complete_workflow) end |
#complete? ⇒ Boolean
Returns true if the import is complete
214 215 216 |
# File 'app/models/spree/import.rb', line 214 def complete? status == 'completed' end |
#complete_mapping! ⇒ Object
Call Spree.import_complete_mapping_workflow — removed in 6.3.
169 170 171 172 173 174 |
# File 'app/models/spree/import.rb', line 169 def complete_mapping! Spree::Deprecation.warn( 'Spree::Import#complete_mapping! is deprecated and will be removed in Spree 6.3. Call Spree.import_complete_mapping_workflow instead.' ) run_pipeline_workflow(Spree.import_complete_mapping_workflow) end |
#csv_headers ⇒ Array<String>
Returns the headers of the csv file
357 358 359 360 361 362 363 364 |
# File 'app/models/spree/import.rb', line 357 def csv_headers return [] if .blank? @csv_headers ||= ::CSV.parse_line( , col_sep: preferred_delimiter ) end |
#current_ability ⇒ Spree::Ability
The ability the row processors scope-fetch through.
Built against whoever ran the import, because that is where the importing
user holds their roles: a marketplace seller's staff hold theirs on the
Spree::Seller, never on the store, so an ability resolved against the
store compiles no rules at all and every scope-fetch through it comes
back empty.
405 406 407 |
# File 'app/models/spree/import.rb', line 405 def current_ability @current_ability ||= Spree.ability_class.new(user, { store: store, resource: seller || store }) end |
#display_name ⇒ String
Returns the display name for the import
351 352 353 |
# File 'app/models/spree/import.rb', line 351 def display_name "#{self.class.model_name.human(count: 2)} #{number}" end |
#event_serializer_class ⇒ Object
418 419 420 |
# File 'app/models/spree/import.rb', line 418 def event_serializer_class 'Spree::Api::V3::ImportSerializer'.safe_constantize end |
#fail! ⇒ Object
Set the status — removed in 6.3. Failure was never a step of its own; the controller records the parse error directly.
192 193 194 195 |
# File 'app/models/spree/import.rb', line 192 def fail! Spree::Deprecation.warn('Spree::Import#fail! is deprecated and will be removed in Spree 6.3. Write the status instead.') update!(status: 'failed') end |
#group_column ⇒ String?
Returns the schema field name used to group rows for parallel processing. Rows sharing the same value in this field are processed together in one job. Returns nil for imports where rows are independent (default — batched in chunks).
156 157 158 |
# File 'app/models/spree/import.rb', line 156 def group_column nil end |
#import_schema ⇒ Spree::ImportSchema
Returns the import schema for the import
295 296 297 |
# File 'app/models/spree/import.rb', line 295 def import_schema "Spree::ImportSchemas::#{type.demodulize}".safe_constantize.new end |
#large_import? ⇒ Boolean
Returns true if the import has more rows than the large import threshold. Large imports skip per-row UI broadcasts and use bulk processing.
148 149 150 |
# File 'app/models/spree/import.rb', line 148 def large_import? rows_count >= Spree::Config[:large_import_threshold] end |
#mapped_fields ⇒ Array<String>
Returns the mapped fields for the import schema
339 340 341 |
# File 'app/models/spree/import.rb', line 339 def mapped_fields @mapped_fields ||= mappings.mapped.where(schema_field: required_fields) end |
#mapping_done? ⇒ Boolean
Returns true if the mapping is done
345 346 347 |
# File 'app/models/spree/import.rb', line 345 def mapping_done? mapped_fields.count == required_fields.count end |
#model_class ⇒ Class
Returns the model class for the import
285 286 287 288 289 290 291 |
# File 'app/models/spree/import.rb', line 285 def model_class if type == 'Spree::Imports::Customers' Spree.customer_class else "Spree::#{type.demodulize.singularize}".safe_constantize end end |
#owner ⇒ Spree::Seller, Spree::Store
Read seller and store — removed in 6.3. Kept because the
polymorphic owner shipped in 5.6 and the v3 serializer still emits
owner_type/owner_id from it.
Who ran this import — the seller when one did, otherwise the store.
378 379 380 |
# File 'app/models/spree/import.rb', line 378 def owner seller || store end |
#owner=(record) ⇒ Object
Assign seller: or store: — removed in 6.3.
383 384 385 386 387 388 389 390 391 392 393 394 |
# File 'app/models/spree/import.rb', line 383 def owner=(record) Spree::Deprecation.warn('Spree::Import#owner= is deprecated and will be removed in Spree 6.3. Assign seller: or store: instead.') case record when Spree::Seller self.seller = record self.store = record.store else self.seller = nil self.store = record end end |
#processing? ⇒ Boolean
Returns true if the import is processing or completed mapping
208 209 210 |
# File 'app/models/spree/import.rb', line 208 def processing? ['processing', 'completed_mapping'].include?(status) end |
#required_fields ⇒ Array<String>
Returns the required fields for the import schema
333 334 335 |
# File 'app/models/spree/import.rb', line 333 def required_fields import_schema.required_fields end |
#results_page_url ⇒ String?
URL of the wizard/results view for this import — the caller-provided
results_url with the wizard's ?import= param appended (a no-op for
the legacy admin's show URL, whose path already identifies the import).
Nil when the preference is absent; the mailer then renders no link.
259 260 261 262 263 264 265 266 267 268 269 |
# File 'app/models/spree/import.rb', line 259 def results_page_url return if preferred_results_url.blank? uri = URI.parse(preferred_results_url) params = URI.decode_www_form(uri.query.to_s) params << ['import', prefixed_id] uri.query = URI.encode_www_form(params) uri.to_s rescue URI::InvalidURIError nil end |
#results_url ⇒ Object
Public API name for the results_url preference (read/write symmetry).
String preferences round-trip nil as "" — normalize blank to nil.
246 247 248 |
# File 'app/models/spree/import.rb', line 246 def results_url preferred_results_url.presence end |
#results_url=(value) ⇒ Object
250 251 252 |
# File 'app/models/spree/import.rb', line 250 def results_url=(value) self.preferred_results_url = value end |
#retry_failed_rows ⇒ Object
Call Spree.import_retry_failed_rows_workflow — removed in 6.3. Returns false when there is nothing to retry, as the guarded event did.
199 200 201 202 203 204 |
# File 'app/models/spree/import.rb', line 199 def retry_failed_rows Spree::Deprecation.warn( 'Spree::Import#retry_failed_rows is deprecated and will be removed in Spree 6.3. Call Spree.import_retry_failed_rows_workflow instead.' ) Spree.import_retry_failed_rows_workflow.call(import: self).success? end |
#row_lookup_cache ⇒ Hash
Per-instance cache shared by row processors within a single processing job. Group jobs funnel every row through the same Import instance, so lookups of shared records (tax/shipping categories, option types, custom_field definitions) resolve once per job instead of once per row.
414 415 416 |
# File 'app/models/spree/import.rb', line 414 def row_lookup_cache @row_lookup_cache ||= {} end |
#row_processor_class ⇒ Class
Returns the row processor class for the import
301 302 303 |
# File 'app/models/spree/import.rb', line 301 def row_processor_class "Spree::ImportRowProcessors::#{type.demodulize.singularize}".safe_constantize end |
#rows_status_counts ⇒ Hash{String => Integer}
Per-status row counts for API status payloads, memoized so one request issues a single grouped COUNT instead of one per status — and, on a lazily preloaded list, one for every import of the list.
229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
# File 'app/models/spree/import.rb', line 229 def rows_status_counts return @rows_status_counts if @rows_status_counts siblings = lazy_preload_context&.records&.grep(Spree::Import) return @rows_status_counts = rows.group(:status).count if siblings.blank? counts = Spree::ImportRow.where(import_id: siblings.map(&:id)).group(:import_id, :status).count siblings.each do |import| import.preloaded_rows_status_counts = counts.each_with_object({}) do |((import_id, status), count), by_status| by_status[status] = count if import_id == import.id end end @rows_status_counts end |
#sample_csv_url ⇒ String?
Publicly downloadable example CSV for this import's type, or nil when the
type has no sample file. Resolved from the type column rather than the
instance's class, so it works on a record built as the base
Spree::Import with type assigned (which is how the admin's new-import
form builds it).
125 126 127 |
# File 'app/models/spree/import.rb', line 125 def sample_csv_url self.class.available_types.find { |klass| klass.to_s == type.to_s }&.sample_csv_url end |
#sample_row ⇒ Hash
First data row as { header => value }, reading a single line of the attached CSV — used by the mapping UI to show example values.
274 275 276 277 278 279 280 281 |
# File 'app/models/spree/import.rb', line 274 def sample_row return {} if .blank? row = ::CSV.foreach(StringIO.new(), headers: true, col_sep: preferred_delimiter).first row&.to_h || {} rescue ::CSV::MalformedCSVError, EncodingError {} end |
#schema_fields ⇒ Array<Hash>
Returns the fields for the import schema If model supports custom_fields, it will include the custom_field definitions for this model
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'app/models/spree/import.rb', line 308 def schema_fields base_fields = import_schema.fields # Dynamically add custom_field definitions if the model supports custom_fields if model_class_supports_custom_fields? custom_field_fields = custom_field_definitions_for_model.map do |definition| { name: definition.csv_header_name, label: definition.label } end base_fields + custom_field_fields else base_fields end end |
#start_mapping! ⇒ Object
Call the Spree::Imports workflows — removed in 6.3.
161 162 163 164 165 166 |
# File 'app/models/spree/import.rb', line 161 def start_mapping! Spree::Deprecation.warn( 'Spree::Import#start_mapping! is deprecated and will be removed in Spree 6.3. Call Spree.import_start_mapping_workflow instead.' ) run_pipeline_workflow(Spree.import_start_mapping_workflow) end |
#start_processing! ⇒ Object
Call Spree.import_start_processing_workflow — removed in 6.3.
177 178 179 180 181 182 |
# File 'app/models/spree/import.rb', line 177 def start_processing! Spree::Deprecation.warn( 'Spree::Import#start_processing! is deprecated and will be removed in Spree 6.3. Call Spree.import_start_processing_workflow instead.' ) run_pipeline_workflow(Spree.import_start_processing_workflow) end |
#template_csv ⇒ String
Header-only CSV for this import's schema — the blank counterpart to
sample_csv_url. One line, so callers can inline it (e.g. as a data:
URI) instead of round-tripping to the server for it.
134 135 136 |
# File 'app/models/spree/import.rb', line 134 def template_csv ::CSV.generate_line(schema_fields.map { |field| field[:name] }) end |
#template_csv_filename ⇒ String
Suggested filename for template_csv, e.g. "products_import_template.csv".
141 142 143 |
# File 'app/models/spree/import.rb', line 141 def template_csv_filename "#{self.class.api_type_for(type)}_import_template.csv" end |
#unmapped_file_columns ⇒ Array<String>
Returns the file columns that are not mapped
327 328 329 |
# File 'app/models/spree/import.rb', line 327 def unmapped_file_columns csv_headers.reject { |header| mappings.mapped.exists?(file_column: header) } end |