From 0d65838e5daf342c2961a96a6832113ed98f8261 Mon Sep 17 00:00:00 2001 From: Rob Harrington Date: Wed, 2 Mar 2016 17:09:39 +1100 Subject: [PATCH] Adding a second migration to auto-add variants to inventories (I stuffed up the first one, oops) --- .../20160302044850_repopulate_inventories.rb | 30 +++++++++++++++++++ db/schema.rb | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20160302044850_repopulate_inventories.rb diff --git a/db/migrate/20160302044850_repopulate_inventories.rb b/db/migrate/20160302044850_repopulate_inventories.rb new file mode 100644 index 0000000000..e38628439a --- /dev/null +++ b/db/migrate/20160302044850_repopulate_inventories.rb @@ -0,0 +1,30 @@ +class RepopulateInventories < ActiveRecord::Migration + # Previous version of this migration (20160218235221) relied on Permissions#variant_override_producers + # which was then changed, meaning that an incomplete set of variants were added to inventories of most hubs + # Re-running this now will ensure that all permitted variants (including those allowed by 20160224034034) are + # added to the relevant inventories + + def up + # If hubs are actively using overrides, populate their inventories with all variants they have permission to override + # Otherwise leave their inventories empty + + hubs_using_overrides = Enterprise.joins("LEFT OUTER JOIN variant_overrides ON variant_overrides.hub_id = enterprises.id") + .where("variant_overrides.id IS NOT NULL").select("DISTINCT enterprises.*") + + hubs_using_overrides.each do |hub| + overridable_producer_ids = hub.relationships_as_child.with_permission(:create_variant_overrides).map(&:parent_id) | [hub.id] + + variants = Spree::Variant.where(is_master: false, product_id: Spree::Product.not_deleted.where(supplier_id: overridable_producer_ids)) + + variants_to_add = variants.joins("LEFT OUTER JOIN (SELECT * from inventory_items WHERE enterprise_id = #{hub.id}) AS o_inventory_items ON o_inventory_items.variant_id = spree_variants.id") + .where('o_inventory_items.id IS NULL') + + variants_to_add.each do |variant| + inventory_item = InventoryItem.create(enterprise: hub, variant: variant, visible: true) + end + end + end + + def down + end +end diff --git a/db/schema.rb b/db/schema.rb index b7d42102ed..5696e5168a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20160224230143) do +ActiveRecord::Schema.define(:version => 20160302044850) do create_table "account_invoices", :force => true do |t| t.integer "user_id", :null => false