Class: Spree::Export
Defined Under Namespace
Classes: SellerScopeUnavailable
Constant Summary
collapse
- SUPPORTED_FILE_FORMATS =
%i[csv].freeze
Class Method Summary
collapse
Instance Method Summary
collapse
Class Method Details
.available_models ⇒ Object
371
372
373
|
# File 'app/models/spree/export.rb', line 371
def available_models
available_types.map(&:model_class)
end
|
.available_types ⇒ Object
352
353
354
|
# File 'app/models/spree/export.rb', line 352
def available_types
Spree.export_types
end
|
.model_class ⇒ Object
eg. Spree::Exports::Products => Spree::Product
380
381
382
383
384
385
386
|
# File 'app/models/spree/export.rb', line 380
def model_class
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 export type — an export is a bulk
read, so an API key needs read_<required_scope> to create, view, and
download it. Derived from the class name
(Spree::Exports::Customers => :customers); override in subclasses whose
records are gated by a different scope (e.g. coupon codes =>
:promotions). Returns nil on the base class, so unmapped types are
only accessible to read_all/write_all keys.
365
366
367
368
369
|
# File 'app/models/spree/export.rb', line 365
def required_scope
return nil if self == Spree::Export
to_s.demodulize.underscore.to_sym
end
|
.type_for_model(model) ⇒ Object
375
376
377
|
# File 'app/models/spree/export.rb', line 375
def type_for_model(model)
available_types.find { |type| type.model_class.to_s == model.to_s }
end
|
Instance Method Details
#build_csv_line(_record) ⇒ Object
183
184
185
|
# File 'app/models/spree/export.rb', line 183
def build_csv_line(_record)
raise NotImplementedError, 'build_csv_line must be implemented'
end
|
171
172
173
|
# File 'app/models/spree/export.rb', line 171
def
raise NotImplementedError, 'csv_headers must be implemented'
end
|
#current_ability ⇒ Object
Capability is read against whatever granted it: a seller's roles are held
on the seller, not the store, so an ability built from the store alone
would answer "no rules" and empty the file.
320
321
322
|
# File 'app/models/spree/export.rb', line 320
def current_ability
@current_ability ||= Spree.ability_class.new(user, { store: store, resource: seller || store })
end
|
Returns an array of custom_field headers for the model
178
179
180
181
|
# File 'app/models/spree/export.rb', line 178
def
@custom_fields_headers ||= store.custom_field_definitions.for_resource_type(model_class.to_s).
order(:namespace, :key).map(&:csv_header_name)
end
|
#decode_prefixed_id_filters(params) ⇒ Object
Replace any prefixed IDs in search_params with their raw DB IDs so
Ransack can match them. Without this, an admin filtering an export by
a foreign key (promotion_id_eq: 'promo_xxx', seller_id_in: [...])
would always get zero rows. We only touch values that look like
prefixed IDs — anything else (numeric IDs, code strings, ranges,
state names) passes through untouched.
268
269
270
|
# File 'app/models/spree/export.rb', line 268
def decode_prefixed_id_filters(params)
params.transform_values { |value| decode_search_value(value) }
end
|
#decode_search_value(value) ⇒ Object
272
273
274
275
276
277
278
279
280
281
|
# File 'app/models/spree/export.rb', line 272
def decode_search_value(value)
case value
when String
Spree::PrefixedId.prefixed_id?(value) ? (Spree::PrefixedId.decode_prefixed_id(value) || value) : value
when Array
value.map { |v| decode_search_value(v) }
else
value
end
end
|
#decoded_search_params ⇒ ActiveSupport::HashWithIndifferentAccess
parsed_search_params with prefixed ids decoded to primary keys.
258
259
260
|
# File 'app/models/spree/export.rb', line 258
def decoded_search_params
decode_prefixed_id_filters(parsed_search_params)
end
|
#done? ⇒ Boolean
107
108
109
|
# File 'app/models/spree/export.rb', line 107
def done?
attachment.present? && attachment.attached?
end
|
#event_serializer_class ⇒ Object
103
104
105
|
# File 'app/models/spree/export.rb', line 103
def event_serializer_class
'Spree::Api::V3::ExportSerializer'.safe_constantize
end
|
#export_file_name ⇒ Object
eg. Spree::Exports::Products => products-store-my-store-code-20241030133348.csv
325
326
327
|
# File 'app/models/spree/export.rb', line 325
def export_file_name
"#{type.demodulize.underscore}-#{store.code}-#{created_at.strftime('%Y%m%d%H%M%S')}.#{format}"
end
|
#export_tmp_file_path ⇒ Object
Unique per run: the file name repeats for every export of a store's type
in the same second, and two workers writing one path corrupt each other.
331
332
333
|
# File 'app/models/spree/export.rb', line 331
def export_tmp_file_path
@export_tmp_file_path ||= Rails.root.join('tmp', "#{SecureRandom.hex(8)}-#{export_file_name}")
end
|
#filtered_records ⇒ Object
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
|
# File 'app/models/spree/export.rb', line 224
def filtered_records
return scope.ransack.result if search_params.blank?
params = decoded_search_params
filtered_scope, params = if scope.respond_to?(:with_custom_field_filters)
scope.with_custom_field_filters(
params, schema: Spree::SearchProvider::CustomFieldSchema.new(store)
)
else
[scope, params]
end
filtered_scope.ransack(params, auth_object: seller_id.present? ? :seller : nil).result
end
|
#generate ⇒ Object
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
# File 'app/models/spree/export.rb', line 125
def generate
@filter_locale = I18n.locale
Spree::Current.set(store: store) do
in_store_locale do
send(:"generate_#{format}")
handle_attachment
end
end
send_export_done_email
end
|
#generate_async ⇒ Object
121
122
123
|
# File 'app/models/spree/export.rb', line 121
def generate_async
Spree::Exports::GenerateJob.perform_later(id)
end
|
#generate_csv ⇒ Object
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
# File 'app/models/spree/export.rb', line 141
def generate_csv
::CSV.open(export_tmp_file_path, 'wb', encoding: 'UTF-8', col_sep: ',', row_sep: "\r\n") do |csv|
csv <<
records_to_export.includes(scope_includes).find_in_batches do |batch|
batch.each do |record|
if multi_line_csv?
record.to_csv(store, **to_csv_options).each do |line|
csv << Spree::CSV::FormulaSanitizer.row(line)
end
else
csv << Spree::CSV::FormulaSanitizer.row(record.to_csv(store, **to_csv_options))
end
end
end
end
end
|
#handle_attachment ⇒ Object
187
188
189
190
191
|
# File 'app/models/spree/export.rb', line 187
def handle_attachment
file = ::File.open(export_tmp_file_path)
attachment.attach(io: file, filename: export_file_name)
::File.delete(export_tmp_file_path) if ::File.exist?(export_tmp_file_path)
end
|
#model_class ⇒ Object
eg. Spree::Exports::Products => Spree::Product
288
289
290
291
292
293
294
|
# File 'app/models/spree/export.rb', line 288
def model_class
if type == 'Spree::Exports::Customers'
Spree.customer_class
else
"Spree::#{type.demodulize.singularize}".constantize
end
end
|
#multi_line_csv? ⇒ Boolean
158
159
160
|
# File 'app/models/spree/export.rb', line 158
def multi_line_csv?
false
end
|
#normalize_search_params ⇒ Object
Ensures search params maintain consistent format between UI and exports
- Preserves valid JSON unchanged
- Converts Ruby hashes to JSON strings
- Handles malformed input gracefully
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
|
# File 'app/models/spree/export.rb', line 300
def normalize_search_params
return if search_params.blank?
if search_params.is_a?(Hash)
self.search_params = search_params.to_json
return
end
begin
parsed = JSON.parse(search_params.to_s)
self.search_params = parsed.to_json
rescue JSON::ParserError
end
end
|
#parsed_search_params ⇒ ActiveSupport::HashWithIndifferentAccess
search_params as a Hash — whether it is still the Hash a caller
assigned or the JSON string the column stores.
248
249
250
251
252
253
|
# File 'app/models/spree/export.rb', line 248
def parsed_search_params
return {}.with_indifferent_access if search_params.blank?
params = search_params.is_a?(String) ? JSON.parse(search_params.to_s).to_h : search_params
params.to_h.with_indifferent_access
end
|
#records_to_export ⇒ Object
220
221
222
|
# File 'app/models/spree/export.rb', line 220
def records_to_export
in_filter_locale { filtered_records }
end
|
#required_key_scopes ⇒ Array<String>?
Catalog keys a delegated credential must hold, beyond the export type's
own read scope, to create or download this export. Only exports whose
rows depend on what they were asked for (a report) need any; nil means
they could not be worked out, and the export must be refused.
117
118
119
|
# File 'app/models/spree/export.rb', line 117
def required_key_scopes
[]
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.
337
338
339
|
# File 'app/models/spree/export.rb', line 337
def results_url
preferred_results_url.presence
end
|
#results_url=(value) ⇒ Object
341
342
343
|
# File 'app/models/spree/export.rb', line 341
def results_url=(value)
self.preferred_results_url = value
end
|
#scope ⇒ Object
The records this export may contain.
Tenancy is these scope narrowings, never the ability: a seller holding
read_orders is granted the model class, not their own subset (see
Spree::Ability), so dropping for_seller here would put every seller's
rows in one seller's file.
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
|
# File 'app/models/spree/export.rb', line 199
def scope
scope = model_class
scope = scope.for_store(store) if model_class.respond_to?(:for_store)
if seller.present?
raise SellerScopeUnavailable, model_class unless model_class.respond_to?(:for_seller)
scope = scope.for_seller(seller)
end
scope = scope.not_drafts if model_class.respond_to?(:not_drafts)
scope = scope.accessible_by(current_ability) if user.present?
scope
end
|
#scope_includes ⇒ Object
283
284
285
|
# File 'app/models/spree/export.rb', line 283
def scope_includes
[]
end
|
#send_export_done_email ⇒ Object
345
346
347
348
349
|
# File 'app/models/spree/export.rb', line 345
def send_export_done_email
return if user.blank?
Spree::ExportMailer.export_done(self).deliver_later
end
|
#to_csv_options ⇒ Hash
Keyword arguments passed to each record's to_csv. Subclasses override
to narrow what a particular export writes — see Spree::Exports::Orders,
which drops columns a seller may not read.
167
168
169
|
# File 'app/models/spree/export.rb', line 167
def to_csv_options
{}
end
|