2022-08-08 16:06:00 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module LabelTemplates
|
|
|
|
class RepositoryRowService
|
|
|
|
class UnsupportedKeyError < StandardError; end
|
|
|
|
|
|
|
|
class ColumnNotFoundError < StandardError; end
|
|
|
|
|
2022-09-22 21:06:36 +08:00
|
|
|
class LogoNotFoundError < StandardError; end
|
|
|
|
|
|
|
|
MAX_PRINTABLE_ITEM_NAME_LENGTH = 64
|
|
|
|
|
|
|
|
def initialize(label_template, repository_row, print_mode=false)
|
2022-08-08 16:06:00 +08:00
|
|
|
@label_template = label_template
|
|
|
|
@repository_row = repository_row
|
2022-09-22 21:06:36 +08:00
|
|
|
@print_mode = print_mode
|
|
|
|
@repository_columns = RepositoryColumn.where(repository_id: @repository_row.repository_id).pluck(:name)
|
2022-08-08 16:06:00 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def render
|
|
|
|
keys = @label_template.content.scan(/(?<=\{\{).*?(?=\}\})/).uniq
|
|
|
|
|
|
|
|
keys.reduce(@label_template.content.dup) do |rendered_content, key|
|
|
|
|
rendered_content.gsub!(/\{\{#{key}\}\}/, fetch_value(key))
|
2022-09-22 21:06:36 +08:00
|
|
|
rescue ColumnNotFoundError, LogoNotFoundError => e
|
|
|
|
raise e unless @print_mode
|
|
|
|
|
|
|
|
rendered_content
|
2022-08-08 16:06:00 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def fetch_value(key)
|
|
|
|
case key
|
2022-09-22 21:06:36 +08:00
|
|
|
when /^c_(.*)/
|
2022-08-08 16:06:00 +08:00
|
|
|
name = Regexp.last_match(1)
|
2022-09-22 21:06:36 +08:00
|
|
|
unless @repository_columns.include?(name)
|
|
|
|
raise ColumnNotFoundError, I18n.t('label_templates.repository_row.errors.column_not_found')
|
|
|
|
end
|
|
|
|
|
|
|
|
return '' unless @print_mode
|
|
|
|
|
2022-08-08 16:06:00 +08:00
|
|
|
repository_cell = @repository_row.repository_cells.joins(:repository_column).find_by(
|
|
|
|
repository_columns: { name: name }
|
|
|
|
)
|
2022-09-22 21:06:36 +08:00
|
|
|
repository_cell ? repository_cell.value.formatted : ''
|
2022-08-08 16:06:00 +08:00
|
|
|
when 'ITEM_ID'
|
|
|
|
@repository_row.code
|
|
|
|
when 'NAME'
|
2022-09-22 21:06:36 +08:00
|
|
|
@repository_row.name.truncate(MAX_PRINTABLE_ITEM_NAME_LENGTH)
|
2022-08-08 16:06:00 +08:00
|
|
|
when 'ADDED_BY'
|
|
|
|
@repository_row.created_by.full_name
|
|
|
|
when 'ADDED_ON'
|
|
|
|
@repository_row.created_at.to_s
|
2022-09-22 21:06:36 +08:00
|
|
|
when 'LOGO'
|
|
|
|
logo
|
2022-08-08 16:06:00 +08:00
|
|
|
else
|
2022-09-22 21:06:36 +08:00
|
|
|
raise ColumnNotFoundError, I18n.t('label_templates.repository_row.errors.column_not_found')
|
2022-08-08 16:06:00 +08:00
|
|
|
end
|
|
|
|
end
|
2022-09-22 21:06:36 +08:00
|
|
|
|
|
|
|
def logo
|
|
|
|
raise LogoNotFoundError, I18n.t('label_templates.repository_row.errors.logo_not_supported')
|
|
|
|
end
|
2022-08-08 16:06:00 +08:00
|
|
|
end
|
|
|
|
end
|