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.5KB

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