You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

import.rb 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2017 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'csv'
  19. class Import < ActiveRecord::Base
  20. has_many :items, :class_name => 'ImportItem', :dependent => :delete_all
  21. belongs_to :user
  22. serialize :settings
  23. before_destroy :remove_file
  24. validates_presence_of :filename, :user_id
  25. validates_length_of :filename, :maximum => 255
  26. DATE_FORMATS = [
  27. '%Y-%m-%d',
  28. '%d/%m/%Y',
  29. '%m/%d/%Y',
  30. '%d.%m.%Y',
  31. '%d-%m-%Y'
  32. ]
  33. def self.menu_item
  34. nil
  35. end
  36. def self.layout
  37. 'base'
  38. end
  39. def self.authorized?(user)
  40. user.admin?
  41. end
  42. def initialize(*args)
  43. super
  44. self.settings ||= {}
  45. end
  46. def file=(arg)
  47. return unless arg.present? && arg.size > 0
  48. self.filename = generate_filename
  49. Redmine::Utils.save_upload(arg, filepath)
  50. end
  51. def set_default_settings
  52. separator = lu(user, :general_csv_separator)
  53. if file_exists?
  54. begin
  55. content = File.read(filepath, 256)
  56. separator = [',', ';'].sort_by {|sep| content.count(sep) }.last
  57. rescue => e
  58. end
  59. end
  60. wrapper = '"'
  61. encoding = lu(user, :general_csv_encoding)
  62. date_format = lu(user, "date.formats.default", :default => "foo")
  63. date_format = DATE_FORMATS.first unless DATE_FORMATS.include?(date_format)
  64. self.settings.merge!(
  65. 'separator' => separator,
  66. 'wrapper' => wrapper,
  67. 'encoding' => encoding,
  68. 'date_format' => date_format,
  69. 'notifications' => '0'
  70. )
  71. end
  72. def to_param
  73. filename
  74. end
  75. # Returns the full path of the file to import
  76. # It is stored in tmp/imports with a random hex as filename
  77. def filepath
  78. if filename.present? && /\A[0-9a-f]+\z/.match?(filename)
  79. File.join(Rails.root, "tmp", "imports", filename)
  80. else
  81. nil
  82. end
  83. end
  84. # Returns true if the file to import exists
  85. def file_exists?
  86. filepath.present? && File.exists?(filepath)
  87. end
  88. # Returns the headers as an array that
  89. # can be used for select options
  90. def columns_options(default=nil)
  91. i = -1
  92. headers.map {|h| [h, i+=1]}
  93. end
  94. # Parses the file to import and updates the total number of items
  95. def parse_file
  96. count = 0
  97. read_items {|row, i| count=i}
  98. update_attribute :total_items, count
  99. count
  100. end
  101. # Reads the items to import and yields the given block for each item
  102. def read_items
  103. i = 0
  104. headers = true
  105. read_rows do |row|
  106. if i == 0 && headers
  107. headers = false
  108. next
  109. end
  110. i+= 1
  111. yield row, i if block_given?
  112. end
  113. end
  114. # Returns the count first rows of the file (including headers)
  115. def first_rows(count=4)
  116. rows = []
  117. read_rows do |row|
  118. rows << row
  119. break if rows.size >= count
  120. end
  121. rows
  122. end
  123. # Returns an array of headers
  124. def headers
  125. first_rows(1).first || []
  126. end
  127. # Returns the mapping options
  128. def mapping
  129. settings['mapping'] || {}
  130. end
  131. # Adds a callback that will be called after the item at given position is imported
  132. def add_callback(position, name, *args)
  133. settings['callbacks'] ||= {}
  134. settings['callbacks'][position.to_i] ||= []
  135. settings['callbacks'][position.to_i] << [name, args]
  136. save!
  137. end
  138. # Executes the callbacks for the given object
  139. def do_callbacks(position, object)
  140. if callbacks = (settings['callbacks'] || {}).delete(position)
  141. callbacks.each do |name, args|
  142. send "#{name}_callback", object, *args
  143. end
  144. save!
  145. end
  146. end
  147. # Imports items and returns the position of the last processed item
  148. def run(options={})
  149. max_items = options[:max_items]
  150. max_time = options[:max_time]
  151. current = 0
  152. imported = 0
  153. resume_after = items.maximum(:position) || 0
  154. interrupted = false
  155. started_on = Time.now
  156. read_items do |row, position|
  157. if (max_items && imported >= max_items) || (max_time && Time.now >= started_on + max_time)
  158. interrupted = true
  159. break
  160. end
  161. if position > resume_after
  162. item = items.build
  163. item.position = position
  164. if object = build_object(row, item)
  165. if object.save
  166. item.obj_id = object.id
  167. else
  168. item.message = object.errors.full_messages.join("\n")
  169. end
  170. end
  171. item.save!
  172. imported += 1
  173. do_callbacks(item.position, object)
  174. end
  175. current = position
  176. end
  177. if imported == 0 || interrupted == false
  178. if total_items.nil?
  179. update_attribute :total_items, current
  180. end
  181. update_attribute :finished, true
  182. remove_file
  183. end
  184. current
  185. end
  186. def unsaved_items
  187. items.where(:obj_id => nil)
  188. end
  189. def saved_items
  190. items.where("obj_id IS NOT NULL")
  191. end
  192. private
  193. def read_rows
  194. return unless file_exists?
  195. csv_options = {:headers => false}
  196. csv_options[:encoding] = settings['encoding'].to_s.presence || 'UTF-8'
  197. csv_options[:encoding] = 'bom|UTF-8' if csv_options[:encoding] == 'UTF-8'
  198. separator = settings['separator'].to_s
  199. csv_options[:col_sep] = separator if separator.size == 1
  200. wrapper = settings['wrapper'].to_s
  201. csv_options[:quote_char] = wrapper if wrapper.size == 1
  202. CSV.foreach(filepath, csv_options) do |row|
  203. yield row if block_given?
  204. end
  205. end
  206. def row_value(row, key)
  207. if index = mapping[key].presence
  208. row[index.to_i].presence
  209. end
  210. end
  211. def row_date(row, key)
  212. if s = row_value(row, key)
  213. format = settings['date_format']
  214. format = DATE_FORMATS.first unless DATE_FORMATS.include?(format)
  215. Date.strptime(s, format) rescue s
  216. end
  217. end
  218. # Builds a record for the given row and returns it
  219. # To be implemented by subclasses
  220. def build_object(row)
  221. end
  222. # Generates a filename used to store the import file
  223. def generate_filename
  224. Redmine::Utils.random_hex(16)
  225. end
  226. # Deletes the import file
  227. def remove_file
  228. if file_exists?
  229. begin
  230. File.delete filepath
  231. rescue => e
  232. logger.error "Unable to delete file #{filepath}: #{e.message}" if logger
  233. end
  234. end
  235. end
  236. # Returns true if value is a string that represents a true value
  237. def yes?(value)
  238. value == lu(user, :general_text_yes) || value == '1'
  239. end
  240. end