| 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
 | class LineReferentialSync < ApplicationModel
  include AASM
  belongs_to :line_referential
  has_many :line_referential_sync_messages, :dependent => :destroy
  after_commit :perform_sync, :on => :create
  validate :multiple_process_validation, :on => :create
  scope :pending, -> { where(status: [:new, :pending]) }
  private
  def perform_sync
    create_sync_message :info, :new
    LineReferentialSyncWorker.perform_async(self.id)
  end
  # There can be only one instance running
  def multiple_process_validation
    if self.class.where(status: [:new, :pending], line_referential_id: line_referential_id).count > 0
      errors.add(:base, :multiple_process)
    end
  end
  aasm column: :status do
    state :new, :initial => true
    state :pending
    state :successful
    state :failed
    event :run, after: :log_pending do
      transitions :from => :new, :to => :pending
    end
    event :successful, after: :log_successful do
      transitions :from => [:pending, :failed], :to => :successful
    end
    event :failed, after: :log_failed do
      transitions :from => [:new, :pending], :to => :failed
    end
  end
  def create_sync_message criticity, key, message_attributes = {}
    params = {
      criticity: criticity,
      message_key: key,
      message_attributes: message_attributes
    }
    line_referential_sync_messages.create params
  end
  def log_pending
    update_attribute(:started_at, Time.now)
    create_sync_message :info, :pending
  end
  def log_successful message_attributes
    update_attribute(:ended_at, Time.now)
    create_sync_message :info, :successful, message_attributes
  end
  def log_failed message_attributes
    update_attribute(:ended_at, Time.now)
    create_sync_message :error, :failed, message_attributes
  end
end
 |