1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
class Import < ActiveRecord::Base
mount_uploader :file, ImportUploader
belongs_to :workbench
belongs_to :referential
belongs_to :parent, polymorphic: true
has_many :messages, class_name: "ImportMessage", dependent: :destroy
has_many :resources, class_name: "ImportResource", dependent: :destroy
has_many :children, foreign_key: :parent_id, class_name: "Import", dependent: :destroy
scope :where_started_at_in, ->(period_range) do
where('started_at BETWEEN :begin AND :end', begin: period_range.begin, end: period_range.end)
end
extend Enumerize
enumerize :status, in: %w(new pending successful warning failed running aborted canceled), scope: true, default: :new
validates :name, presence: true
validates :file, presence: true
validates_presence_of :workbench, :creator
validates_format_of :file, with: %r{\.zip\z}i, message: I18n.t('activerecord.errors.models.import.attributes.file.wrong_file_extension')
before_create :initialize_fields
def self.model_name
ActiveModel::Name.new Import, Import, "Import"
end
def children_succeedeed
children.with_status(:successful, :warning).count
end
def self.launched_statuses
%w(new pending)
end
def self.failed_statuses
%w(failed aborted canceled)
end
def self.finished_statuses
%w(successful failed warning aborted canceled)
end
def notify_parent
parent.child_change
update(notified_parent_at: DateTime.now)
end
def child_change
return if self.class.finished_statuses.include?(status)
update_status
update_referentials
end
def update_status
status =
if children.where(status: self.class.failed_statuses).count > 0
'failed'
elsif children.where(status: "warning").count > 0
'warning'
elsif children.where(status: "successful").count == children.count
'successful'
end
attributes = {
current_step: children.count,
status: status
}
if self.class.finished_statuses.include?(status)
attributes[:ended_at] = Time.now
end
update attributes
end
def update_referentials
return unless self.class.finished_statuses.include?(status)
children.each do |import|
import.referential.update(ready: true) if import.referential
end
end
private
def initialize_fields
self.token_download = SecureRandom.urlsafe_base64
end
end
|