spree_core 6.0.0.rc4 → 6.0.0.rc6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. checksums.yaml +4 -4
  2. data/app/jobs/spree/images/save_from_url_job.rb +24 -5
  3. data/app/models/concerns/spree/account_deactivation.rb +54 -0
  4. data/app/models/concerns/spree/calculator/currency_amounts.rb +19 -6
  5. data/app/models/concerns/spree/derived_number.rb +1 -1
  6. data/app/models/concerns/spree/has_external_references.rb +24 -16
  7. data/app/models/concerns/spree/prefixed_id.rb +15 -5
  8. data/app/models/concerns/spree/publishable.rb +47 -1
  9. data/app/models/concerns/spree/purchase/addresses.rb +114 -36
  10. data/app/models/concerns/spree/purchase/digital_items.rb +17 -3
  11. data/app/models/concerns/spree/purchase/freight.rb +2 -1
  12. data/app/models/concerns/spree/purchase/payment_processing.rb +7 -1
  13. data/app/models/concerns/spree/purchase/quantity_rules.rb +2 -0
  14. data/app/models/concerns/spree/stores/channels.rb +3 -1
  15. data/app/models/concerns/spree/translatable_resource.rb +6 -1
  16. data/app/models/concerns/spree/webhook_payload_redaction.rb +1 -0
  17. data/app/models/spree/ability.rb +8 -0
  18. data/app/models/spree/address.rb +6 -0
  19. data/app/models/spree/admin_user.rb +1 -0
  20. data/app/models/spree/base.rb +33 -1
  21. data/app/models/spree/calculator/shipping/digital_delivery.rb +3 -1
  22. data/app/models/spree/calculator/shipping/flat_rate.rb +3 -1
  23. data/app/models/spree/calculator/shipping/per_item.rb +3 -1
  24. data/app/models/spree/cart.rb +7 -7
  25. data/app/models/spree/category.rb +76 -5
  26. data/app/models/spree/channel.rb +79 -40
  27. data/app/models/spree/company.rb +46 -3
  28. data/app/models/spree/customer.rb +1 -1
  29. data/app/models/spree/customer_group.rb +59 -41
  30. data/app/models/spree/data_request.rb +34 -1
  31. data/app/models/spree/delivery_method.rb +18 -8
  32. data/app/models/spree/delivery_profile.rb +18 -0
  33. data/app/models/spree/digital_asset.rb +14 -0
  34. data/app/models/spree/event.rb +20 -5
  35. data/app/models/spree/fulfillment.rb +8 -1
  36. data/app/models/spree/fulfillment_changer.rb +3 -1
  37. data/app/models/spree/fulfillment_item.rb +11 -0
  38. data/app/models/spree/import.rb +20 -2
  39. data/app/models/spree/order.rb +1 -1
  40. data/app/models/spree/order_routing/strategy/rules.rb +4 -1
  41. data/app/models/spree/price_list.rb +15 -0
  42. data/app/models/spree/product/channels.rb +16 -8
  43. data/app/models/spree/product.rb +7 -2
  44. data/app/models/spree/return.rb +8 -1
  45. data/app/models/spree/sales_context.rb +162 -0
  46. data/app/models/spree/search_provider/base.rb +8 -3
  47. data/app/models/spree/search_provider/database.rb +2 -10
  48. data/app/models/spree/seller.rb +35 -5
  49. data/app/models/spree/seller_balance.rb +28 -0
  50. data/app/models/spree/seller_requirements/delivery_method.rb +20 -2
  51. data/app/models/spree/stock/coordinator.rb +7 -4
  52. data/app/models/spree/stock/estimator.rb +6 -0
  53. data/app/models/spree/stock/inventory_unit_builder.rb +14 -2
  54. data/app/models/spree/stock/packer.rb +39 -5
  55. data/app/models/spree/stock/quantifier.rb +16 -0
  56. data/app/models/spree/stock_location.rb +15 -8
  57. data/app/models/spree/store.rb +31 -2
  58. data/app/models/spree/store_credit.rb +4 -4
  59. data/app/models/spree/tax_line.rb +5 -4
  60. data/app/models/spree/variant.rb +23 -6
  61. data/app/models/spree/webhook_endpoint.rb +45 -11
  62. data/app/services/spree/carts/destroy.rb +7 -2
  63. data/app/services/spree/carts/price_items.rb +3 -0
  64. data/app/services/spree/carts/split_by_seller.rb +3 -1
  65. data/app/services/spree/carts/update.rb +1 -4
  66. data/app/services/spree/catalogs/set_product_terms.rb +8 -3
  67. data/app/services/spree/collections/add_products.rb +1 -1
  68. data/app/services/spree/collections/regenerate_products.rb +1 -3
  69. data/app/services/spree/collections/remove_products.rb +1 -1
  70. data/app/services/spree/data_requests/confirm.rb +37 -0
  71. data/app/services/spree/data_requests/create.rb +61 -13
  72. data/app/services/spree/newsletter/subscribe.rb +9 -1
  73. data/app/services/spree/order_groups/allocate_payments.rb +7 -5
  74. data/app/services/spree/orders/update.rb +19 -0
  75. data/app/services/spree/product_memberships.rb +16 -6
  76. data/app/services/spree/products/duplicator.rb +12 -4
  77. data/app/services/spree/search_provider/custom_field_schema.rb +10 -2
  78. data/app/services/spree/stock_levels/correct.rb +11 -4
  79. data/app/services/spree/stock_reservations/reserve.rb +1 -1
  80. data/app/services/spree/stores/provision_defaults.rb +11 -7
  81. data/app/services/spree/tags/bulk_add.rb +16 -6
  82. data/app/workflows/spree/carts/complete.rb +25 -9
  83. data/app/workflows/spree/carts/upsert_items.rb +31 -4
  84. data/app/workflows/spree/customers/anonymize.rb +40 -19
  85. data/app/workflows/spree/data_requests/fulfill.rb +20 -6
  86. data/app/workflows/spree/digital_assets/create.rb +56 -0
  87. data/app/workflows/spree/digital_assets/update.rb +44 -0
  88. data/app/workflows/spree/digital_assets/writing.rb +108 -0
  89. data/app/workflows/spree/imports/start_mapping.rb +3 -1
  90. data/app/workflows/spree/orders/complete.rb +12 -5
  91. data/app/workflows/spree/orders/create.rb +41 -17
  92. data/app/workflows/spree/payments/capture.rb +12 -0
  93. data/app/workflows/spree/products/nested_attributes.rb +12 -28
  94. data/app/workflows/spree/products/propose.rb +9 -4
  95. data/app/workflows/spree/stock_levels/bulk_upsert.rb +28 -13
  96. data/app/workflows/spree/variants/nested_attributes.rb +35 -10
  97. data/config/locales/en.yml +14 -0
  98. data/db/migrate/20261022000001_store_credit_actor_polymorphic.rb +13 -0
  99. data/db/migrate/20261023100001_add_deactivated_at_to_spree_admin_users.rb +7 -0
  100. data/lib/generators/spree/dummy/templates/rails/test.rb +87 -0
  101. data/lib/spree/checkout/default_requirements.rb +12 -2
  102. data/lib/spree/core/dependencies.rb +5 -0
  103. data/lib/spree/core/engine.rb +2 -0
  104. data/lib/spree/core/permissions/default_catalog.rb +7 -2
  105. data/lib/spree/core/version.rb +1 -1
  106. data/lib/spree/reporting/default_vocabulary.rb +1 -1
  107. data/lib/spree/testing_support/factories/data_request_factory.rb +4 -0
  108. data/lib/spree/testing_support/factories/product_factory.rb +10 -4
  109. data/lib/spree/testing_support/factories/store_factory.rb +4 -1
  110. data/lib/spree/upgrades/5_6_to_6_0/manifest.yml +10 -0
  111. data/lib/tasks/backfill_tagging_tenants.rake +35 -0
  112. data/lib/tasks/seller_sample_data.rake +114 -112
  113. metadata +15 -6
@@ -10,8 +10,15 @@ module Spree
10
10
  # @param context [String] default: 'tags'
11
11
  # @return [Spree::ServiceModule::Base::Result]
12
12
  def call(tag_names: [], records: [], context: 'tags')
13
- tags = tag_names.map do |tag_name|
14
- ActsAsTaggableOn::Tag.find_or_create_by(name: tag_name.strip)
13
+ names = tag_names.map(&:strip).reject(&:blank?).uniq
14
+ return if names.empty?
15
+
16
+ # One read for the names that already exist, then a create only for
17
+ # the ones that do not. `find_or_create_by` per name is a query per
18
+ # tag, which a bulk tagging pays on every name in the payload.
19
+ existing = ActsAsTaggableOn::Tag.where(name: names).index_by(&:name)
20
+ tags = names.map do |name|
21
+ existing[name] || ActsAsTaggableOn::Tag.create_or_find_by(name: name)
15
22
  end
16
23
 
17
24
  record_class = records.first.class
@@ -27,17 +34,20 @@ module Spree
27
34
 
28
35
  private
29
36
 
37
+ # Mirrors the gem's own tagging save, which stores the taggable's tenant
38
+ # (its `store_id` for store-owned records) as a string on each tagging.
30
39
  def taggings_attributes(tags, records, context:, record_class:)
31
- records.pluck(:id).map do |record_id|
40
+ records.flat_map do |record|
32
41
  tags.map do |tag|
33
42
  {
34
- taggable_id: record_id,
43
+ taggable_id: record.id,
35
44
  taggable_type: record_class.to_s,
36
45
  context: context,
37
- tag_id: tag.id
46
+ tag_id: tag.id,
47
+ tenant: record.taggable_tenant&.to_s
38
48
  }
39
49
  end
40
- end.flatten.compact
50
+ end
41
51
  end
42
52
  end
43
53
  end
@@ -422,10 +422,21 @@ module Spree
422
422
  # provider a question whose answer is discarded — and for an external
423
423
  # engine that is a billable remote call per line item, inside the
424
424
  # completion lock.
425
+ #
426
+ # Each copy is handed the cart line's variant, loaded once for every
427
+ # line, so validating the copies reads its product, stock and tax
428
+ # category for all of them at once rather than per line.
425
429
  def copy_line_items!(cart, order)
426
- cart.line_items.reload.index_with do |cart_line_item|
430
+ cart_line_items = cart.line_items.reload.to_a
431
+ ActiveRecord::Associations::Preloader.new(
432
+ records: cart_line_items,
433
+ associations: { variant: [{ product: %i[store product_publications tax_category] }, { stock_levels: %i[stock_location active_stock_reservations] }] }
434
+ ).call
435
+
436
+ cart_line_items.index_with do |cart_line_item|
427
437
  attributes = cart_line_item.attributes.except('id', 'cart_id', 'created_at', 'updated_at')
428
438
  line_item = order.line_items.new(attributes.merge('order_id' => order.id))
439
+ line_item.variant = cart_line_item.variant if cart_line_item.variant
429
440
  line_item.skip_tax_estimation = true
430
441
  line_item.save!
431
442
  line_item
@@ -434,9 +445,12 @@ module Spree
434
445
 
435
446
  # @return [Hash{Integer => Integer}] cart fulfillment id → order fulfillment id
436
447
  def copy_fulfillments!(cart, order, line_item_map)
437
- line_item_id_map = line_item_map.transform_keys(&:id).transform_values(&:id)
448
+ line_items_by_cart_line_item_id = line_item_map.transform_keys(&:id)
449
+
450
+ cart_fulfillments = cart.fulfillments.reload.to_a
451
+ ActiveRecord::Associations::Preloader.new(records: cart_fulfillments, associations: %i[selected_delivery_rate fulfillment_items]).call
438
452
 
439
- cart.fulfillments.reload.each_with_object({}) do |cart_fulfillment, map|
453
+ cart_fulfillments.each_with_object({}) do |cart_fulfillment, map|
440
454
  attributes = cart_fulfillment.attributes.except('id', 'cart_id', 'number', 'tracking', 'created_at', 'updated_at')
441
455
  fulfillment = order.fulfillments.create!(attributes.merge('order_id' => order.id, 'address_id' => order.ship_address_id))
442
456
 
@@ -447,13 +461,15 @@ module Spree
447
461
 
448
462
  cart_fulfillment.fulfillment_items.each do |item|
449
463
  item_attributes = item.attributes.except('id', 'created_at', 'updated_at')
450
- fulfillment.fulfillment_items.create!(
451
- item_attributes.merge(
452
- 'fulfillment_id' => fulfillment.id,
453
- 'order_id' => order.id,
454
- 'line_item_id' => line_item_id_map.fetch(item.line_item_id)
455
- )
464
+ line_item = line_items_by_cart_line_item_id.fetch(item.line_item_id)
465
+ fulfillment_item = fulfillment.fulfillment_items.new(
466
+ item_attributes.merge('fulfillment_id' => fulfillment.id, 'order_id' => order.id)
456
467
  )
468
+ # Objects rather than ids, so validating the copy does not look
469
+ # each of them up again.
470
+ fulfillment_item.line_item = line_item
471
+ fulfillment_item.variant = line_item.variant if line_item.variant_id == item.variant_id
472
+ fulfillment_item.save!
457
473
  end
458
474
 
459
475
  map[cart_fulfillment.id] = fulfillment.id
@@ -90,9 +90,10 @@ module Spree
90
90
  # applied.
91
91
  def resolve_items
92
92
  store = cart.store || Spree::Current.store
93
+ requested_items = Array(items).map { |item_params| item_params.to_h.deep_symbolize_keys }
94
+ prefetch_added_variants(store, requested_items)
93
95
 
94
- @resolved_items = Array(items).filter_map do |item_params|
95
- item_params = item_params.to_h.deep_symbolize_keys
96
+ @resolved_items = requested_items.filter_map do |item_params|
96
97
  quantity = (item_params[:quantity] || 1).to_i
97
98
  variant = resolve_variant(store, item_params[:variant_id], removing: quantity <= 0)
98
99
  next if variant.nil?
@@ -357,18 +358,44 @@ module Spree
357
358
  cart.line_items.detect { |line_item| line_item.variant_id.to_s == variant_id.to_s }&.variant ||
358
359
  Spree::Variant.with_deleted.find_by_param(variant_id)
359
360
  else
360
- variant = store.variants.find_by_param(variant_id)
361
+ variant = @added_variants[variant_param_id(variant_id)]
361
362
  # +orderable_variants+ narrows what a request may add. A line already
362
363
  # in the cart is a quantity edit and resolves as before — checkout
363
364
  # judges it — so one stale line cannot fail a whole cart's update.
364
365
  if variant && orderable_variants && cart.line_items.none? { |line_item| line_item.variant_id == variant.id }
365
- variant = orderable_variants.find_by(id: variant.id)
366
+ variant = nil unless @orderable_added_variant_ids.include?(variant.id)
366
367
  end
367
368
 
368
369
  variant || raise(ActiveRecord::RecordNotFound.new("Variant '#{variant_id}' not found in this store", 'Spree::Variant', 'id', variant_id))
369
370
  end
370
371
  end
371
372
 
373
+ # Every variant the batch adds, looked up through the store in one
374
+ # query rather than one per item, and which of them the buyer may order.
375
+ def prefetch_added_variants(store, requested_items)
376
+ ids = requested_items.filter_map do |item_params|
377
+ variant_param_id(item_params[:variant_id]) if (item_params[:quantity] || 1).to_i.positive?
378
+ end
379
+
380
+ @added_variants = ids.empty? ? {} : store.variants.where(id: ids.uniq).preload_associations_lazily.index_by(&:id)
381
+ Spree::Stock::Quantifier.preload(@added_variants.values)
382
+ @orderable_added_variant_ids = if orderable_variants && @added_variants.any?
383
+ orderable_variants.where(id: @added_variants.keys).pluck(:id).to_set
384
+ else
385
+ Set.new
386
+ end
387
+ end
388
+
389
+ # The id a variant param names: a prefixed id, or a bare integer id
390
+ # kept for backwards compatibility.
391
+ #
392
+ # @return [Integer, nil]
393
+ def variant_param_id(param)
394
+ return nil if param.blank?
395
+
396
+ Spree::Variant.decode_prefixed_id(param) || (param.to_s.to_i if param.to_s.match?(/\A\d+\z/))
397
+ end
398
+
372
399
  def warn(index, item, code, message)
373
400
  warnings << Spree::Carts::ItemWarning.new(item_index: index, variant: item.variant, code: code, message: message)
374
401
  end
@@ -212,9 +212,15 @@ module Spree
212
212
  # redacting that would overwrite the shared address for every other
213
213
  # member and every other order. Only rows this person owns, or rows
214
214
  # nobody owns, are this erasure's to rewrite.
215
+ #
216
+ # Ownership is the id alone, never the type. A snapshot taken from a
217
+ # company site keeps its owner_type so the copy stays addressed to a
218
+ # business rather than to a person, so matching on the type too would
219
+ # skip exactly those copies — and an erasure that quietly covers less
220
+ # than it did raises nothing.
215
221
  snapshots = Spree::Address.where(id: address_ids)
216
222
  mine = snapshots.where(owner_type: customer.class.base_class.to_s, owner_id: customer.id)
217
- unowned = snapshots.where(owner_type: nil, owner_id: nil)
223
+ unowned = snapshots.where(owner_id: nil)
218
224
 
219
225
  mine.or(unowned).find_each do |address|
220
226
  redact_address(address, deleted: false)
@@ -312,7 +318,7 @@ module Spree
312
318
  }
313
319
 
314
320
  owner_ids.each do |owner_type, ids|
315
- Spree::ShippingLabel.where(owner_type: owner_type, owner_id: ids).find_each do |label|
321
+ Spree::ShippingLabel.where(owner_type: owner_type, owner_id: ids).with_attached_file.find_each do |label|
316
322
  purge_after_commit(label.file)
317
323
  end
318
324
  end
@@ -402,12 +408,14 @@ module Spree
402
408
  # complete copy of everything being erased, sitting behind a link that
403
409
  # stays live for days. Rewriting the row's email would leave the
404
410
  # payload itself untouched and still fetchable.
405
- requests.each do |data_request|
411
+ requests.with_attached_export_file.each do |data_request|
406
412
  purge_after_commit(data_request.export_file)
407
413
  end
408
414
 
409
415
  # The token goes too, so a link already emailed stops resolving rather
410
- # than waiting out its expiry.
416
+ # than waiting out its expiry. Confirmation links are bound to it, so
417
+ # a request still waiting for one can never be confirmed.
418
+ requests.awaiting_confirmation.update_all(status: 'lapsed', updated_at: Time.current)
411
419
  requests.update_all(
412
420
  email: customer.email,
413
421
  download_token: nil,
@@ -458,22 +466,35 @@ module Spree
458
466
 
459
467
  # @param address [Spree::Address]
460
468
  # @param deleted [Boolean] whether to soft-delete it as well
469
+ # What the person left on an address, rewritten; the address itself kept
470
+ # readable enough to answer a tax enquiry.
471
+ #
472
+ # A snapshot copied from a company site is the narrower case. The dock
473
+ # and the trading name on it are the business's, not this person's, and
474
+ # erasing them would take the merchant's record of a lawful sale with
475
+ # them — so only the contact details go. A business address is allowed
476
+ # to name nobody, which is why those fields are emptied rather than
477
+ # stamped: writing "Redacted" where a company never named anyone would
478
+ # invent a person who was not there.
461
479
  def redact_address(address, deleted:)
462
- attributes = {
463
- first_name: REDACTED_NAME,
464
- last_name: REDACTED_NAME,
465
- address1: REDACTED_NAME,
466
- address2: nil,
467
- phone: nil,
468
- alternative_phone: nil,
469
- company: nil,
470
- label: nil,
471
- latitude: nil,
472
- longitude: nil,
473
- postal_code: truncated_postal_code(address.postal_code),
474
- metadata: {},
475
- updated_at: Time.current
476
- }
480
+ attributes =
481
+ if address.business_owned?
482
+ { first_name: nil, last_name: nil }
483
+ else
484
+ {
485
+ first_name: REDACTED_NAME,
486
+ last_name: REDACTED_NAME,
487
+ address1: REDACTED_NAME,
488
+ address2: nil,
489
+ company: nil,
490
+ label: nil,
491
+ latitude: nil,
492
+ longitude: nil,
493
+ postal_code: truncated_postal_code(address.postal_code)
494
+ }
495
+ end
496
+
497
+ attributes.merge!(phone: nil, alternative_phone: nil, metadata: {}, updated_at: Time.current)
477
498
  attributes[:deleted_at] = Time.current if deleted && address.deleted_at.nil?
478
499
 
479
500
  address.update_columns(attributes)
@@ -36,6 +36,7 @@ module Spree
36
36
  super
37
37
 
38
38
  step :ensure_pending
39
+ step :ensure_addressed_to_customer
39
40
  step :mark_processing
40
41
 
41
42
  run_hooks :before_fulfill
@@ -56,6 +57,15 @@ module Spree
56
57
  failure(data_request, I18n.t('spree.data_request_errors.not_pending'))
57
58
  end
58
59
 
60
+ # An account already erased has a replaced address by design, and
61
+ # erase_customer counts that as done.
62
+ def ensure_addressed_to_customer
63
+ customer = data_request.customer
64
+ return if customer.nil? || customer.anonymized? || data_request.addressed_to_customer?
65
+
66
+ failure(data_request, I18n.t('spree.data_request_errors.address_changed'))
67
+ end
68
+
59
69
  def mark_processing
60
70
  data_request.update!(status: 'processing')
61
71
  end
@@ -78,21 +88,25 @@ module Spree
78
88
  # anonymizer starts after the check and finishes its attachment scan
79
89
  # before this attaches, stranding a full personal-data file it will
80
90
  # never see.
91
+ #
92
+ # The address is checked again under the same lock, so it cannot change
93
+ # between the check and the export reading it.
81
94
  return attach_export unless customer
82
95
 
83
- refused = false
96
+ refusal = nil
84
97
 
85
98
  customer.with_lock do
86
- if customer.reload.anonymized?
87
- refused = true
99
+ customer.reload
100
+ if customer.anonymized?
101
+ refusal = 'spree.data_request_errors.already_anonymized'
102
+ elsif !data_request.addressed_to_customer?
103
+ refusal = 'spree.data_request_errors.address_changed'
88
104
  else
89
105
  attach_export
90
106
  end
91
107
  end
92
108
 
93
- return unless refused
94
-
95
- failure(data_request, I18n.t('spree.data_request_errors.already_anonymized'))
109
+ failure(data_request, I18n.t(refusal)) if refusal
96
110
  end
97
111
 
98
112
  def attach_export
@@ -0,0 +1,56 @@
1
+ module Spree
2
+ module DigitalAssets
3
+ # Adds a downloadable file (or a provider-backed deliverable) to a product.
4
+ #
5
+ # The single gate for new assets: the operator's and the seller's nested
6
+ # endpoints and the `digital_assets` list on a product write all run
7
+ # through it, so a :validate handler sees every file a catalog gains.
8
+ # A host that scans uploads registers on `digital_assets.create.validate`
9
+ # for a quick check, or on `after_create` to queue a slower one; the bytes
10
+ # are already in storage when either fires.
11
+ #
12
+ # Passing `seller:` applies the marketplace's rules for a seller's file —
13
+ # whether sellers may upload at all, which content types, and whether an
14
+ # approved listing goes back to review. The operator's own writes pass none.
15
+ class Create < Spree::Workflow
16
+ include Spree::DigitalAssets::Writing
17
+
18
+ hooks :validate, :after_create
19
+
20
+ # The unsaved record a :validate handler reads.
21
+ attr_reader :digital_asset
22
+
23
+ # @param product [Spree::Product]
24
+ # @param attributes [Hash] `signed_id`, `variant_id`, the download limits
25
+ # and, for the operator, the provider fields
26
+ # @param seller [Spree::Seller, nil] the seller this file is written for
27
+ # @param submitted_by [Spree.admin_user_class, nil] who made the change,
28
+ # named on the review it may reopen
29
+ # @return [Spree::ServiceModule::Result] value is the digital asset
30
+ def perform(product:, attributes: {}, seller: nil, submitted_by: nil)
31
+ super
32
+
33
+ step :build_digital_asset
34
+ step :resolve_upload
35
+ step :enforce_seller_rules
36
+ run_hooks :validate
37
+
38
+ ApplicationRecord.transaction do
39
+ step :attach_upload
40
+ step :save_digital_asset
41
+ step :reopen_review
42
+ run_hooks :after_create
43
+ end
44
+
45
+ success(digital_asset)
46
+ end
47
+
48
+ private
49
+
50
+ def build_digital_asset
51
+ @digital_asset = Spree::DigitalAsset.new
52
+ assign_attributes
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,44 @@
1
+ module Spree
2
+ module DigitalAssets
3
+ # Changes a digital asset: its download limits, the variant it hangs off,
4
+ # or the file itself. Replacing the file keeps every already-issued link
5
+ # working, since links resolve through the asset rather than the blob.
6
+ #
7
+ # Handlers reading `digital_asset.changes` in :validate see the pending
8
+ # edit; `blob` is the replacement file, when the payload carries one.
9
+ class Update < Spree::Workflow
10
+ include Spree::DigitalAssets::Writing
11
+
12
+ hooks :validate, :after_update
13
+
14
+ # @param digital_asset [Spree::DigitalAsset]
15
+ # @param attributes [Hash] see Spree::DigitalAssets::Create
16
+ # @param seller [Spree::Seller, nil] the seller this change is written for
17
+ # @param submitted_by [Spree.admin_user_class, nil] who made the change
18
+ # @return [Spree::ServiceModule::Result] value is the digital asset
19
+ def perform(digital_asset:, attributes: {}, seller: nil, submitted_by: nil)
20
+ super
21
+
22
+ step :assign_attributes
23
+ step :resolve_upload
24
+ step :enforce_seller_rules
25
+ run_hooks :validate
26
+
27
+ ApplicationRecord.transaction do
28
+ step :attach_upload
29
+ step :save_digital_asset
30
+ step :reopen_review
31
+ run_hooks :after_update
32
+ end
33
+
34
+ success(digital_asset)
35
+ end
36
+
37
+ private
38
+
39
+ def product
40
+ digital_asset.product
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,108 @@
1
+ module Spree
2
+ module DigitalAssets
3
+ # The steps a file write shares between Create and Update: the upload the
4
+ # payload names, the marketplace's rules for a seller's file, and sending
5
+ # an approved listing back to review once what it delivers has changed.
6
+ module Writing
7
+ extend ActiveSupport::Concern
8
+
9
+ # Why a product reopened review: recorded on the submission row so the
10
+ # operator's queue says what changed.
11
+ REVIEW_REASON = 'digital_asset_changed'.freeze
12
+
13
+ included do
14
+ # The uploaded file the payload names, resolved before it is attached.
15
+ attr_reader :blob
16
+ end
17
+
18
+ private
19
+
20
+ def assign_attributes
21
+ attrs = attributes.to_h.with_indifferent_access
22
+ @signed_id = attrs.delete(:signed_id)
23
+ variant_id = attrs.delete(:variant_id)
24
+
25
+ digital_asset.assign_attributes(attrs)
26
+ # Through the product's own variants, so an asset reached through one
27
+ # product can never point at another product's variant.
28
+ digital_asset.variant = product.variants.find_by_param!(variant_id) if variant_id.present?
29
+ digital_asset.variant ||= product.default_variant
30
+ end
31
+
32
+ def resolve_upload
33
+ return if @signed_id.blank?
34
+
35
+ @blob = ActiveStorage::Blob.find_signed(@signed_id)
36
+ return refuse(:digital_assets_upload_not_found) if blob.nil?
37
+
38
+ # Attaching never moves a blob between storage services, so a file
39
+ # uploaded to the public bucket would stay publicly readable while
40
+ # looking attached.
41
+ unless blob.service_name.to_s == Spree.private_storage_service_name.to_s
42
+ return refuse(:digital_assets_attachment_must_be_private)
43
+ end
44
+
45
+ # A provider-backed asset delivers through its provider, so a file on
46
+ # it would show in the panel but never reach a buyer. An unregistered
47
+ # provider is left to the model's validation rather than asked.
48
+ return unless Spree.digital_asset_providers.include?(digital_asset.provider_class)
49
+
50
+ refuse(:digital_assets_provider_takes_no_file) unless digital_asset.provider_class.requires_attachment?
51
+ end
52
+
53
+ # What the marketplace lets a seller attach. The operator's own writes
54
+ # are not subject to these: the operator is who the rules protect.
55
+ def enforce_seller_rules
56
+ return if seller.nil?
57
+
58
+ refuse(:digital_assets_sellers_disabled) unless store.preferred_seller_digital_assets_enabled
59
+ return if blob.nil?
60
+
61
+ # Identifying reads the file's own signature where it has one, so a
62
+ # renamed executable cannot pass as a PDF; a format with no signature
63
+ # (plain text) keeps the type the client declared.
64
+ blob.identify_without_saving
65
+ return if content_type_accepted?(blob.content_type)
66
+
67
+ refuse(:digital_assets_content_type_not_accepted, content_type: blob.content_type)
68
+ end
69
+
70
+ # An entry names one type (`audio/mpeg`) or a whole family (`audio/*`).
71
+ def content_type_accepted?(content_type)
72
+ family = "#{content_type.to_s.split('/').first}/*"
73
+ store.preferred_seller_digital_asset_content_types.any? { |accepted| accepted.casecmp?(content_type.to_s) || accepted == family }
74
+ end
75
+
76
+ def attach_upload
77
+ digital_asset.attachment.attach(blob) if blob
78
+ end
79
+
80
+ def save_digital_asset
81
+ failure(digital_asset) unless digital_asset.save
82
+ end
83
+
84
+ # A seller changing what an approved listing delivers reopens its review.
85
+ # The operator's own change does not: they are the reviewer.
86
+ def reopen_review
87
+ return if seller.nil? || blob.nil? || !product.active?
88
+ return unless store.preferred_review_seller_digital_asset_changes
89
+ return if store.preferred_auto_approve_seller_products
90
+
91
+ result = Spree.product_propose_workflow.call(product: product, submitted_by: submitted_by, reason: REVIEW_REASON)
92
+ return if result.success?
93
+
94
+ digital_asset.errors.add(:base, result.error.to_s)
95
+ failure(digital_asset)
96
+ end
97
+
98
+ def store
99
+ product.store
100
+ end
101
+
102
+ def refuse(key, **options)
103
+ digital_asset.errors.add(:base, I18n.t("spree.#{key}", **options))
104
+ failure(digital_asset)
105
+ end
106
+ end
107
+ end
108
+ end
@@ -33,8 +33,10 @@ module Spree
33
33
  # TODO: seed from the previous import of the same type, so a merchant
34
34
  # doesn't map the same columns twice.
35
35
  def build_mappings
36
+ existing = import.mappings.index_by(&:schema_field)
37
+
36
38
  import.schema_fields.each do |schema_field|
37
- mapping = import.mappings.find_or_create_by!(schema_field: schema_field[:name])
39
+ mapping = existing[schema_field[:name]] || import.mappings.build(schema_field: schema_field[:name])
38
40
  mapping.try_to_auto_assign_file_column(import.csv_headers)
39
41
  mapping.save!
40
42
  end
@@ -140,11 +140,16 @@ module Spree
140
140
  end
141
141
 
142
142
  def allocate_fulfillment_stock(fulfillment)
143
- fulfillment.manifest.each do |item|
144
- next unless item.variant.track_inventory?
145
- next unless item.quantity.positive?
143
+ items = fulfillment.manifest.select { |item| item.variant.track_inventory? && item.quantity.positive? }
144
+ return if items.empty?
146
145
 
147
- fulfillment.stock_location.allocate(item.variant, item.quantity, fulfillment)
146
+ stock_location = fulfillment.stock_location
147
+ # Lowest id first, as StockLocation#stock_level reads.
148
+ stock_levels = stock_location.stock_levels.where(variant_id: items.map { |item| item.variant.id }).order(:id).
149
+ group_by(&:variant_id).transform_values(&:first)
150
+
151
+ items.each do |item|
152
+ stock_location.allocate(item.variant, item.quantity, fulfillment, stock_level: stock_levels[item.variant.id])
148
153
  end
149
154
  end
150
155
 
@@ -240,7 +245,9 @@ module Spree
240
245
  # wildcard subscribers dedupe on the metadata marker.
241
246
  def publish_order_placed
242
247
  metadata = { notify_customer: order.notify_customer }
243
- payload = order.event_payload
248
+ # The payload renders every line and parcel, read back through a lazily
249
+ # preloading query so each association loads once rather than per row.
250
+ payload = Spree::Order.where(id: order.id).preload_associations_lazily.take!.event_payload
244
251
  order.publish_event('order.placed', payload, metadata)
245
252
  order.publish_event('order.completed', payload, metadata.merge(deprecated_alias_of: 'order.placed'))
246
253
  end
@@ -28,6 +28,14 @@ module Spree
28
28
 
29
29
  return failure(:store_is_required) if store.nil?
30
30
 
31
+ @sales_context = Spree::SalesContext.new(
32
+ store: store,
33
+ market: (resolve_market if @params[:market_id].present?),
34
+ currency: @params[:currency],
35
+ locale: @params[:locale]
36
+ )
37
+ return refuse_sales_context unless @sales_context.valid?
38
+
31
39
  order = nil
32
40
  ApplicationRecord.transaction do
33
41
  order = build_order
@@ -60,8 +68,9 @@ module Spree
60
68
  customer: @customer,
61
69
  created_by: @created_by,
62
70
  email: @params[:email] || @customer&.email,
63
- currency: @params[:currency].presence&.upcase || @store.default_currency,
64
- locale: @params[:locale] || Spree::Current.locale,
71
+ market: @sales_context.market,
72
+ currency: @sales_context.currency,
73
+ locale: @sales_context.locale || Spree::Current.locale,
65
74
  customer_note: @params[:customer_note],
66
75
  po_number: @params[:po_number],
67
76
  internal_note: @params[:internal_note],
@@ -74,7 +83,6 @@ module Spree
74
83
  # signed id, so it assigns like any other attribute.
75
84
  attrs[:po_document_signed_id] = @params[:po_document_signed_id] if @params[:po_document_signed_id].present?
76
85
 
77
- attrs[:market] = resolve_market if @params[:market_id].present?
78
86
  attrs[:channel] = resolve_channel if @params[:channel_id].present?
79
87
  attrs[:company] = resolve_company if @params[:company_id].present?
80
88
  attrs[:preferred_stock_location] = resolve_preferred_stock_location if @params[:preferred_stock_location_id].present?
@@ -83,6 +91,12 @@ module Spree
83
91
  @store.orders.new(attrs)
84
92
  end
85
93
 
94
+ def refuse_sales_context
95
+ order = @store.orders.new
96
+ order.errors.merge!(@sales_context.errors)
97
+ failure(order, order.errors.full_messages.to_sentence)
98
+ end
99
+
86
100
  def resolve_market
87
101
  @store.markets.find_by_param!(@params[:market_id])
88
102
  end
@@ -100,34 +114,44 @@ module Spree
100
114
  end
101
115
 
102
116
  def assign_addresses(order)
103
- if @params[:use_customer_default_address] && @customer
104
- @customer.association(:bill_address).load_target
105
- @customer.association(:ship_address).load_target
106
- order.bill_address = @customer.bill_address&.snapshot
107
- order.ship_address = @customer.ship_address&.snapshot
108
- end
117
+ assign_default_addresses(order) if @params[:use_customer_default_address]
109
118
 
110
119
  assign_address(order, :ship_address, @params[:shipping_address_id], @params[:shipping_address])
111
120
  assign_address(order, :bill_address, @params[:billing_address_id], @params[:billing_address])
121
+ order.use_shipping = @params[:use_shipping]
122
+ end
123
+
124
+ def assign_default_addresses(order)
125
+ company = order.company
126
+
127
+ if company.present?
128
+ order.bill_address = company.default_billing_address&.snapshot
129
+ order.ship_address = company.default_shipping_address&.snapshot
130
+ return
131
+ end
132
+
133
+ return if @customer.nil?
134
+
135
+ @customer.association(:bill_address).load_target
136
+ @customer.association(:ship_address).load_target
137
+ order.bill_address = @customer.bill_address&.snapshot
138
+ order.ship_address = @customer.ship_address&.snapshot
112
139
  end
113
140
 
114
141
  def assign_address(order, association, address_id, address_attrs)
115
142
  if address_id.present?
116
- address = resolve_user_address(address_id)
143
+ address = order.selectable_address(address_id)
117
144
  order.public_send(:"#{association}_id=", address.id) if address
118
145
  elsif address_attrs.present?
119
146
  order.public_send(:"#{association}_attributes=", address_attrs)
120
147
  end
121
148
  end
122
149
 
123
- def resolve_user_address(address_id)
124
- return unless @customer
125
-
126
- @customer.addresses.find_by_param(address_id)
127
- end
128
-
129
150
  def add_items(order)
130
- result = Spree::Orders::UpsertItems.call(order: order, items: @params[:items])
151
+ result = Spree::Orders::UpsertItems.call(
152
+ order: order, items: @params[:items],
153
+ orderable_variants: Spree::SalesContext.from_order(order).orderable_variants
154
+ )
131
155
  return if result.success?
132
156
 
133
157
  propagate_step_failure!(order, result, fallback: 'Failed to add items to order')