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 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 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. '%Y/%m/%d',
  31. '%d.%m.%Y',
  32. '%d-%m-%Y'
  33. ]
  34. def self.menu_item
  35. nil
  36. end
  37. def self.layout
  38. 'base'
  39. end
  40. def self.authorized?(user)
  41. user.admin?
  42. end
  43. def initialize(*args)
  44. super
  45. self.settings ||= {}
  46. end
  47. def file=(arg)
  48. return unless arg.present? && arg.size > 0
  49. self.filename = generate_filename
  50. Redmine::Utils.save_upload(arg, filepath)
  51. end
  52. def set_default_settings(options={})
  53. separator = lu(user, :general_csv_separator)
  54. if file_exists?
  55. begin
  56. content = File.read(filepath, 256)
  57. separator = [',', ';'].sort_by {|sep| content.count(sep) }.last
  58. rescue => e
  59. end
  60. end
  61. wrapper = '"'
  62. encoding = lu(user, :general_csv_encoding)
  63. date_format = lu(user, "date.formats.default", :default => "foo")
  64. date_format = DATE_FORMATS.first unless DATE_FORMATS.include?(date_format)
  65. self.settings.merge!(
  66. 'separator' => separator,
  67. 'wrapper' => wrapper,
  68. 'encoding' => encoding,
  69. 'date_format' => date_format,
  70. 'notifications' => '0'
  71. )
  72. if options.key?(:project_id) && !options[:project_id].blank?
  73. # Do not fail if project doesn't exist
  74. begin
  75. project = Project.find(options[:project_id])
  76. self.settings.merge!('mapping' => {'project_id' => project.id})
  77. rescue; end
  78. end
  79. end
  80. def to_param
  81. filename
  82. end
  83. # Returns the full path of the file to import
  84. # It is stored in tmp/imports with a random hex as filename
  85. def filepath
  86. if filename.present? && /\A[0-9a-f]+\z/.match?(filename)
  87. File.join(Rails.root, "tmp", "imports", filename)
  88. else
  89. nil
  90. end
  91. end
  92. # Returns true if the file to import exists
  93. def file_exists?
  94. filepath.present? && File.exists?(filepath)
  95. end
  96. # Returns the headers as an array that
  97. # can be used for select options
  98. def columns_options(default=nil)
  99. i = -1
  100. headers.map {|h| [h, i+=1]}
  101. end
  102. # Parses the file to import and updates the total number of items
  103. def parse_file
  104. count = 0
  105. read_items {|row, i| count=i}
  106. update_attribute :total_items, count
  107. count
  108. end
  109. # Reads the items to import and yields the given block for each item
  110. def read_items
  111. i = 0
  112. headers = true
  113. read_rows do |row|
  114. if i == 0 && headers
  115. headers = false
  116. next
  117. end
  118. i+= 1
  119. yield row, i if block_given?
  120. end
  121. end
  122. # Returns the count first rows of the file (including headers)
  123. def first_rows(count=4)
  124. rows = []
  125. read_rows do |row|
  126. rows << row
  127. break if rows.size >= count
  128. end
  129. rows
  130. end
  131. # Returns an array of headers
  132. def headers
  133. first_rows(1).first || []
  134. end
  135. # Returns the mapping options
  136. def mapping
  137. settings['mapping'] || {}
  138. end
  139. # Adds a callback that will be called after the item at given position is imported
  140. def add_callback(position, name, *args)
  141. settings['callbacks'] ||= {}
  142. settings['callbacks'][position] ||= []
  143. settings['callbacks'][position] << [name, args]
  144. save!
  145. end
  146. # Executes the callbacks for the given object
  147. def do_callbacks(position, object)
  148. if callbacks = (settings['callbacks'] || {}).delete(position)
  149. callbacks.each do |name, args|
  150. send "#{name}_callback", object, *args
  151. end
  152. save!
  153. end
  154. end
  155. # Imports items and returns the position of the last processed item
  156. def run(options={})
  157. max_items = options[:max_items]
  158. max_time = options[:max_time]
  159. current = 0
  160. imported = 0
  161. resume_after = items.maximum(:position) || 0
  162. interrupted = false
  163. started_on = Time.now
  164. read_items do |row, position|
  165. if (max_items && imported >= max_items) || (max_time && Time.now >= started_on + max_time)
  166. interrupted = true
  167. break
  168. end
  169. if position > resume_after
  170. item = items.build
  171. item.position = position
  172. item.unique_id = row_value(row, 'unique_id') if use_unique_id?
  173. if object = build_object(row, item)
  174. if object.save
  175. item.obj_id = object.id
  176. else
  177. item.message = object.errors.full_messages.join("\n")
  178. end
  179. end
  180. item.save!
  181. imported += 1
  182. do_callbacks(use_unique_id? ? item.unique_id : item.position, object)
  183. end
  184. current = position
  185. end
  186. if imported == 0 || interrupted == false
  187. if total_items.nil?
  188. update_attribute :total_items, current
  189. end
  190. update_attribute :finished, true
  191. remove_file
  192. end
  193. current
  194. end
  195. def unsaved_items
  196. items.where(:obj_id => nil)
  197. end
  198. def saved_items
  199. items.where("obj_id IS NOT NULL")
  200. end
  201. private
  202. def read_rows
  203. return unless file_exists?
  204. csv_options = {:headers => false}
  205. csv_options[:encoding] = settings['encoding'].to_s.presence || 'UTF-8'
  206. csv_options[:encoding] = 'bom|UTF-8' if csv_options[:encoding] == 'UTF-8'
  207. separator = settings['separator'].to_s
  208. csv_options[:col_sep] = separator if separator.size == 1
  209. wrapper = settings['wrapper'].to_s
  210. csv_options[:quote_char] = wrapper if wrapper.size == 1
  211. CSV.foreach(filepath, **csv_options) do |row|
  212. yield row if block_given?
  213. end
  214. end
  215. def row_value(row, key)
  216. if index = mapping[key].presence
  217. row[index.to_i].presence
  218. end
  219. end
  220. def row_date(row, key)
  221. if s = row_value(row, key)
  222. format = settings['date_format']
  223. format = DATE_FORMATS.first unless DATE_FORMATS.include?(format)
  224. Date.strptime(s, format) rescue s
  225. end
  226. end
  227. # Builds a record for the given row and returns it
  228. # To be implemented by subclasses
  229. def build_object(row)
  230. end
  231. # Generates a filename used to store the import file
  232. def generate_filename
  233. Redmine::Utils.random_hex(16)
  234. end
  235. # Deletes the import file
  236. def remove_file
  237. if file_exists?
  238. begin
  239. File.delete filepath
  240. rescue => e
  241. logger.error "Unable to delete file #{filepath}: #{e.message}" if logger
  242. end
  243. end
  244. end
  245. # Returns true if value is a string that represents a true value
  246. def yes?(value)
  247. value == lu(user, :general_text_yes) || value == '1'
  248. end
  249. def use_unique_id?
  250. mapping['unique_id'].present?
  251. end
  252. end