Files
docuseal/lib/submissions/generate_result_attachments.rb
T

825 lines
30 KiB
Ruby
Raw Normal View History

2023-05-21 17:59:36 +03:00
# frozen_string_literal: true
module Submissions
module GenerateResultAttachments
2023-06-18 16:30:35 +03:00
FONT_SIZE = 11
2024-02-16 11:34:30 +02:00
FONT_PATH = '/fonts/GoNotoKurrent-Regular.ttf'
2025-03-05 12:12:16 +02:00
FONT_BOLD_PATH = '/fonts/GoNotoKurrent-Bold.ttf'
2023-08-25 00:27:56 +03:00
FONT_NAME = if File.exist?(FONT_PATH)
FONT_PATH
else
'Helvetica'
end
2023-05-28 23:20:48 +03:00
2025-05-19 14:06:37 +03:00
ICO_REGEXP = %r{\Aimage/(?:x-icon|vnd\.microsoft\.icon)\z}
BMP_REGEXP = %r{\Aimage/(?:bmp|x-bmp|x-ms-bmp)\z}
2025-03-05 12:12:16 +02:00
FONT_BOLD_NAME = if File.exist?(FONT_BOLD_PATH)
FONT_BOLD_PATH
else
'Helvetica'
end
FONT_ITALIC_NAME = 'Helvetica'
FONT_BOLD_ITALIC_NAME = 'Helvetica'
FONT_VARIANS = {
none: FONT_NAME,
bold: FONT_BOLD_NAME,
italic: FONT_ITALIC_NAME,
bold_italic: FONT_BOLD_ITALIC_NAME
}.freeze
2024-10-31 14:25:37 +02:00
SIGN_REASON = 'Signed by %<name>s with DocuSeal.com'
2023-06-24 12:27:34 +03:00
2024-01-15 01:45:26 +02:00
RTL_REGEXP = TextUtils::RTL_REGEXP
2024-01-07 14:19:21 +02:00
2023-06-24 22:50:12 +03:00
TEXT_LEFT_MARGIN = 1
TEXT_TOP_MARGIN = 1
2024-04-22 19:10:58 +03:00
MAX_PAGE_ROTATE = 20
2023-06-24 22:50:12 +03:00
2023-06-22 01:31:39 +03:00
A4_SIZE = [595, 842].freeze
2024-08-05 10:45:05 +03:00
TESTING_FOOTER = 'Testing Document - NOT LEGALLY BINDING'
2025-02-12 19:49:50 +02:00
DEFAULT_FONTS = %w[Times Helvetica Courier].freeze
2025-03-05 12:12:16 +02:00
FONTS_LINE_HEIGHT = {
'Times' => 1.4,
'Helvetica' => 1.4,
'Courier' => 1.6
}.freeze
2024-08-05 10:45:05 +03:00
2024-03-15 19:02:17 +02:00
MISSING_GLYPH_REPLACE = {
'▪' => '-',
2024-02-13 22:23:42 +02:00
'✔️' => 'V',
2024-03-15 19:02:17 +02:00
'✔' => 'V',
2024-06-04 11:48:02 +03:00
'✓' => 'V',
2024-03-15 19:02:17 +02:00
'✅' => 'V'
}.freeze
MISSING_GLYPH_REPLACE_TYPE1 = {
'▪' => :bullet,
'✔️' => :V,
'✔' => :V,
2024-06-04 11:48:02 +03:00
'✓' => :V,
2024-03-15 19:02:17 +02:00
'✅' => :V
2024-02-08 21:11:31 +02:00
}.freeze
2023-05-21 17:59:36 +03:00
module_function
2023-05-28 23:20:48 +03:00
# rubocop:disable Metrics
2023-06-13 00:29:07 +03:00
def call(submitter)
2024-12-01 00:10:07 +02:00
return generate_detached_signature_attachments(submitter) if detached_signature?(submitter)
2024-05-25 20:57:36 +03:00
pdfs_index = generate_pdfs(submitter)
2023-06-27 00:57:29 +03:00
2023-06-13 00:29:07 +03:00
template = submitter.submission.template
2024-05-25 20:57:36 +03:00
account = submitter.account
pkcs = Accounts.load_signing_pkcs(account)
tsa_url = Accounts.load_timeserver_url(account)
image_pdfs = []
original_documents = template.documents.preload(:blob)
result_attachments =
2024-12-07 01:35:59 +02:00
submitter.submission.template_schema.filter_map do |item|
2024-05-25 20:57:36 +03:00
pdf = pdfs_index[item['attachment_uuid']]
2024-12-07 01:35:59 +02:00
next if pdf.nil?
2024-08-14 19:30:16 +03:00
if original_documents.find { |a| a.uuid == item['attachment_uuid'] }.image?
pdf = normalize_image_pdf(pdf)
2024-05-25 20:57:36 +03:00
2024-08-14 19:30:16 +03:00
image_pdfs << pdf
end
2024-05-25 20:57:36 +03:00
2024-08-14 19:30:16 +03:00
build_pdf_attachment(pdf:, submitter:, pkcs:, tsa_url:,
uuid: item['attachment_uuid'],
name: item['name'])
2024-05-25 20:57:36 +03:00
end
2024-11-05 22:54:59 +02:00
return ApplicationRecord.no_touching { result_attachments.map { |e| e.tap(&:save!) } } if image_pdfs.size < 2
2024-05-25 20:57:36 +03:00
images_pdf =
image_pdfs.each_with_object(HexaPDF::Document.new) do |pdf, doc|
pdf.pages.each { |page| doc.pages << doc.import(page) }
end
2024-08-14 19:30:16 +03:00
images_pdf = normalize_image_pdf(images_pdf)
2024-05-25 20:57:36 +03:00
images_pdf_attachment =
build_pdf_attachment(
pdf: images_pdf,
submitter:,
tsa_url:,
pkcs:,
uuid: images_pdf_uuid(original_documents.select(&:image?)),
name: template.name
)
2024-11-05 22:54:59 +02:00
ApplicationRecord.no_touching do
(result_attachments + [images_pdf_attachment]).map { |e| e.tap(&:save!) }
end
2024-05-25 20:57:36 +03:00
end
def generate_pdfs(submitter)
2024-10-15 19:16:09 +03:00
configs = submitter.account.account_configs.where(key: [AccountConfig::FLATTEN_RESULT_PDF_KEY,
AccountConfig::WITH_SIGNATURE_ID])
2024-07-24 20:55:35 +03:00
2024-10-15 19:16:09 +03:00
with_signature_id = configs.find { |c| c.key == AccountConfig::WITH_SIGNATURE_ID }&.value == true
is_flatten = configs.find { |c| c.key == AccountConfig::FLATTEN_RESULT_PDF_KEY }&.value != false
2023-05-28 23:20:48 +03:00
2024-10-15 19:16:09 +03:00
pdfs_index = build_pdfs_index(submitter.submission, submitter:, flatten: is_flatten)
2023-05-28 23:20:48 +03:00
2024-08-05 10:45:05 +03:00
if with_signature_id || submitter.account.testing?
2024-07-24 20:55:35 +03:00
pdfs_index.each_value do |pdf|
next if pdf.trailer.info[:DocumentID].present?
2024-08-27 23:36:44 +03:00
font = pdf.fonts.add(FONT_NAME)
2024-08-05 10:45:05 +03:00
document_id = Digest::MD5.hexdigest(submitter.submission.slug).upcase
pdf.trailer.info[:DocumentID] = document_id
2024-07-24 20:55:35 +03:00
pdf.pages.each do |page|
font_size = (([page.box.width, page.box.height].min / A4_SIZE[0].to_f) * 9).to_i
cnv = page.canvas(type: :overlay)
2024-08-05 10:45:05 +03:00
text =
if submitter.account.testing?
if with_signature_id
"#{TESTING_FOOTER} | ID: #{document_id}"
else
TESTING_FOOTER
end
else
2024-10-01 20:06:37 +03:00
"#{I18n.t('document_id', locale: submitter.account.locale)}: #{document_id}"
2024-08-05 10:45:05 +03:00
end
2024-08-27 23:36:44 +03:00
text = HexaPDF::Layout::TextFragment.create(
text, font:, font_size:, underlays: [
lambda do |canv, box|
canv.fill_color('white').rectangle(-1, 0, box.width + 2, box.height).fill
end
]
)
HexaPDF::Layout::TextLayouter.new(font:, font_size:)
.fit([text], page.box.width, page.box.height)
.draw(cnv, 1, font_size * 1.37)
2024-07-24 20:55:35 +03:00
end
end
end
2024-10-15 19:16:09 +03:00
fill_submitter_fields(submitter, submitter.account, pdfs_index, with_signature_id:, is_flatten:)
end
2024-12-23 22:58:24 +02:00
def fill_submitter_fields(submitter, account, pdfs_index, with_signature_id:, is_flatten:, with_headings: nil)
2024-10-15 19:16:09 +03:00
cell_layouter = HexaPDF::Layout::TextLayouter.new(text_valign: :center, text_align: :center)
attachments_data_cache = {}
2024-10-15 20:49:19 +03:00
return pdfs_index if submitter.submission.template_fields.blank?
2024-12-23 22:58:24 +02:00
with_headings = find_last_submitter(submitter.submission, submitter:).blank? if with_headings.nil?
2023-07-26 09:58:50 +03:00
submitter.submission.template_fields.each do |field|
2024-12-23 22:58:24 +02:00
next if field['type'] == 'heading' && !with_headings
next if field['submitter_uuid'] != submitter.uuid && field['type'] != 'heading'
2023-06-16 23:39:55 +03:00
2023-05-28 23:20:48 +03:00
field.fetch('areas', []).each do |area|
pdf = pdfs_index[area['attachment_uuid']]
2023-12-11 18:28:24 +02:00
next if pdf.nil?
2023-05-28 23:20:48 +03:00
page = pdf.pages[area['page']]
2023-12-11 18:28:24 +02:00
next if page.nil?
2023-09-06 17:27:54 +03:00
page.rotate(0, flatten: true) if page[:Rotate] != 0
2023-05-28 23:20:48 +03:00
2023-08-12 12:34:02 +03:00
page[:Annots] ||= []
2024-04-01 13:09:35 +03:00
page[:Annots] = page[:Annots].try(:reject) do |e|
next if e.is_a?(Integer)
2023-12-06 16:04:28 +02:00
e.present? && e[:A] && e[:A][:URI].to_s.starts_with?('file:///docuseal_field')
2024-04-01 13:09:35 +03:00
end || page[:Annots]
2023-08-12 12:34:02 +03:00
2023-05-28 23:20:48 +03:00
width = page.box.width
height = page.box.height
2024-06-20 16:14:18 +03:00
preferences_font_size = field.dig('preferences', 'font_size').then { |num| num.present? ? num.to_i : nil }
font_size = preferences_font_size
font_size ||= (([page.box.width, page.box.height].min / A4_SIZE[0].to_f) * FONT_SIZE).to_i
2023-05-28 23:20:48 +03:00
2025-05-02 12:33:27 +03:00
fill_color = field.dig('preferences', 'color').to_s.delete_prefix('#').presence
2024-11-10 12:48:53 +02:00
2025-02-12 19:49:50 +02:00
font_name = field.dig('preferences', 'font')
2025-03-05 12:12:16 +02:00
font_variant = (field.dig('preferences', 'font_type').presence || 'none').to_sym
2025-02-12 19:49:50 +02:00
font_name = FONT_NAME unless font_name.in?(DEFAULT_FONTS)
2025-03-05 12:12:16 +02:00
if font_variant != :none && font_name == FONT_NAME
font_name = FONT_VARIANS[font_variant]
font_variant = nil unless font_name.in?(DEFAULT_FONTS)
end
2025-04-10 13:22:10 +03:00
font = pdf.fonts.add(font_name, variant: font_variant, custom_encoding: font_name.in?(DEFAULT_FONTS))
2024-07-16 13:18:03 +03:00
2023-06-13 00:29:07 +03:00
value = submitter.values[field['uuid']]
2024-12-23 22:58:24 +02:00
value = field['default_value'] if field['type'] == 'heading'
2023-05-28 23:20:48 +03:00
2024-03-17 19:06:00 +02:00
text_align = field.dig('preferences', 'align').to_s.to_sym.presence ||
(value.to_s.match?(RTL_REGEXP) ? :right : :left)
2025-01-24 23:08:44 +02:00
text_valign = (field.dig('preferences', 'valign').to_s.presence || 'center').to_sym
layouter = HexaPDF::Layout::TextLayouter.new(text_valign:, text_align:, font:, font_size:)
2024-01-07 14:19:21 +02:00
2023-07-08 20:51:37 +03:00
next if Array.wrap(value).compact_blank.blank?
2024-04-22 21:34:55 +03:00
if is_flatten
begin
page.flatten_annotations
rescue StandardError => e
Rollbar.error(e) if defined?(Rollbar)
end
2024-03-27 18:24:41 +02:00
end
2023-05-28 23:20:48 +03:00
canvas = page.canvas(type: :overlay)
2023-08-25 00:27:56 +03:00
canvas.font(FONT_NAME, size: font_size)
2023-05-28 23:20:48 +03:00
case field['type']
2024-08-06 00:19:33 +03:00
when ->(type) { type == 'signature' && (with_signature_id || field.dig('preferences', 'reason_field_uuid')) }
2024-07-24 20:55:35 +03:00
attachment = submitter.attachments.find { |a| a.uuid == value }
2025-05-19 14:06:37 +03:00
image = load_vips_image(attachment, attachments_data_cache).autorot
2024-07-24 20:55:35 +03:00
2024-08-06 00:19:33 +03:00
reason_value = submitter.values[field.dig('preferences', 'reason_field_uuid')].presence
2024-07-24 20:55:35 +03:00
reason_string =
2024-10-01 20:06:37 +03:00
I18n.with_locale(submitter.account.locale) do
2024-12-12 19:16:24 +02:00
"#{reason_value ? "#{I18n.t('reason')}: " : ''}#{reason_value || I18n.t('digitally_signed_by')} " \
2024-10-01 20:06:37 +03:00
"#{submitter.name}#{submitter.email.present? ? " <#{submitter.email}>" : ''}\n" \
"#{I18n.l(attachment.created_at.in_time_zone(submitter.account.timezone), format: :long)} " \
"#{TimeUtils.timezone_abbr(submitter.account.timezone, attachment.created_at)}"
end
2024-07-24 20:55:35 +03:00
reason_text = HexaPDF::Layout::TextFragment.create(reason_string,
font:,
font_size: (font_size / 1.8).to_i)
2025-05-18 09:44:55 +03:00
if area['h']&.positive? && (area['w'].to_f / area['h']) > 6
area_x = area['x'] * width
area_y = area['y'] * height
area_w = area['w'] * width
area_h = area['h'] * height
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
half_width = area_w / 2.0
scale = [half_width / image.width, area_h / image.height].min
image_width = image.width * scale
image_height = image.height * scale
image_x = area_x + ((half_width - image_width) / 2.0)
image_y = height - area_y - image_height
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
io = StringIO.new(image.resize([scale * 4, 1].select(&:positive?).min).write_to_buffer('.png'))
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
canvas.image(io, at: [image_x, image_y], width: image_width, height: image_height)
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
id_string = "ID: #{attachment.uuid}".upcase
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
while true
text = HexaPDF::Layout::TextFragment.create(id_string,
font:,
font_size: (font_size / 1.8).to_i)
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
result = layouter.fit([text], half_width, (font_size / 1.8) / 0.65)
2024-07-24 20:55:35 +03:00
2025-05-18 09:44:55 +03:00
break if result.status == :success
id_string = "#{id_string.delete_suffix('...')[0..-2]}..."
break if id_string.length < 8
end
text_x = area_x + half_width
text_y = height - area_y
reason_result = layouter.fit([reason_text], half_width, height)
layouter.fit([text], half_width, (font_size / 1.8) / 0.65)
.draw(canvas, text_x + TEXT_LEFT_MARGIN, text_y)
layouter.fit([reason_text], half_width, reason_result.lines.sum(&:height))
.draw(canvas, text_x + TEXT_LEFT_MARGIN, text_y - TEXT_TOP_MARGIN - result.lines.sum(&:height))
else
id_string = "ID: #{attachment.uuid}".upcase
loop do
text = HexaPDF::Layout::TextFragment.create(id_string,
font:,
font_size: (font_size / 1.8).to_i)
result = layouter.fit([text], area['w'] * width, (font_size / 1.8) / 0.65)
break if result.status == :success
id_string = "#{id_string.delete_suffix('...')[0..-2]}..."
break if id_string.length < 8
end
reason_result = layouter.fit([reason_text], area['w'] * width, height)
text_height = result.lines.sum(&:height) + reason_result.lines.sum(&:height)
image_height = (area['h'] * height) - text_height
image_height = (area['h'] * height) / 2 if image_height < (area['h'] * height) / 2
scale = [(area['w'] * width) / image.width, image_height / image.height].min
io = StringIO.new(image.resize([scale * 4, 1].select(&:positive?).min).write_to_buffer('.png'))
layouter.fit([text], area['w'] * width, (font_size / 1.8) / 0.65)
.draw(canvas, (area['x'] * width) + TEXT_LEFT_MARGIN,
height - (area['y'] * height) - TEXT_TOP_MARGIN - image_height)
layouter.fit([reason_text], area['w'] * width, reason_result.lines.sum(&:height))
.draw(canvas, (area['x'] * width) + TEXT_LEFT_MARGIN,
height - (area['y'] * height) - TEXT_TOP_MARGIN -
result.lines.sum(&:height) - image_height)
canvas.image(
io,
at: [
(area['x'] * width) + (area['w'] * width / 2) - ((image.width * scale) / 2),
height - (area['y'] * height) - (image.height * scale / 2) - (image_height / 2)
],
width: image.width * scale,
height: image.height * scale
)
end
2023-12-22 13:33:53 +02:00
when 'image', 'signature', 'initials', 'stamp'
2023-06-14 02:08:26 +03:00
attachment = submitter.attachments.find { |a| a.uuid == value }
2023-06-24 22:50:12 +03:00
2024-11-01 18:39:03 +02:00
image =
begin
2025-05-19 14:06:37 +03:00
load_vips_image(attachment, attachments_data_cache).autorot
2024-11-01 18:39:03 +02:00
rescue Vips::Error
next unless attachment.content_type.starts_with?('image/')
next if attachment.byte_size.zero?
raise
end
2023-05-21 17:59:36 +03:00
2023-07-07 21:29:38 +03:00
scale = [(area['w'] * width) / image.width,
(area['h'] * height) / image.height].min
2023-07-07 00:54:32 +03:00
2023-12-06 19:01:30 +02:00
io = StringIO.new(image.resize([scale * 4, 1].select(&:positive?).min).write_to_buffer('.png'))
2023-07-07 00:54:32 +03:00
2023-06-18 16:30:35 +03:00
canvas.image(
io,
at: [
2023-07-07 21:29:38 +03:00
(area['x'] * width) + (area['w'] * width / 2) - ((image.width * scale) / 2),
height - (area['y'] * height) - (image.height * scale / 2) - (area['h'] * height / 2)
2023-06-18 16:30:35 +03:00
],
2023-07-07 21:29:38 +03:00
width: image.width * scale,
height: image.height * scale
2023-06-18 16:30:35 +03:00
)
2023-12-14 21:22:26 +02:00
when 'file', 'payment'
2023-06-18 16:30:35 +03:00
items = Array.wrap(value).each_with_object([]) do |uuid, acc|
2023-06-14 02:08:26 +03:00
attachment = submitter.attachments.find { |a| a.uuid == uuid }
2023-05-21 17:59:36 +03:00
2023-08-09 09:33:14 +03:00
acc << HexaPDF::Layout::InlineBox.create(width: font_size, height: font_size,
2023-06-18 16:30:35 +03:00
margin: [0, 1, -2, 0]) do |cv, box|
cv.image(PdfIcons.paperclip_io, at: [0, 0], width: box.content_width)
end
2024-07-16 13:18:03 +03:00
acc << HexaPDF::Layout::TextFragment.create("#{attachment.filename}\n", font:,
2023-08-09 09:33:14 +03:00
font_size:)
2023-05-28 23:20:48 +03:00
end
2023-06-18 16:30:35 +03:00
lines = layouter.fit(items, area['w'] * width, height).lines
box_height = lines.sum(&:height)
height_diff = [0, box_height - (area['h'] * height)].max
lines.each_with_index.reduce(0) do |acc, (line, index)|
next acc unless line.items.first.is_a?(HexaPDF::Layout::InlineBox)
attachment_uuid = Array.wrap(value)[acc]
attachment = submitter.attachments.find { |a| a.uuid == attachment_uuid }
2024-04-23 20:09:39 +03:00
next_index = lines[(index + 1)..].index { |l| l.items.first.is_a?(HexaPDF::Layout::InlineBox) }
next_index += index if next_index
next_index ||= lines.size - 1
diff = ((area['h'] * height) / 2) - (lines.sum(&:height) / 2)
2023-06-18 16:30:35 +03:00
page[:Annots] << pdf.add(
{
Type: :Annot, Subtype: :Link,
Rect: [
2023-06-24 22:50:12 +03:00
(area['x'] * width) + TEXT_LEFT_MARGIN,
2024-04-23 20:09:39 +03:00
height - (area['y'] * height) - lines[...index].sum(&:height) +
height_diff - (height_diff.zero? ? diff : 0),
2023-06-24 22:50:12 +03:00
(area['x'] * width) + (area['w'] * width) + TEXT_LEFT_MARGIN,
2024-04-23 20:09:39 +03:00
height - (area['y'] * height) - lines[..next_index].sum(&:height) +
height_diff - (height_diff.zero? ? diff : 0)
2023-06-18 16:30:35 +03:00
],
A: { Type: :Action, S: :URI,
2024-02-18 11:26:30 +02:00
URI: ActiveStorage::Blob.proxy_url(attachment.blob) }
2023-06-18 16:30:35 +03:00
}
)
acc + 1
2023-05-21 17:59:36 +03:00
end
2023-06-18 16:30:35 +03:00
layouter.fit(items, area['w'] * width, height_diff.positive? ? box_height : area['h'] * height)
2023-06-24 22:50:12 +03:00
.draw(canvas, (area['x'] * width) + TEXT_LEFT_MARGIN,
height - (area['y'] * height) + height_diff - TEXT_TOP_MARGIN)
2023-11-14 01:30:00 +02:00
when ->(type) { type == 'checkbox' || (type.in?(%w[multiple radio]) && area['option_uuid'].present?) }
if field['type'].in?(%w[multiple radio])
option = field['options']&.find { |o| o['uuid'] == area['option_uuid'] }
2024-10-02 17:57:31 +03:00
option_name = option['value'].presence
option_name ||= "#{I18n.t('option', locale: account.locale)} #{field['options'].index(option) + 1}"
2024-03-26 19:26:03 +02:00
value = Array.wrap(value).include?(option_name)
2023-11-14 01:30:00 +02:00
end
2023-06-18 16:30:35 +03:00
next unless value == true
scale = [(area['w'] * width) / PdfIcons::WIDTH, (area['h'] * height) / PdfIcons::HEIGHT].min
canvas.image(
PdfIcons.check_io,
at: [
(area['x'] * width) + (area['w'] * width / 2) - (PdfIcons::WIDTH * scale / 2),
height - (area['y'] * height) - (area['h'] * height / 2) - (PdfIcons::HEIGHT * scale / 2)
],
width: PdfIcons::WIDTH * scale,
height: PdfIcons::HEIGHT * scale
)
2024-09-21 12:49:52 +03:00
when ->(type) { type == 'cells' && !area['cell_w'].to_f.zero? }
2023-06-27 00:57:29 +03:00
cell_width = area['cell_w'] * width
2025-03-04 00:12:56 +02:00
if (mask = field.dig('preferences', 'mask').presence)
value = TextUtils.mask_value(value, mask)
end
2025-03-03 00:14:14 +02:00
2024-12-13 00:24:29 +02:00
chars = TextUtils.maybe_rtl_reverse(value).chars
chars = chars.reverse if field.dig('preferences', 'align') == 'right'
chars.each_with_index do |char, index|
2024-07-07 09:57:33 +03:00
next if char.blank?
2024-07-16 13:18:03 +03:00
text = HexaPDF::Layout::TextFragment.create(char, font:,
2024-11-10 12:48:53 +02:00
fill_color:,
2023-08-09 09:33:14 +03:00
font_size:)
2023-06-27 00:57:29 +03:00
2024-07-07 09:57:33 +03:00
line_height = layouter.fit([text], cell_width, height).lines.first.height
if preferences_font_size.blank? && line_height > (area['h'] * height)
text = HexaPDF::Layout::TextFragment.create(char,
2024-07-16 13:18:03 +03:00
font:,
2024-11-10 12:48:53 +02:00
fill_color:,
2024-07-07 09:57:33 +03:00
font_size: (font_size / 1.4).to_i)
line_height = layouter.fit([text], cell_width, height).lines.first.height
end
if preferences_font_size.blank? && line_height > (area['h'] * height)
text = HexaPDF::Layout::TextFragment.create(char,
2024-07-16 13:18:03 +03:00
font:,
2024-11-10 12:48:53 +02:00
fill_color:,
2024-07-07 09:57:33 +03:00
font_size: (font_size / 1.9).to_i)
line_height = layouter.fit([text], cell_width, height).lines.first.height
end
2024-12-13 00:24:29 +02:00
x =
if field.dig('preferences', 'align') == 'right'
((area['x'] + area['w']) * width) - (cell_width * (index + 1))
else
(area['x'] * width) + (cell_width * index)
end
2024-07-07 09:57:33 +03:00
cell_layouter.fit([text], cell_width, [line_height, area['h'] * height].max)
2024-12-13 00:24:29 +02:00
.draw(canvas, x, height - (area['y'] * height))
2023-06-27 00:57:29 +03:00
end
2023-05-28 23:20:48 +03:00
else
2023-12-17 23:32:05 +02:00
if field['type'] == 'date'
value = TimeUtils.format_date_string(value, field.dig('preferences', 'format'), account.locale)
end
2023-06-18 16:30:35 +03:00
2024-05-12 11:12:07 +03:00
value = NumberUtils.format_number(value, field.dig('preferences', 'format')) if field['type'] == 'number'
2024-01-15 01:45:26 +02:00
value = TextUtils.maybe_rtl_reverse(Array.wrap(value).join(', '))
2024-01-07 14:19:21 +02:00
2025-03-04 00:12:56 +02:00
if (mask = field.dig('preferences', 'mask').presence)
value = TextUtils.mask_value(value, mask)
end
2025-03-03 00:14:14 +02:00
2025-02-05 18:17:55 +02:00
text_params = { font:, fill_color:, font_size: }
2025-03-05 12:12:16 +02:00
text_params[:line_height] = text_params[:font_size] * (FONTS_LINE_HEIGHT[font_name] || 1)
2025-02-05 18:17:55 +02:00
text = HexaPDF::Layout::TextFragment.create(value, **text_params)
2023-06-18 16:30:35 +03:00
lines = layouter.fit([text], area['w'] * width, height).lines
box_height = lines.sum(&:height)
2023-11-07 11:36:11 +02:00
2024-06-20 16:14:18 +03:00
if preferences_font_size.blank? && box_height > (area['h'] * height) + 1
2025-02-05 18:17:55 +02:00
text_params[:font_size] = (font_size / 1.4).to_i
2025-03-05 12:12:16 +02:00
text_params[:line_height] = text_params[:font_size] * (FONTS_LINE_HEIGHT[font_name] || 1)
2025-02-05 18:17:55 +02:00
text = HexaPDF::Layout::TextFragment.create(value, **text_params)
2023-11-07 11:36:11 +02:00
2024-03-17 19:06:00 +02:00
lines = layouter.fit([text], field['type'].in?(%w[date number]) ? width : area['w'] * width, height).lines
2023-11-07 11:36:11 +02:00
box_height = lines.sum(&:height)
end
2024-06-20 16:14:18 +03:00
if preferences_font_size.blank? && box_height > (area['h'] * height) + 1
2025-02-05 18:17:55 +02:00
text_params[:font_size] = (font_size / 1.9).to_i
2025-03-05 12:12:16 +02:00
text_params[:line_height] = text_params[:font_size] * (FONTS_LINE_HEIGHT[font_name] || 1)
2025-02-05 18:17:55 +02:00
text = HexaPDF::Layout::TextFragment.create(value, **text_params)
2024-03-20 16:52:47 +02:00
lines = layouter.fit([text], field['type'].in?(%w[date number]) ? width : area['w'] * width, height).lines
box_height = lines.sum(&:height)
end
2023-06-18 16:30:35 +03:00
height_diff = [0, box_height - (area['h'] * height)].max
2024-03-17 19:06:00 +02:00
right_align_x_adjustment =
if field['type'].in?(%w[date number]) && text_align != :left
(width - (area['w'] * width)) / (text_align == :center ? 2.0 : 1)
else
0
end
2025-01-24 23:08:44 +02:00
align_y_diff =
if text_valign == :top
0
elsif text_valign == :bottom
height_diff + TEXT_TOP_MARGIN
else
height_diff / 2
end
2024-03-17 19:06:00 +02:00
layouter.fit([text], field['type'].in?(%w[date number]) ? width : area['w'] * width,
height_diff.positive? ? box_height : area['h'] * height)
.draw(canvas, (area['x'] * width) - right_align_x_adjustment + TEXT_LEFT_MARGIN,
2025-01-24 23:08:44 +02:00
height - (area['y'] * height) + align_y_diff - TEXT_TOP_MARGIN)
2023-05-21 17:59:36 +03:00
end
2023-05-28 23:20:48 +03:00
end
end
2024-10-15 20:49:19 +03:00
pdfs_index
2023-05-21 17:59:36 +03:00
end
2023-06-13 00:29:07 +03:00
2024-03-15 13:03:10 +02:00
def build_pdf_attachment(pdf:, submitter:, pkcs:, tsa_url:, uuid:, name:)
2023-06-22 01:31:39 +03:00
io = StringIO.new
2023-10-11 21:05:42 +03:00
pdf.trailer.info[:Creator] = info_creator
2023-06-24 12:27:34 +03:00
2023-12-21 23:29:06 +02:00
sign_reason = fetch_sign_reason(submitter)
2023-12-02 18:14:33 +02:00
2024-12-17 23:25:04 +02:00
if sign_reason && pkcs
2023-12-21 23:29:06 +02:00
sign_params = {
reason: sign_reason,
2024-09-26 10:58:32 +03:00
**build_signing_params(submitter, pkcs, tsa_url)
2023-12-21 23:29:06 +02:00
}
2024-10-10 09:04:25 +03:00
pdf.pages.first[:Annots] = [] unless pdf.pages.first[:Annots].respond_to?(:<<)
2024-03-15 12:13:32 +02:00
begin
pdf.sign(io, write_options: { validate: false }, **sign_params)
rescue HexaPDF::MalformedPDFError => e
Rollbar.error(e) if defined?(Rollbar)
pdf.sign(io, write_options: { validate: false, incremental: false }, **sign_params)
end
2024-07-09 13:15:51 +03:00
maybe_enable_ltv(io, sign_params)
2023-12-21 23:29:06 +02:00
else
2024-03-15 12:13:32 +02:00
begin
pdf.write(io, incremental: true, validate: false)
rescue HexaPDF::MalformedPDFError => e
Rollbar.error(e) if defined?(Rollbar)
pdf.write(io, incremental: false, validate: false)
end
2023-12-21 23:29:06 +02:00
end
2023-06-22 01:31:39 +03:00
2024-03-15 13:03:10 +02:00
ActiveStorage::Attachment.new(
2024-07-09 13:15:51 +03:00
blob: ActiveStorage::Blob.create_and_upload!(io: io.tap(&:rewind), filename: "#{name}.pdf"),
2024-02-25 16:25:04 +02:00
metadata: { original_uuid: uuid,
analyzed: true,
sha256: Base64.urlsafe_encode64(Digest::SHA256.digest(io.string)) },
2023-06-22 01:31:39 +03:00
name: 'documents',
record: submitter
)
end
2024-07-09 13:15:51 +03:00
# rubocop:enable Metrics
def maybe_enable_ltv(io, _sign_params)
io
end
2023-06-22 01:31:39 +03:00
2024-09-26 10:58:32 +03:00
def build_signing_params(_submitter, pkcs, tsa_url)
2024-05-01 23:40:09 +03:00
params = {
certificate: pkcs.certificate,
key: pkcs.key,
certificate_chain: pkcs.ca_certs || []
}
if tsa_url
params[:timestamp_handler] = Submissions::TimestampHandler.new(tsa_url:)
2024-05-08 09:38:16 +03:00
params[:signature_size] = 20_000
2024-05-01 23:40:09 +03:00
end
params
end
2023-06-22 01:31:39 +03:00
def images_pdf_uuid(attachments)
Digest::UUID.uuid_v5(Digest::UUID::OID_NAMESPACE, attachments.map(&:uuid).sort.join(':'))
end
2024-10-15 19:16:09 +03:00
def build_pdfs_index(submission, submitter: nil, flatten: true)
latest_submitter = find_last_submitter(submission, submitter:)
2023-07-01 13:16:07 +03:00
Submissions::EnsureResultGenerated.call(latest_submitter) if latest_submitter
2023-06-13 00:29:07 +03:00
2023-06-22 01:31:39 +03:00
documents = latest_submitter&.documents&.preload(:blob).to_a.presence
2024-10-15 19:16:09 +03:00
documents ||= submission.template_schema_documents.preload(:blob)
2023-06-13 00:29:07 +03:00
2024-12-07 01:35:59 +02:00
attachment_uuids = Submissions.filtered_conditions_schema(submission).pluck('attachment_uuid')
attachments_index = documents.index_by { |a| a.metadata['original_uuid'] || a.uuid }
attachment_uuids.each_with_object({}) do |uuid, acc|
attachment = attachments_index[uuid]
attachment ||= submission.template_schema_documents.preload(:blob).find { |a| a.uuid == uuid }
next unless attachment
2023-06-22 01:31:39 +03:00
pdf =
if attachment.image?
build_pdf_from_image(attachment)
else
HexaPDF::Document.new(io: StringIO.new(attachment.download))
end
2024-04-22 19:10:58 +03:00
pdf = maybe_rotate_pdf(pdf)
2024-12-07 01:35:59 +02:00
maybe_flatten_pdf(pdf) if flatten
2024-02-08 17:59:40 +02:00
2024-03-15 19:02:17 +02:00
pdf.config['font.on_missing_glyph'] = method(:on_missing_glyph).to_proc
2024-12-07 01:35:59 +02:00
acc[uuid] = pdf
2023-06-13 00:29:07 +03:00
end
end
2023-06-22 01:31:39 +03:00
2024-12-07 01:35:59 +02:00
def maybe_flatten_pdf(pdf)
pdf.acro_form.create_appearances(force: true) if pdf.acro_form && pdf.acro_form[:NeedAppearances]
pdf.acro_form&.flatten
rescue HexaPDF::MissingGlyphError
nil
rescue StandardError => e
Rollbar.error(e) if defined?(Rollbar)
end
2024-04-22 19:10:58 +03:00
def maybe_rotate_pdf(pdf)
return pdf if pdf.pages.size > MAX_PAGE_ROTATE
is_rotated = pdf.pages.filter_map do |page|
page.rotate(0, flatten: true) if page[:Rotate] != 0
end.present?
return pdf unless is_rotated
io = StringIO.new
pdf.write(io, incremental: false, validate: false)
HexaPDF::Document.new(io:)
rescue StandardError => e
Rollbar.error(e) if defined?(Rollbar)
pdf
end
2024-03-15 19:02:17 +02:00
def on_missing_glyph(character, font_wrapper)
2024-07-25 15:11:01 +03:00
Rails.logger.info("Missing glyph: #{character}") if character.present? && defined?(Rollbar)
2024-03-15 19:02:17 +02:00
replace_with =
if font_wrapper.font_type == :Type1
MISSING_GLYPH_REPLACE_TYPE1[character] || :space
else
(MISSING_GLYPH_REPLACE[character] || ' ').bytes.first - 29
end
font_wrapper.custom_glyph(replace_with, character)
end
2024-10-15 19:16:09 +03:00
def find_last_submitter(submission, submitter: nil)
submission.submitters
.select(&:completed_at?)
.select { |e| submitter.nil? ? true : e.id != submitter.id && e.completed_at <= submitter.completed_at }
.max_by(&:completed_at)
2024-02-25 16:25:04 +02:00
end
2023-06-22 01:31:39 +03:00
def build_pdf_from_image(attachment)
pdf = HexaPDF::Document.new
2024-05-02 13:40:01 +03:00
2023-06-22 01:31:39 +03:00
page = pdf.pages.add
scale = [A4_SIZE.first / attachment.metadata['width'].to_f,
A4_SIZE.last / attachment.metadata['height'].to_f].min
page.box.width = attachment.metadata['width'] * scale
page.box.height = attachment.metadata['height'] * scale
page.canvas.image(
2023-07-07 00:54:32 +03:00
StringIO.new(attachment.preview_images.first.download),
2023-06-22 01:31:39 +03:00
at: [0, 0],
width: page.box.width,
height: page.box.height
)
pdf
end
2023-06-29 02:04:17 +03:00
2024-08-14 19:30:16 +03:00
def normalize_image_pdf(pdf)
io = StringIO.new
pdf.write(io)
io.rewind
HexaPDF::Document.new(io:)
end
2023-12-21 23:29:06 +02:00
def sign_reason(name)
format(SIGN_REASON, name:)
end
2024-05-16 23:18:48 +03:00
def single_sign_reason(submitter)
signers = submitter.submission.submitters.sort_by(&:completed_at).map { |s| s.email || s.name || s.phone }
format(SIGN_REASON, name: signers.reverse.join(', '))
2023-12-21 23:29:06 +02:00
end
def fetch_sign_reason(submitter)
reason_name = submitter.email || submitter.name || submitter.phone
2023-12-25 13:16:52 +02:00
config =
if Docuseal.multitenant?
AccountConfig.where(account: submitter.account, key: AccountConfig::ESIGNING_PREFERENCE_KEY)
2024-05-16 23:18:48 +03:00
.first_or_initialize(value: 'single')
2023-12-25 13:16:52 +02:00
else
AccountConfig.where(key: AccountConfig::ESIGNING_PREFERENCE_KEY)
2024-05-16 23:18:48 +03:00
.first_or_initialize(value: 'single')
2023-12-25 13:16:52 +02:00
end
return sign_reason(reason_name) if config.value == 'multiple'
2023-12-21 23:29:06 +02:00
2024-05-16 23:18:48 +03:00
if !submitter.submission.submitters.exists?(completed_at: nil) &&
submitter.completed_at == submitter.submission.submitters.maximum(:completed_at)
return single_sign_reason(submitter)
end
2023-12-21 23:29:06 +02:00
nil
2023-10-11 21:05:42 +03:00
end
def info_creator
2023-12-30 01:19:46 +02:00
"#{Docuseal.product_name} (#{Docuseal::PRODUCT_URL})"
2023-10-11 21:05:42 +03:00
end
2024-12-01 00:10:07 +02:00
def detached_signature?(_submitter)
false
end
def generate_detached_signature_attachments(_submitter)
[]
end
2025-05-19 14:06:37 +03:00
def load_vips_image(attachment, cache = {})
cache[attachment.uuid] ||= attachment.download
data = cache[attachment.uuid]
if ICO_REGEXP.match?(attachment.content_type)
LoadIco.call(data)
elsif BMP_REGEXP.match?(attachment.content_type)
LoadBmp.call(data)
else
Vips::Image.new_from_buffer(data, '')
end
end
def h
Rails.application.routes.url_helpers
end
2023-05-21 17:59:36 +03:00
end
end