Topic: Rails upgrade

I have a data warehouse type application, which I'm redesigning.  Since I'm going to be redesigning the application to add additional features, I want to upgrade from rails 2.3.5 to rails 3.x.x, while still using Ruby 1.8.7.  Is there an easy way to do this, without having to change several lines of code in a 2k + application?

Re: Rails upgrade

Rails 3+ is working with Ruby 1.9 so,
You should use RVM (Ruby Virtual Machine) which helps you to use many ruby version at the same time. Thus, you just choose whatever version of ruby you want to use on terminal. check it out http://beginrescueend.com/ enjoy.

life is not short however you think to learn Rails

Re: Rails upgrade

Maybe I wrote the question wrong, but what I'm looking for what will no longer work in the rails 2.3.5 app when I upgrade to rails 3+.  Or what section of my code will need to be changed.

Re: Rails upgrade

It's difficult to answer without reviewing your code. I think one of the main reasons for the change from Rails 2.x to Rails 3 was that they dropped support for Ruby 1.8.6 and earlier.  So perhaps if you wrote it in Ruby 1.8.7 or higher you might be okay. It also depends on which gems were used, and whether those have changed as well.

As posted earlier, try installing RVM on a development machine, then install your application under RVM. RVM will then allow you to try different Rails versions and see what happens.

Re: Rails upgrade

RVM doesn't work on a windows server, from what i know.  Everything was developed in 1.8.7. 

The gems i use:

rubygems, faster_csv-1.5.3, fileutils, rexml/document, will_paginate-2.3.12,

plugins used:

jrails and query_reviewer

rails gems used:

rails actionmailer, actionpack, activerecord, activeresource,activesupport, and railties.

Would be best way to go about it create a new skelton of my application with rails 3+ and then re-generate the controllers and paste code into them?

Re: Rails upgrade

Also, when attempting to post the code in [.code] [/.code] it says [.i] can't be opened within itself

Re: Rails upgrade

I fixed it by adding a .

require 'rubygems'
require 'faster_csv'
require 'fileutils'
require 'rexml/document'

class ItemsController < ApplicationController
  layout "trinity_price_comparison"
  before_filter :authorize_admin, :except => [:import_search_file, :pick_search_column, :read_headings_from_file, :create_uom, :cross_reference_import, :commit_cross_references, :show_cross_references, :edit, :search, :search_file_parsed, :show]

  $IGNORED_COLUMNS = ["id", "lock_version", "created_at", "updated_at", "hospital_id", "vendor_id", "category_id", "manufacturer_id", "agreement_id", "sub_category_id", "vendor_catalog_number_no_zero", "vendor_catalog_number_no_dash", "manufacturer_catalog_number_no_zero", "manufacturer_catalog_number_no_dash", "data_source", "data_date"]
  $IGNORED_TABLES = ["sessions", "schema_migrations", "users"]

  # GET /items
  # GET /items.xml
  def index
    @items = Item.paginate :page => params[:page], :order => "created_at DESC", :include => [:hospital, :agreement, :vendor, :manufacturer, :category, :sub_category]

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @items }
    end
  end

  # GET /items/1
  # GET /items/1.xml
  def show
    @item = Item.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @item }
    end
  end

  # GET /items/new
  # GET /items/new.xml
  def new
    @item = Item.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @item }
    end
  end

  # GET /items/1/edit
  def edit
    @item = Item.find(params[:id])
    unless @item.blank?
      @uom_conversions = @item.uom_conversions
    end
    @uom_conversion = UomConversion.new
  end

  # POST /items
  # POST /items.xml
  def create
    @item = Item.new(params[:item])

    respond_to do |format|
      if @item.save
        flash[:notice] = 'Item was successfully created.'
        format.html { redirect_to(@item) }
        format.xml  { render :xml => @item, :status => :created, :location => @item }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @item.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /items/1
  # PUT /items/1.xml
  def update
    @item = Item.find(params[:id])

    respond_to do |format|
      if @item.update_attributes(params[:item])
        flash[:notice] = 'Item was successfully updated.'
        format.html { redirect_to(@item) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @item.errors, :status => :unprocessable_entity }
      end
    end
  end

  def import_search_file
    @feed_types = ActiveSupport::OrderedHash["","", "Lawson", 1, "Cardinal", 3, "Lawson Specials", 2]
  end

  def pick_search_column
    if params[:item].blank?
      flash[:notice] = "Invalid form entry"
      redirect_to :action => "import_search_file"
    elsif params[:source].blank?
      flash[:notice] = "Please select the data source"
      redirect_to :action => "import_search_file"
    else
      file = params[:item][:searchfile]
      path = "#{RAILS_ROOT}/public/temp/#{session[:user_id]}/import_items"
      filename = "#{path}/#{file.original_filename}"
      @includespecials = params[:cb_IncludeSpecials]
      @headings = read_headings_from_file(file, path, filename)
      @source = params[:source]
      @search_column = params[:search_column]
      @file_path = filename
    end
  end

  def search_file_parsed
    @file_path = params[:file_path]
    @search_column = params[:search_column]
    @source = params[:source]
    @includespecials = params[:includespecials]

    file = File.new(@file_path, "r")
    while @headings_list.blank?
      line = file.gets
      unless line.blank?
        FasterCSV.parse(line) do |row|
          @headings_list = row
        end
      end
    end
    # Need a check to make sure file hasn't been modified or deleted
    grid = FasterCSV.read(@file_path)
    @prodnum = ""
    commaflag = false
    #@searchstring = @headings_list[0]
    for i in 0 .. @headings_list.size
      if @headings_list[.i] == @search_column
        for j in 1 .. grid.length-1
          if commaflag
            @prodnum = @prodnum + ","
          end
          @prodnum = @prodnum + grid[j][.i]
          commaflag = true
        end
      end
    end

    redirect_to(:controller => 'items', :action => 'search', :txt_ProductNumber => @prodnum, :sel_DB_Source => @source, :query => "true", :cb_IncludeSpecials => @includespecials)
  end

  def import_file
    @feed_types = ActiveSupport::OrderedHash["","", "Lawson", 1, "Cardinal", 3, "Lawson Specials", 2]
    @date = Date.today
  end
  
  def get_column_list
    
    tables_columns = ActiveSupport::OrderedHash.new
    for table in ActiveRecord::Base.connection.tables
      unless $IGNORED_TABLES.include?(table)
        model = model_from_table_name(table)
        unless model.nil?
          tables_columns[table] = model.column_names.delete_if { |x| $IGNORED_COLUMNS.include?(x) }
        end
      end
    end
    return tables_columns
  end
  
  def match_columns
    if params[:item].blank?
      flash[:notice] = "Invalid form entry"
      redirect_to :action => "import_file"
    elsif params[:item][:source].blank?
      flash[:notice] = "Please select the data source"
      redirect_to :action => "import_file"
    else
      file = params[:item][:datafeed]
      path = "#{RAILS_ROOT}/public/temp/#{session[:user_id]}/import_items"
      filename = "#{path}/#{file.original_filename}"
      @headings = read_headings_from_file(file, path, filename)
      @tables_columns = get_column_list()
      @source = params[:item][:source]
      @month = params[:date][:month]
      @year = params[:date][:year]
      @file_path = filename
      @defaults = parse_xml((@source == "3")? "../data/cardinal_defaults.xml" : "../data/lawson_defaults.xml")
    end
  end

  def match_pricelist_columns
    if params[:item].blank?
      flash[:notice] = "Invalid form entry"
      redirect_to :action => "pricelist_import"
    else
      file = params[:item][:pricelist]
      path = "#{RAILS_ROOT}/public/temp/#{session[:user_id]}/import_pricelist"
      filename = "#{path}/#{file.original_filename}"
      @headings = read_headings_from_file(file, path, filename)
      @tables_columns = get_column_list()
      @file_path = filename
      @defaults = parse_xml("../data/pricelist_defaults.xml")
    end
  end

  def read_headings_from_file(file, path, filepath)
    if File.exist?(filepath)
      FileUtils.rm_rf(filepath)
    end
    FileUtils.makedirs(path)
    File.open(filepath, "w") { |f| f.write(file.read.gsub("\r",""))}

    file = File.new(filepath, "r")
    while @headings_list.blank?
      line = file.gets
      unless line.blank?
        FasterCSV.parse(line) do |row|
          @headings_list = row
        end
      end
    end
    return @headings_list
  end
 
  def set_default_matches
    @tables_columns = get_column_list()
    @lawson_defaults = parse_xml("../data/lawson_defaults.xml")
    @cardinal_defaults = parse_xml("../data/cardinal_defaults.xml")
    @pricelist_defaults = parse_xml("../data/pricelist_defaults.xml")
  end
  
  def parse_xml(file)
    if File.exist?(file)
      tables_defaults = Hash.new
      root = REXML::Document.new(File.new(file)).root
      root.each_element_with_attribute( "table" ) { |default|
        tables_defaults["#{default.attributes["table"]}.#{default.attributes["column"]}"] = default.attributes["value"]
      }
      return tables_defaults
    end
  end
  
  def save_xml(file, params_array)
    unless params_array.blank?
      xml = ["<defaults>"]
      for param in params_array
        xml.push("\t<default table=\"#{param[0].split(".")[0].downcase}\" column=\"#{param[0].split(".")[1].downcase}\" value=\"#{param[1]}\" />")
      end
      xml.push("</defaults>")
      file = File.new(file, "w")
      for line in xml
        file.puts line
      end
      file.close
    end
  end
  
  def save_default_matches
    save_xml("../data/lawson_defaults.xml", params[:lawson])
    save_xml("../data/cardinal_defaults.xml", params[:cardinal])
    save_xml("../data/pricelist_defaults.xml", params[:pricelist])
    flash[:notice] = "Default values have been updated."
    redirect_to :action => "set_default_matches"
  end
  
  def commit_import
    @start_time = Time.now
    @import_successes = Hash.new
    @import_errors = Hash.new
    data_date = Date.civil(params[:date][:year].to_i, params[:date][:month].to_i, 1)
    file_path = params[:file_path]
    @items = Array.new
    # Need a check to make sure file hasn't been modified or deleted
    grid = FasterCSV.read(file_path)
    # First row is the column headings
    @headings = grid[0]
    headings_index = Hash.new
    @headings.each_with_index { |heading,index|
      headings_index[heading.to_s.gsub(/\s/,"_").gsub(/[^0-9a-zA-Z_]/, "")] = index.to_i
    }
    @tables_values_hash_template = Hash.new
    for table in ActiveRecord::Base.connection.tables
      unless $IGNORED_TABLES.include?(table)
        @tables_values_hash_template[table] = Hash.new
        @import_errors[table] = Hash.new
        @import_successes[table] = 0
      end
    end
    @tables_values_hash_template["items"][:data_date] = data_date
    @tables_values_hash_template["items"][:data_source] = params[:source]
    @rows_found = grid.length-1
    for i in 1..@rows_found
      tables_values_hash = Marshal.load(Marshal.dump(@tables_values_hash_template))
      params[:column_match].each { |key, value|
        unless value.blank?
          @table_column = value.split(".")
          cell_value = grid[.i][headings_index[key]]
          unless cell_value.blank?
            # Perform any specific table/column actions here
            case value.downcase
            when "items.vendor_catalog_number"
              tables_values_hash["items"]["vendor_catalog_number_no_dash"] = cell_value.gsub("-", "")
              tables_values_hash["items"]["vendor_catalog_number_no_zero"] = cell_value.gsub(/^0+/, "")
            when "items.manufacturer_catalog_number"
              tables_values_hash["items"]["manufacturer_catalog_number_no_dash"] = cell_value.gsub("-", "")
              tables_values_hash["items"]["manufacturer_catalog_number_no_zero"] = cell_value.gsub(/^0+/, "")
            end
            tables_values_hash[@table_column[0]][@table_column[1].to_sym] = cell_value
          end
        end
      }
      tables_values_hash.each { |table, values_hash| 
        unless table.downcase == "items"
          model = model_from_table_name(table)
          unless model.nil?
            object = model.new(values_hash)
            if object.save
              @import_successes[table] += 1
            else
              @import_errors[table][.i+1] = object.errors
            end
          end
        end
      }
      for column in Item.column_names
        if /^.*_id$/.match(column)
          table_name = column[0..-4].pluralize
          puts table_name
          model = model_from_table_name(table_name)
          unless tables_values_hash[table_name].blank?
            puts "hash_isnt_blank"
            result = model.find(:first, :conditions => tables_values_hash[table_name])
            unless result.blank?
              puts "result_found"
              tables_values_hash["items"][column] = result.id
            end
          end
        end
      end
      item = Item.new(tables_values_hash["items"])
      if item.save
        @import_successes["items"] += 1
      else
        @import_errors["items"][.i+1] = item.errors
      end
    end
    @end_time = Time.now
  end

  def commit_pricelist
    @start_time = Time.now
    @successes = 0
    @duplicates = 0
    @failures = 0
    @blank_values = 0
    file_path = params[:file_path]
    # Need a check to make sure file hasn't been modified or deleted
    grid = FasterCSV.read(file_path)
    # First row is the column headings
    @headings = grid[0]
    headings_index = Hash.new
    @headings.each_with_index { |heading,index|
      headings_index[heading.to_s.gsub(/\s/,"_").gsub(/[^0-9a-zA-Z_]/, "")] = index.to_i
    }
    @rows_found = grid.length - 1
    previous_conditions_string = ""
    previous_conditions = Hash.new
    for i in 1..@rows_found
      conditions = {"items" => Array.new}
      updates = Array.new
      params[:column_match].each { |key, value|
        @table_column = value.split(".")
        cell_value = grid[.i][headings_index[key]]
        unless cell_value.blank? || value.blank?
          if @table_column[1] == "unspsc" || @table_column[1] == "unspsc_description"
            updates.push("`#{@table_column[1]}` = #{(/^\d+$/.match(cell_value))? cell_value : "'#{cell_value}'"}")
          else
            if conditions[@table_column[0]].blank?
              conditions[@table_column[0]] = ["`#{@table_column[1]}` = #{(/^\d+$/.match(cell_value))? cell_value : "'#{cell_value}'"}"]
            else
              conditions[@table_column[0]].push("`#{@table_column[1]}` = #{(/^\d+$/.match(cell_value))? cell_value : "'#{cell_value}'"}")
            end
          end
        end
      }
      conditions.each { |table, conditions_array|
        unless table == "items"
          unless conditions_array == previous_conditions[table]
            model = model_from_table_name(table)
            result = model.find(:first, :conditions => [conditions_array.join(" AND ")])
            unless result.blank?
              conditions["items"].push("`#{table.singularize}_id` = #{result.id}" )
            end
            previous_conditions[table] = conditions_array
          end
        end
      }
      conditions_string = conditions["items"].join(" AND ")
      unless conditions_string == previous_conditions_string || conditions_string.blank?
        unless updates.blank?
          if Item.update_all(updates.join(", "), conditions_string)
            previous_conditions_string = conditions_string
            @successes += 1
          else
            @failures += 1
          end
        else
          @blank_values += 1
        end
      else
        @duplicates += 1
      end
    end
    @end_time = Time.now
  end

  # Method to return the class of the model from a given table name
  def model_from_table_name(table_name)
    unless table_name.blank?
      return eval( table_name.singularize.split( '_' ).collect { |word| word.capitalize }.join )
    else
      return nil
    end
  end

  def pricelist_import
  end

  def cross_reference_import
  end

  def commit_cross_references
    if params[:item].blank?
      flash[:notice] = "Invalid form entry"
      redirect_to :action => "cross_reference_import"
    else
      file = params[:item][:cross_references]
      path = "#{RAILS_ROOT}/public/temp/#{session[:user_id]}/import_cross_references"
      filename = "#{path}/#{file.original_filename}"
      if File.exist?(filename)
        FileUtils.rm_rf(filename)
      end
      FileUtils.makedirs(path)
      File.open(filename, "w") { |f| f.write(file.read.gsub("\r",""))}
      @bad_rows = Array.new
      @bad_column_pairs = Array.new
      grid = FasterCSV.read(filename)
      for row in grid
        if row.length % 2 == 0 && row.length > 2
          column_index = 0
          crosses = Array.new
          while column_index < row.length
            if !row[column_index].blank? && !row[column_index+1].blank?
              cross = Item.find(:first, :conditions => ["manufacturers.name = ? AND items.manufacturer_catalog_number = ?", row[column_index].to_s.strip, row[column_index+1].to_s.strip], :include => :manufacturer)
              crosses.push(cross) unless cross.blank?
            else
              @bad_column_pairs.push("#{row[column_index]},#{row[column_index+1]}") if !row[column_index].blank? || !row[column_index+1].blank?
            end
            column_index += 2
          end
          CrossReference.add_crosses(crosses) unless crosses.length < 2
        else
          @bad_rows.push(row.join(","))
        end
      end
    end
  end
  
  def search
    @query = nil
    @from_date = Date.today
    @to_date = Date.today
    if params["query"] == "true"
      @sqlstring = ""
      @joinstring = ""
      andflag = false
      vendorjoin = false
      mfgjoin = false
      agreejoin = false
      hospitaljoin = false
      #puts "Test thing: #{params[:commit]}"
      @submit_type = params[:commit]
      @usedate = params[:cb_UseDate]
      if @usedate == "on"
        @from_date = Date.civil(params[:date][:from_year].to_i, params[:date][:from_month].to_i, 1)
        @to_date = Date.civil(params[:date][:to_year].to_i, params[:date][:to_month].to_i, 1)
        @sqlstring = @sqlstring + "(items.data_date >= '#{@from_date}' AND items.data_date <= '#{@to_date}')"
        andflag = true
      end
      if not params[:txt_ProductNumber].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @prodnum = params[:txt_ProductNumber]
        @prodnum = @prodnum.gsub(/\s*,\s*0*/, ',')
        @prodnum = @prodnum.gsub(/^\s*0*|\s+$/, '')
        @currentsplits = @prodnum.split(",")

        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "vendor_catalog_number = '#{current}' or vendor_catalog_number_no_dash = '#{current}' or vendor_catalog_number_no_zero = '#{current}' or manufacturer_catalog_number = '#{current}' or manufacturer_catalog_number_no_dash = '#{current}' or manufacturer_catalog_number_no_zero = '#{current}' or cardinal_catalog_number = '#{current}'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
      end
      if not params[:txt_ProductDescription].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @proddesc = params[:txt_ProductDescription]
        @proddesc = @proddesc.gsub(/\s*,\s*/, ',')
        @proddesc = @proddesc.gsub(/^\s+|\s+$/, '')
        @currentsplits = @proddesc.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "items.description LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
      end
      if not params[:txt_ProductSubdesc].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @prodsubdesc = params[:txt_ProductSubdesc]
        @prodsubdesc = @prodsubdesc.gsub(/\s*,\s*/, ',')
        @prodsubdesc = @prodsubdesc.gsub(/^\s+|\s+$/, '')
        @currentsplits = @prodsubdesc.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "items.sub_description LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
      end
      if not params[:txt_UNSPSC].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @unspsc = params[:txt_UNSPSC]
        @unspsc = @unspsc.gsub(/\s*,\s*/, ',')
        @unspsc = @unspsc.gsub(/^\s+|\s+$/, '')
        @currentsplits = @unspsc.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "items.UNSPSC LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
      end
      if not params[:txt_VendorName].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @vendname = params[:txt_VendorName]
        @vendname = @vendname.gsub(/\s*,\s*/, ',')
        @vendname = @vendname.gsub(/^\s+|\s+$/, '')
        @currentsplits = @vendname.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "vendors.name LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
        if not vendorjoin
          @joinstring = @joinstring + "INNER JOIN vendors ON items.vendor_id = vendors.id "
          vendorjoin = true
        end
      end
      if not params[:txt_MfgName].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @mfgname = params[:txt_MfgName]
        @mfgname = @mfgname.gsub(/\s*,\s*/, ',')
        @mfgname = @mfgname.gsub(/^\s+|\s+$/, '')
        @currentsplits = @mfgname.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "manufacturers.name LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
        if not mfgjoin
          @joinstring = @joinstring + "INNER JOIN manufacturers ON items.manufacturer_id = manufacturers.id "
          mfgjoin = true
        end
      end
      if not params[:txt_ContractNumber].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @contractnum = params[:txt_ContractNumber]
        @contractnum = @contractnum.gsub(/\s*,\s*/, ',')
        @contractnum = @contractnum.gsub(/^\s+|\s+$/, '')
        @currentsplits = @contractnum.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "agreements.number LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
        if not agreejoin
          @joinstring = @joinstring + "INNER JOIN agreements ON items.agreement_id = agreements.id "
          agreejoin = true
        end
      end

      if not params[:txt_ContractDesc].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @contractdesc = params[:txt_ContractDesc]
        @contractdesc = @contractdesc.gsub(/\s*,\s*/, ',')
        @contractdesc = @contractdesc.gsub(/^\s+|\s+$/, '')
        @currentsplits = @contractdesc.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "agreements.description LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
        if not agreejoin
          @joinstring = @joinstring + "INNER JOIN agreements ON items.agreement_id = agreements.id "
          agreejoin = true
        end
      end

      if not params[:txt_ContractSubdesc].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @contractsub = params[:txt_ContractSubdesc]
        @contractsub = @contractsub.gsub(/\s*,\s*/, ',')
        @contractsub = @contractsub.gsub(/^\s+|\s+$/, '')
        @currentsplits = @contractsub.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "agreements.sub_description LIKE '%#{current}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
        if not agreejoin
          @joinstring = @joinstring + "INNER JOIN agreements ON items.agreement_id = agreements.id "
          agreejoin = true
        end
      end

      if not params[:txt_MO].blank?
        if andflag
          @sqlstring = @sqlstring + " AND "
        end
        @mo = params[:txt_MO]
        @mo = @mo.gsub(/\s*,\s*/, ',')
        @mo = @mo.gsub(/^\s+|\s+$/, '')
        @currentsplits = @mo.split(",")
        orflag = false
        currentstring = "("
        @currentsplits.each do |current|
          if orflag
            currentstring = currentstring + " or "
          end
          currentstring = currentstring + "hospitals.ministry_organization LIKE '%#{@mo}%'"
          orflag = true
        end
        currentstring = currentstring + ")"
        @sqlstring = @sqlstring + currentstring
        andflag = true
        if not hospitaljoin
          @joinstring = @joinstring + "INNER JOIN hospitals ON items.hospital_id = hospitals.id "
          hospitaljoin = true
        end
      end
      
      if andflag
        @sqlstring = @sqlstring + " AND "
      end
      @dbsource = params[:sel_DB_Source]
      @includespecials = params[:cb_IncludeSpecials]
      if @dbsource == "Lawson"
        if @includespecials == "on"
          @sqlstring = @sqlstring + "(items.data_source = 1 or items.data_source = 2)"
        else
          @sqlstring = @sqlstring + "(items.data_source = 1)"
        end
      else
        @sqlstring = @sqlstring + "(items.data_source = 3)"
      end


      if @sqlstring != ""
        @query = Item.paginate( :page => params[:page], :joins=> @joinstring, :conditions => @sqlstring, :include => [:hospital, :agreement, :vendor, :manufacturer, :category, :sub_category])
      else
        @query = Item.paginate( :page => params[:page],:include => [:hospital, :agreement, :vendor, :manufacturer, :category, :sub_category])
      end
      
      if @submit_type == "Export Results"
        if @sqlstring != ""
          @query2 = Item.find(:all, :joins=> @joinstring, :conditions => @sqlstring, :include => [:hospital, :agreement, :vendor, :manufacturer, :category, :sub_category])
        else
          @query2 = Item.find(:all, :include => [:hospital, :agreement, :vendor, :manufacturer, :category, :sub_category])
        end

        file = "search_results.csv"
        path = "#{RAILS_ROOT}/public/temp/#{session[:user_id]}/export_items"
        filename = "#{path}/#{file}"

        if File.exist?(filename)
          FileUtils.rm_rf(filename)
        end

        FileUtils.makedirs(path)
        FasterCSV.open(filename, "w") do |csv|
          linearray = ["Hospital","Ministry Organization","Agreement","Vendor","Manufacturer","Category","Sub Category","Description","Sub Description","Purchase UOM","Cost Per UOM","UOM Breakdowns","Units Per Package","Quantity","Purchase Price","ISS Account","ISS Account Description","UNSPSC","UNSPSC Description","Data Source","Vendor Catalog Number","Manufacturer Catalog Number","Cardinal Catalog Number","Data Date"]
          csv << linearray
          @query2.each do |item|
            linearray = Array.new

            unless item.hospital.blank?
              linearray.push(item.hospital.name)
            else
              linearray.push("")
            end

            unless item.hospital.blank?
              linearray.push(item.hospital.ministry_organization)
            else
              linearray.push("")
            end

            unless item.agreement.blank?
              linearray.push(item.agreement.number)
            else
              linearray.push("")
            end

            unless item.vendor.blank?
              linearray.push(item.vendor.name)
            else
              linearray.push("")
            end

            unless item.manufacturer.blank?
              linearray.push(item.manufacturer.name)
            else
              linearray.push("")
            end

            unless item.category.blank?
              linearray.push(item.category.name)
            else
              linearray.push("")
            end

            unless item.sub_category.blank?
              linearray.push(item.sub_category.name)
            else
              linearray.push("")
            end
            linearray.push(item.description)
            linearray.push(item.sub_description)
            linearray.push(item.purchase_uom)
            linearray.push(item.cost_per_uom)
            breakdowns = ""

            for uom_conversion in item.uom_conversions
              unless breakdowns == ""
                breakdowns += "  "
              end
              breakdowns += "#{uom_conversion.quantity_per_package} #{uom_conversion.single_unit_label} / #{uom_conversion.package}"
              if uom_conversion.package.upcase == item.purchase_uom.upcase
                unit_per_package = uom_conversion.quantity_per_package
              end
            end
            linearray.push(breakdowns)
            linearray.push(unit_per_package)
            linearray.push(item.quantity)
            linearray.push(item.purchase_price)
            linearray.push(item.iss_account)
            linearray.push(item.iss_account_description)
            linearray.push(item.unspsc)
            linearray.push(item.unspsc_description)
            linearray.push($DATA_SOURCES[.item.data_source-1])
            linearray.push(item.vendor_catalog_number)
            linearray.push(item.manufacturer_catalog_number)
            linearray.push(item.cardinal_catalog_number)
            linearray.push(item.data_date)
            csv << linearray
          end
        end
        send_file filename
        #puts "We did an export."
      end
      
    end
  end

  def delete_data
    @month = params[:date][:before_month].to_i
    @year = params[:date][:before_year].to_i

    if ((@year == (Date.today.year - 1)) and (@month > Date.today.month))
      flash[:notice] = "Cannot delete data less than a year old."
      redirect_to :action => "delete_old_data"
    else
      @delete_before_date = Date.civil(@year, @month, 1)
      delete_condition = "data_date < '#{@delete_before_date}'"
      
      @records_deleted = Item.count(:conditions => delete_condition)

      if @records_deleted == 1
        Item.destroy_all(delete_condition)
        @heading = "Success!"
        @message = "#{@records_deleted} item older than #{@delete_before_date} has been deleted."
      elsif @records_deleted == 0
        flash[:notice] = "No items older than the specified date were found."
        redirect_to :action => "delete_old_data"
      else
        Item.destroy_all(delete_condition)
        @heading = "Success!"
        @message = "#{@records_deleted} items older than #{@delete_before_date} have been deleted."
      end
    end
  end

  def delete_old_data
    @max_date = Date.today.year - 1
  end

  # POST /uom_conversions
  # POST /uom_conversions.xml
  def create_uom
    @uom_conversion = UomConversion.new(params[:uom_conversion])
    new_uom = UomConversion.new
    if @uom_conversion.save
      @uom_conversions = UomConversion.find(:all, :conditions => {:product_number => params[:uom_conversion][:product_number]})
      render :partial => "uoms", :locals => {:uom_conversions => @uom_conversions, :new_uom_conversion => new_uom, :product_number => params[:uom_conversion][:product_number]}
    else
      error_count = @uom_conversion.errors.count
      error_message = "<div id='errorExplanation' class='errorExplanation'><h2>#{error_count} error#{(error_count > 1)? "s": ""} prohibited this uom conversion from being saved</h2><p>There were problems with the following fields:</p><ul><li>"
      error_message += @uom_conversion.errors.full_messages.join("</li><li>")
      error_message += "</li></ul></div>"
      render :text => error_message, :status => :unprocessable_entity
    end
  end

  def remove_uom
    @uom_conversion = UomConversion.find_by_id(params[:uom_id])
    product_number = @uom_conversion.product_number
    new_uom = UomConversion.new
    @uom_conversion.destroy
    @uom_conversions = UomConversion.find(:all, :conditions => {:product_number => product_number})

    render :partial => "uoms", :locals => {:uom_conversions => @uom_conversions, :new_uom_conversion => new_uom, :product_number => product_number}
  end

  def show_cross_references
    @item = Item.find_by_id(params[:id])
    @cross_references = @item.cross_references
    unless @cross_references.blank?
      @cross_references.insert(0, @item)
      render :partial => "items_table", :locals => {:ajax => true, :items => @cross_references}
    else
      render :text => "<h2>There are no cross references for that item.</h2>"
    end
  end
end