class UpgradeEffectiveOrdersFrom1x < ActiveRecord::Migration def self.up create_table <%= @products_table_name %> do |t| t.string :title t.integer :price, :default => 0 t.boolean :tax_exempt, :default => false t.timestamps end add_column <%= @orders_table_name %>, :note, :text add_column <%= @orders_table_name %>, :note_to_buyer, :text add_column <%= @orders_table_name %>, :note_internal, :text add_column <%= @orders_table_name %>, :payment_provider, :string add_column <%= @orders_table_name %>, :payment_card, :string add_column <%= @orders_table_name %>, :tax_rate, :decimal, :precision => 6, :scale => 3 add_column <%= @orders_table_name %>, :subtotal, :integer add_column <%= @orders_table_name %>, :tax, :integer add_column <%= @orders_table_name %>, :total, :integer puts 'Resaving all Effective::Order objects to assign new database column values.' Effective::Order.reset_column_information Effective::Order.find_each do |order| order.tax_rate = ((order.order_items.first.try(:tax_rate) || 0.0) * 100.0) update_payment_provider_and_card(order) order.save(validate: false) print '.' end print "\n" if Effective::Order.any? remove_column <%= @order_items_table_name %>, :tax_rate puts 'Done' end def self.down add_column <%= @order_items_table_name %>, :tax_rate, :decimal, :precision => 5, :scale => 3 Effective::OrderItem.reset_column_information Effective::OrderItem.find_each { |order_item| order_item.update_column(:tax_rate, (order_item.try(:order).tax_rate || 0.0) / 100.0) } remove_column <%= @orders_table_name %>, :note remove_column <%= @orders_table_name %>, :payment_provider remove_column <%= @orders_table_name %>, :payment_card remove_column <%= @orders_table_name %>, :tax_rate remove_column <%= @orders_table_name %>, :subtotal remove_column <%= @orders_table_name %>, :tax remove_column <%= @orders_table_name %>, :total end def update_payment_provider_and_card(order) return unless order.payment.present? payment = HashWithIndifferentAccess.new(order.payment) charge = HashWithIndifferentAccess.new(payment[:charge]) # Try to figure out the payment provider provider = if payment[:response_code] && payment[:transactionKey] 'moneris' elsif charge[:id] && charge[:customer] && charge[:application_fee].present? 'stripe_connect' elsif charge[:id] && charge[:customer] 'stripe' elsif payment[:payer_email] 'paypal' elsif (payment[:details] || '').include?('free') 'free' else 'admin' end card = case provider when 'moneris' payment[:card] when 'stripe_connect' (charge['card']['brand'] rescue nil) when 'stripe' (charge['card']['brand'] rescue nil) when 'paypal' payment[:payment_type] when 'free' 'none' when 'admin' 'none' end order.payment_provider = provider.presence || 'admin' order.payment_card = card.presence || 'unknown' end end