1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-12-12 23:09:03 +01:00
fab-manager/app/services/footprint_service.rb

50 lines
2.0 KiB
Ruby
Raw Normal View History

2019-09-18 15:09:14 +02:00
# frozen_string_literal: true
# Provides helper methods to compute footprints
class FootprintService
# Compute the footprint
2020-07-21 19:25:21 +02:00
# @param klass Invoice|InvoiceItem|HistoryValue
2019-09-18 15:09:14 +02:00
# @param item an instance of the provided class
# @param sort the items in database by the provided criterion, to find the previous one
def self.compute_footprint(klass, item, sort_on = 'id')
2020-07-21 19:25:21 +02:00
Checksum.text(FootprintService.footprint_data(klass, item, sort_on))
end
# Return the original data string used to compute the footprint
# @param klass Invoice|InvoiceItem|HistoryValue
# @param item an instance of the provided class
# @param sort the items in database by the provided criterion, to find the previous one
def self.footprint_data(klass, item, sort_on = 'id')
raise TypeError unless item.is_a? klass
2019-09-18 15:09:14 +02:00
previous = klass.where("#{sort_on} < ?", item[sort_on])
2020-07-21 19:25:21 +02:00
.order("#{sort_on} DESC")
.limit(1)
2019-09-18 15:09:14 +02:00
2020-07-21 19:25:21 +02:00
columns = FootprintService.footprint_columns(klass)
2019-09-18 15:09:14 +02:00
2020-07-21 19:25:21 +02:00
"#{columns.map { |c| item[c] }.join}#{previous.first ? previous.first.footprint : ''}"
end
# Return an ordered array of the columns used in the footprint computation
# @param klass Invoice|InvoiceItem|HistoryValue
def self.footprint_columns(klass)
klass.columns.map(&:name).delete_if { |c| %w[footprint updated_at].include? c }
end
# Logs a debugging message to help finding why a footprint is invalid
# @param klass Invoice|InvoiceItem|HistoryValue
# @param item an instance of the provided class
def self.debug_footprint(klass, item)
columns = FootprintService.footprint_columns(klass)
current = FootprintService.footprint_data(klass, item)
saved = FootprintDebug.find_by(footprint: item.footprint, klass: klass)
puts "Debug footprint for #{klass} [ id: #{item.id} ]"
2020-07-21 19:25:21 +02:00
puts '-----------------------------------------'
puts "columns: [ #{columns.join(', ')} ]"
puts "current footprint: #{current}"
puts " saved footprint: #{saved&.data}"
puts '-----------------------------------------'
2019-09-18 15:09:14 +02:00
end
end