Class: Labimotion::ExportElement
- Inherits:
-
Object
- Object
- Labimotion::ExportElement
- Defined in:
- lib/labimotion/libs/export_element.rb
Constant Summary collapse
- TABLE_BLANK_WORDML =
'<w:p/>'- TABLE_BORDER =
'<w:tblBorders>' \ '<w:top w:val="single" w:sz="4" w:color="auto"/>' \ '<w:left w:val="single" w:sz="4" w:color="auto"/>' \ '<w:bottom w:val="single" w:sz="4" w:color="auto"/>' \ '<w:right w:val="single" w:sz="4" w:color="auto"/>' \ '<w:insideH w:val="single" w:sz="4" w:color="auto"/>' \ '<w:insideV w:val="single" w:sz="4" w:color="auto"/>' \ '</w:tblBorders>'
- DATETIME_RANGE_HEADERS =
['Start', 'Stop', 'Duration (calc)', 'Duration'].freeze
- DATETIME_RANGE_PRECISE_LABELS =
%w[year month day hour minute second].freeze
- DURATION_UNIT_LABELS =
{ 'd' => 'day', 'h' => 'hour', 'min' => 'minute', 's' => 'second' }.freeze
- TABLE_CELL_TEXT_RENDERERS =
{ Labimotion::FieldType::DRAG_SAMPLE => ->(_sf, c, ctx) { ctx.table_cell_sample_text(c['value'] || {}) }, Labimotion::FieldType::DRAG_MOLECULE => ->(_sf, c, ctx) { ctx.table_cell_molecule_text(c['value'] || {}) }, Labimotion::FieldType::DRAG_ELEMENT => ->(_sf, c, ctx) { ctx.table_cell_element_text(c['value'] || {}) }, Labimotion::FieldType::SELECT => ->(_sf, c, _ctx) { c['value'].to_s }, Labimotion::FieldType::SYSTEM_DEFINED => ->(sf, c, ctx) { ctx.table_cell_sysdef_text(sf, c) } }.freeze
- DOCX_COVER_MIMES =
The element's cover selection (chem-generic-ui#1050) rendered into the export: the stored
{source, id}references are resolved through the same helpers as the cover_image API, so the docx shows exactly what the element page shows. Only rasters Word renders reliably are embedded as originals; everything else falls back to the PNG thumbnail. %w[image/png image/jpeg image/gif image/bmp].freeze
- DOCX_COVER_EXT =
{ 'image/png' => '.png', 'image/jpeg' => '.jpg', 'image/gif' => '.gif', 'image/bmp' => '.bmp' }.freeze
- DOCX_COVER_MAX_W =
px-unit bounds of the rendered image (Sablon::Image::PX_TO_EMU scale): 1600 ≈ 13.3cm wide, 1100 ≈ 9.2cm tall
1600- DOCX_COVER_MAX_H =
1100
Instance Method Summary collapse
-
#apply_docx_cover_dimensions(image, data) ⇒ Object
Without dimensions the placeholder geometry of the template is kept, which distorts the aspect ratio — best effort, never fatal.
- #borrow_unit(higher, lower, base) ⇒ Object
- #build_cover_image(ref) ⇒ Object
- #build_cover_images ⇒ Object
- #build_datetime_range_wordml(field) ⇒ Object
- #build_field(layer, field) ⇒ Object
- #build_field_html(layer, field, cols) ⇒ Object
- #build_fields(layer) ⇒ Object
- #build_fields_html(layer) ⇒ Object
- #build_layers ⇒ Object
- #build_layers_html ⇒ Object
- #build_table_body_rows(sub_values, sub_fields, width, font_size) ⇒ Object
- #build_table_field(sub_val, sub_field) ⇒ Object
- #build_table_header_row(sub_fields, width, font_size) ⇒ Object
- #build_table_wordml(field) ⇒ Object
- #build_utc_from_parts(parts) ⇒ Object
- #build_wordml_cell(text, width, font_size, bold) ⇒ Object
- #close_cover_tempfiles ⇒ Object
- #compute_duration_calc(time_start, time_stop) ⇒ Object
- #cover_context ⇒ Object
- #cover_helpers ⇒ Object
- #datetime_range_parts_complete?(parts) ⇒ Boolean
- #datetime_range_values(by_col) ⇒ Object
- #datetime_range_wordml_table(values) ⇒ Object
- #docx_context ⇒ Object
- #docx_cover_caption(ref, att) ⇒ Object
- #docx_cover_original(att) ⇒ Object
- #docx_cover_payload(att) ⇒ Object
- #docx_cover_sablon_image(data, mime) ⇒ Object
- #duration_unit_label(value_system, value) ⇒ Object
- #format_duration_calc(_duration_calc_sf, time_start, time_stop) ⇒ Object
- #format_duration_value(duration_sf) ⇒ Object
- #format_precise_part(count, label) ⇒ Object
- #html_labimotion ⇒ Object
-
#initialize(current_user, element, export_format) ⇒ ExportElement
constructor
A new instance of ExportElement.
- #parse_datetime_range_value(str) ⇒ Object
- #pluralize_unit?(value) ⇒ Boolean
- #precise_diff_components(start_t, stop_t) ⇒ Object
- #precise_diff_humanize(start_t, stop_t) ⇒ Object
- #precise_diff_raw(start_t, stop_t) ⇒ Object
- #res_name ⇒ Object
- #sample_url ⇒ Object
- #table_cell_element_text(val) ⇒ Object
- #table_cell_molecule_text(val) ⇒ Object
- #table_cell_sample_text(val) ⇒ Object
- #table_cell_sysdef_text(sub_field, cell) ⇒ Object
- #table_cell_text(sub_val, sub_field) ⇒ Object
- #to_docx ⇒ Object
- #xml_escape(str) ⇒ Object
Constructor Details
#initialize(current_user, element, export_format) ⇒ ExportElement
Returns a new instance of ExportElement.
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 |
# File 'lib/labimotion/libs/export_element.rb', line 13 def initialize(current_user, element, export_format) @current_user = current_user @element = element @parent = case element.class.name when 'Labimotion::Segment' element&.element when 'Labimotion::Dataset' element&.element&.root_element end @element_klass = case element.class.name when 'Labimotion::Element' element.element_klass when 'Labimotion::Segment' element.segment_klass when 'Labimotion::Dataset' element.dataset_klass end @name = @element.instance_of?(Labimotion::Element) ? element.name : @parent&.name @short_label = @element.instance_of?(Labimotion::Element) ? element.short_label : @parent&.short_label @element_name = "#{@element_klass.label}_#{@short_label}".gsub(/\s+/, '') @properties = element.properties @options = element.properties_release[Labimotion::Prop::SEL_OPTIONS] @export_format = export_format @cover_tempfiles = [] rescue StandardError => e Labimotion.log_exception(e) end |
Instance Method Details
#apply_docx_cover_dimensions(image, data) ⇒ Object
Without dimensions the placeholder geometry of the template is kept, which distorts the aspect ratio — best effort, never fatal.
576 577 578 579 580 581 582 583 584 585 586 |
# File 'lib/labimotion/libs/export_element.rb', line 576 def apply_docx_cover_dimensions(image, data) require 'mini_magick' width, height = MiniMagick::Image.read(data).dimensions return unless width.to_i.positive? && height.to_i.positive? scale = [1.0, DOCX_COVER_MAX_W.to_f / width, DOCX_COVER_MAX_H.to_f / height].min image.px_width = (width * scale).round image.px_height = (height * scale).round rescue LoadError, StandardError => e Labimotion.log_exception(e) end |
#borrow_unit(higher, lower, base) ⇒ Object
355 356 357 358 359 |
# File 'lib/labimotion/libs/export_element.rb', line 355 def borrow_unit(higher, lower, base) return [higher, lower] unless lower.negative? [higher - 1, lower + base] end |
#build_cover_image(ref) ⇒ Object
530 531 532 533 534 535 536 537 538 539 |
# File 'lib/labimotion/libs/export_element.rb', line 530 def build_cover_image(ref) att = cover_helpers.(@element, ref['source'], ref['id']) data, mime = att && docx_cover_payload(att) return nil if data.nil? { image: docx_cover_sablon_image(data, mime), caption: docx_cover_caption(ref, att) } rescue StandardError => e Labimotion.log_exception(e) nil end |
#build_cover_images ⇒ Object
520 521 522 523 524 525 526 527 528 |
# File 'lib/labimotion/libs/export_element.rb', line 520 def build_cover_images return [] unless @element.instance_of?(Labimotion::Element) refs = @element.&.fetch('cover_images', nil) || [] refs.filter_map { |ref| build_cover_image(ref) } rescue StandardError => e Labimotion.log_exception(e) [] end |
#build_datetime_range_wordml(field) ⇒ Object
242 243 244 245 246 247 248 249 250 |
# File 'lib/labimotion/libs/export_element.rb', line 242 def build_datetime_range_wordml(field) sub_fields = field.fetch('sub_fields', []) || [] by_col = sub_fields.each_with_object({}) { |sf, h| h[sf['col_name']] = sf if sf.is_a?(Hash) } values = datetime_range_values(by_col) datetime_range_wordml_table(values) rescue StandardError => e Labimotion.log_exception(e) Sablon.content(:word_ml, TABLE_BLANK_WORDML) end |
#build_field(layer, field) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'lib/labimotion/libs/export_element.rb', line 78 def build_field(layer, field) field_obj = {} field_obj[:label] = field['label'] field_obj[:field] = field['field'] field_obj[:type] = field['type'] field_obj.merge!(field.slice('value', 'value_system')) field_obj[:is_table] = false field_obj[:not_table] = true case field['type'] when Labimotion::FieldType::DRAG_ELEMENT field_obj[:value] = (field['value'] && field['value']['el_label']) || '' field_obj[:obj] = field['value'] ### change to object when Labimotion::FieldType::DRAG_SAMPLE val = field.fetch('value', nil) if val.present? instance = Sample.find_by(id: val['el_id']) field_obj[:value] = val['el_label'] field_obj[:has_structure] = true obj_os = Entities::SampleReportEntity.new( instance, current_user: @current_user, detail_levels: ElementDetailLevelCalculator.new(user: @current_user, element: instance).detail_levels, ).serializable_hash obj_final = OpenStruct.new(obj_os) field_obj[:structure] = Reporter::Docx::DiagramSample.new(obj: obj_final, format: 'png').generate end when Labimotion::FieldType::SYS_REACTION val = field.fetch('value', nil) if val.present? instance = Reaction.find_by(id: val['el_id']) field_obj[:value] = val['el_label'] field_obj[:has_structure] = true obj_os = Entities::ReactionReportEntity.new( instance, current_user: @current_user, detail_levels: ElementDetailLevelCalculator.new(user: @current_user, element: instance).detail_levels, ).serializable_hash obj_final = OpenStruct.new(obj_os) field_obj[:structure] = Reporter::Docx::DiagramReaction.new(obj: obj_final, format: 'png').generate end when Labimotion::FieldType::DRAG_MOLECULE val = field.fetch('value', nil) if val.present? obj = Molecule.find_by(id: val['el_id']) field_obj[:value] = val['el_label'] end when Labimotion::FieldType::SELECT field_obj[:value] = @options.fetch(field['option_layers'], nil)&.fetch('options', nil)&.find { |ss| ss['key'] == field['value'] }&.fetch('label', nil) || field['value'] when Labimotion::FieldType::UPLOAD files = field.fetch('value', nil)&.fetch('files', []) val = files&.map { |file| "#{file['filename']} #{file['label']}" }&.join('\n') field_obj[:value] = val when Labimotion::FieldType::TABLE field_obj[:is_table] = false field_obj[:not_table] = true field_obj[:value] = build_table_wordml(field) when Labimotion::FieldType::DATETIME_RANGE field_obj[:is_table] = false field_obj[:not_table] = true field_obj[:value] = build_datetime_range_wordml(field) when Labimotion::FieldType::INPUT_GROUP val = [] field.fetch('sub_fields', [])&.each do |sub_field| if sub_field['type'] == Labimotion::FieldType::SYSTEM_DEFINED val.push("#{sub_field['value']} #{sub_field['value_system']}") else val.push(sub_field['value']) end end field_obj[:value] = val.join(' ') when Labimotion::FieldType::WF_NEXT if field['value'].present? && field['wf_options'].present? field_obj[:value] = field['wf_options'].find { |ss| ss['key'] == field['value'] }&.fetch('label', nil)&.split('(')&.first&.strip end when Labimotion::FieldType::SYSTEM_DEFINED _field = field unit = Labimotion::Units::FIELDS.find { |o| o[:field] == _field['option_layers'] }&.fetch(:units, []).find { |u| u[:key] == _field['value_system'] }&.fetch(:label, '') val = _field['value'].to_s + ' ' + unit val = Sablon.content(:html, "<div>" + val + "</div>") if val.include? '<' field_obj[:value] = val when Labimotion::FieldType::TEXT_FORMULA field.fetch('text_sub_fields', []).each do |sub_field| va = @properties['layers'][sub_field.fetch('layer','')]['fields'].find { |f| f['field'] == sub_field.fetch('field','') }&.fetch('value',nil) field_obj[:value] = (field_obj[:value] || '') + va.to_s + sub_field.fetch('separator','') if va.present? end # field_obj[:value] = (field['value'] && field['value']['el_label']) || '' # field_obj[:obj] = field['value'] ### change to object else field_obj[:value] = field['value'] end field_obj rescue StandardError => e Labimotion.log_exception(e) end |
#build_field_html(layer, field, cols) ⇒ Object
604 605 606 607 608 609 610 611 612 613 614 615 616 617 |
# File 'lib/labimotion/libs/export_element.rb', line 604 def build_field_html(layer, field, cols) case field['type'] when Labimotion::FieldType::DRAG_SAMPLE, Labimotion::FieldType::DRAG_ELEMENT, Labimotion::FieldType::DRAG_MOLECULE val = (field['value'] && field['value']['el_label']) || '' when Labimotion::FieldType::UPLOAD val = (field['value'] && field['value']['files'] && field['value']['files'].first && field['value']['files'].first['filename'] ) || '' else val = field['value'] end htd = field['hasOwnRow'] == true ? "<td colspan=#{cols}>" : '<td>' "#{htd}<b>#{field['label']}: </b><br />#{val}</td>" rescue StandardError => e Labimotion.log_exception(e) end |
#build_fields(layer) ⇒ Object
450 451 452 453 454 455 456 457 458 459 460 461 462 |
# File 'lib/labimotion/libs/export_element.rb', line 450 def build_fields(layer) fields = layer[Labimotion::Prop::FIELDS] || [] field_objs = [] fields.each do |field| next if field['type'] == 'dummy' field_obj = build_field(layer, field) field_objs.push(field_obj) end field_objs rescue StandardError => e Labimotion.log_exception(e) end |
#build_fields_html(layer) ⇒ Object
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
# File 'lib/labimotion/libs/export_element.rb', line 619 def build_fields_html(layer) fields = layer[Labimotion::Prop::FIELDS] || [] field_objs = [] cols = layer['cols'] || 0 field_objs.push('<table style="width: 4000dxa"><tr>') fields.each do |field| if cols&.zero? || field['hasOwnRow'] == true field_objs.push('</tr><tr>') cols = layer['cols'] end field_obj = build_field_html(layer, field, layer['cols']) field_objs.push(field_obj) cols -= 1 cols = 0 if field['hasOwnRow'] == true end field_objs.push('</tr></table>') field_objs&.join("")&.gsub('<tr></tr>', '') rescue StandardError => e Labimotion.log_exception(e) end |
#build_layers ⇒ Object
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 |
# File 'lib/labimotion/libs/export_element.rb', line 49 def build_layers objs = [] @properties[Labimotion::Prop::LAYERS]&.keys&.sort_by do |key| [ @properties[Labimotion::Prop::LAYERS].fetch(key, nil)&.fetch('position', 0) || 0, @properties[Labimotion::Prop::LAYERS].fetch(key, nil)&.fetch('wf_position', 0) || 0 ] end&.each do |key| layer = @properties[Labimotion::Prop::LAYERS][key] || {} ## Build fields html # field_objs = build_fields_html(layer) if layer[Labimotion::Prop::FIELDS]&.length&.positive? # field_html = Sablon.content(:html, field_objs) if field_objs.present? field_objs = build_fields(layer) layer_info = { label: layer['label'], layer: layer['layer'], cols: layer['cols'], timeRecord: layer['timeRecord'], fields: field_objs } objs.push(layer_info) end objs rescue StandardError => e Labimotion.log_exception(e) end |
#build_layers_html ⇒ Object
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 |
# File 'lib/labimotion/libs/export_element.rb', line 641 def build_layers_html layer_html = [] first_line = true @properties[Labimotion::Prop::LAYERS]&.keys&.each do |key| layer_html.push('</tr></table>') if first_line == false layer = @properties[Labimotion::Prop::LAYERS][key] || {} fields = layer[Labimotion::Prop::FIELDS] || [] layer_html.push("<h2><b>Layer:#{layer['label']}</b></h2>") layer_html.push('<table><tr>') cols = layer['cols'] fields.each do |field| if (cols === 0) layer_html.push('</tr><tr>') end val = field['value'].is_a?(Hash) ? field['value']['el_label'] : field['value'] layer_html.push("<td>#{field['label']}: <br />#{val}</td>") cols -= 1 end first_line = false end layer_html.push('</tr></table>') layer_html.join('') rescue StandardError => e Labimotion.log_exception(e) end |
#build_table_body_rows(sub_values, sub_fields, width, font_size) ⇒ Object
377 378 379 380 381 382 |
# File 'lib/labimotion/libs/export_element.rb', line 377 def build_table_body_rows(sub_values, sub_fields, width, font_size) sub_values.map do |sv| cells = sub_fields.map { |sf| build_wordml_cell(table_cell_text(sv, sf), width, font_size, false) }.join "<w:tr>#{cells}</w:tr>" end.join end |
#build_table_field(sub_val, sub_field) ⇒ Object
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/labimotion/libs/export_element.rb', line 174 def build_table_field(sub_val, sub_field) return '' if sub_field.fetch('id', nil).nil? || sub_val[sub_field['id']].nil? case sub_field['type'] when Labimotion::FieldType::DRAG_SAMPLE val = sub_val[sub_field['id']]['value'] || {} label = val['el_label'].present? ? "Short Label: [#{val['el_label']}] \n" : '' name = val['el_name'].present? ? "Name: [#{val['el_name']}] \n" : '' ext = val['el_external_label'].present? ? "Ext. Label: [#{val['el_external_label']}] \n" : '' mass = val['el_molecular_weight'].present? ? "Mass: [#{val['el_molecular_weight']}] \n" : '' url = val['el_id'].present? ? "#{sample_url}/#{val['el_id']}" : '' "#{label}#{name}#{ext}#{mass}#{url}" when Labimotion::FieldType::DRAG_MOLECULE val = sub_val[sub_field['id']]['value'] || {} smile = val['el_smiles'].present? ? "SMILES: [#{val['el_smiles']}] \n" : '' inchikey = val['el_inchikey'].present? ? "InChiKey:[#{val['el_inchikey']}] \n" : '' iupac = val['el_iupac'].present? ? "IUPAC:[#{val['el_iupac']}] \n" : '' mass = val['el_molecular_weight'].present? ? "MASS: [#{val['el_molecular_weight']}] \n" : '' "#{smile}#{inchikey}#{iupac}#{mass}" when Labimotion::FieldType::SELECT sub_val[sub_field['id']]['value'] when Labimotion::FieldType::SYSTEM_DEFINED unit = Labimotion::Units::FIELDS.find { |o| o[:field] == sub_field['option_layers'] }&.fetch(:units, [])&.find { |u| u[:key] == sub_val[sub_field['id']]['value_system'] }&.fetch(:label, '') val = sub_val[sub_field['id']]['value'].to_s + ' ' + unit val = Sablon.content(:html, "<div>" + val + "</div>") if val.include? '<' val else sub_val[sub_field['id']] end end |
#build_table_header_row(sub_fields, width, font_size) ⇒ Object
372 373 374 375 |
# File 'lib/labimotion/libs/export_element.rb', line 372 def build_table_header_row(sub_fields, width, font_size) cells = sub_fields.map { |sf| build_wordml_cell(sf['col_name'].to_s, width, font_size, true) }.join "<w:tr>#{cells}</w:tr>" end |
#build_table_wordml(field) ⇒ Object
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/labimotion/libs/export_element.rb', line 215 def build_table_wordml(field) sub_fields = field.fetch('sub_fields', []) return Sablon.content(:word_ml, TABLE_BLANK_WORDML) if sub_fields.empty? width = (9000.0 / sub_fields.length).round font_size = sub_fields.length > 6 ? 16 : 20 grid = sub_fields.map { %(<w:gridCol w:w="#{width}"/>) }.join header = build_table_header_row(sub_fields, width, font_size) rows = build_table_body_rows(field.fetch('sub_values', []), sub_fields, width, font_size) tbl = '<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="pct"/>' \ "#{TABLE_BORDER}</w:tblPr><w:tblGrid>#{grid}</w:tblGrid>" \ "#{header}#{rows}</w:tbl>" Sablon.content(:word_ml, tbl) rescue StandardError => e Labimotion.log_exception(e) Sablon.content(:word_ml, TABLE_BLANK_WORDML) end |
#build_utc_from_parts(parts) ⇒ Object
324 325 326 327 |
# File 'lib/labimotion/libs/export_element.rb', line 324 def build_utc_from_parts(parts) Time.utc(parts[:year], parts[:mon], parts[:mday], parts[:hour] || 0, parts[:min] || 0, parts[:sec] || 0) end |
#build_wordml_cell(text, width, font_size, bold) ⇒ Object
384 385 386 387 388 389 390 391 392 393 |
# File 'lib/labimotion/libs/export_element.rb', line 384 def build_wordml_cell(text, width, font_size, bold) bold_xml = bold ? '<w:b/>' : '' rpr = "<w:rPr>#{bold_xml}<w:sz w:val=\"#{font_size}\"/></w:rPr>" lines = text.to_s.split(/\r?\n/) lines = [''] if lines.empty? paragraphs = lines.map do |line| "<w:p><w:r>#{rpr}<w:t xml:space=\"preserve\">#{xml_escape(line)}</w:t></w:r></w:p>" end.join "<w:tc><w:tcPr><w:tcW w:w=\"#{width}\" w:type=\"dxa\"/></w:tcPr>#{paragraphs}</w:tc>" end |
#close_cover_tempfiles ⇒ Object
494 495 496 |
# File 'lib/labimotion/libs/export_element.rb', line 494 def close_cover_tempfiles Array(@cover_tempfiles).each(&:close!) end |
#compute_duration_calc(time_start, time_stop) ⇒ Object
300 301 302 303 304 305 306 |
# File 'lib/labimotion/libs/export_element.rb', line 300 def compute_duration_calc(time_start, time_stop) start_t = parse_datetime_range_value(time_start) stop_t = parse_datetime_range_value(time_stop) return '' unless start_t && stop_t && stop_t > start_t precise_diff_humanize(start_t, stop_t) end |
#cover_context ⇒ Object
515 516 517 518 |
# File 'lib/labimotion/libs/export_element.rb', line 515 def cover_context covers = build_cover_images { has_cover: covers.present?, cover_images: covers } end |
#cover_helpers ⇒ Object
593 594 595 |
# File 'lib/labimotion/libs/export_element.rb', line 593 def cover_helpers @cover_helpers ||= Object.new.extend(Labimotion::CoverImageHelpers) end |
#datetime_range_parts_complete?(parts) ⇒ Boolean
320 321 322 |
# File 'lib/labimotion/libs/export_element.rb', line 320 def datetime_range_parts_complete?(parts) %i[year mon mday].all? { |k| parts[k] } end |
#datetime_range_values(by_col) ⇒ Object
252 253 254 255 256 257 258 259 260 261 |
# File 'lib/labimotion/libs/export_element.rb', line 252 def datetime_range_values(by_col) time_start = by_col['timeStart']&.dig('value').to_s time_stop = by_col['timeStop']&.dig('value').to_s [ time_start, time_stop, format_duration_calc(by_col['durationCalc'], time_start, time_stop), format_duration_value(by_col['duration']) ] end |
#datetime_range_wordml_table(values) ⇒ Object
263 264 265 266 267 268 269 270 271 272 273 |
# File 'lib/labimotion/libs/export_element.rb', line 263 def datetime_range_wordml_table(values) width = (9000.0 / DATETIME_RANGE_HEADERS.length).round font_size = 20 grid = DATETIME_RANGE_HEADERS.map { %(<w:gridCol w:w="#{width}"/>) }.join header_cells = DATETIME_RANGE_HEADERS.map { |h| build_wordml_cell(h, width, font_size, true) }.join body_cells = values.map { |v| build_wordml_cell(v, width, font_size, false) }.join tbl = '<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="pct"/>' \ "#{TABLE_BORDER}</w:tblPr><w:tblGrid>#{grid}</w:tblGrid>" \ "<w:tr>#{header_cells}</w:tr><w:tr>#{body_cells}</w:tr></w:tbl>" Sablon.content(:word_ml, tbl) end |
#docx_context ⇒ Object
481 482 483 484 485 486 487 488 489 490 491 492 |
# File 'lib/labimotion/libs/export_element.rb', line 481 def docx_context { label: @element_klass.label, desc: @element_klass.desc, name: @name, parent_klass: @parent.present? ? "#{@parent&.class&.name&.split('::')&.last}: " : '', short_label: @short_label, date: Time.now.strftime('%d/%m/%Y'), author: @current_user.name, layers: build_layers }.merge(cover_context) end |
#docx_cover_caption(ref, att) ⇒ Object
588 589 590 591 |
# File 'lib/labimotion/libs/export_element.rb', line 588 def docx_cover_caption(ref, att) label = ref['source'] == 'analysis' ? @element.analyses.find_by(id: ref['id'])&.name : att.filename "ref: #{ref['source']}: #{label}" end |
#docx_cover_original(att) ⇒ Object
549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/labimotion/libs/export_element.rb', line 549 def docx_cover_original(att) return nil unless att.type_image? && !att.type_image_tiff? mime = att.content_type.to_s.downcase data = att.read_file return nil if data.nil? return [data, mime] if DOCX_COVER_MIMES.include?(mime) # the template's blip placeholder takes bitmaps only, so svg & friends # are rasterized onto white through the shared cover helper converted = cover_helpers.cover_rasterize(data, mime) [converted, 'image/png'] if converted end |
#docx_cover_payload(att) ⇒ Object
541 542 543 544 545 546 547 |
# File 'lib/labimotion/libs/export_element.rb', line 541 def docx_cover_payload(att) original = docx_cover_original(att) return original if original thumb = att.read_thumbnail [thumb, 'image/png'] if thumb end |
#docx_cover_sablon_image(data, mime) ⇒ Object
563 564 565 566 567 568 569 570 571 572 |
# File 'lib/labimotion/libs/export_element.rb', line 563 def docx_cover_sablon_image(data, mime) tmp = Tempfile.new(['labimotion-cover', DOCX_COVER_EXT.fetch(mime, '.png')]) tmp.binmode tmp.write(data) tmp.flush @cover_tempfiles << tmp image = Sablon::Image.create_by_path(tmp.path) apply_docx_cover_dimensions(image, data) image end |
#duration_unit_label(value_system, value) ⇒ Object
282 283 284 285 286 287 |
# File 'lib/labimotion/libs/export_element.rb', line 282 def duration_unit_label(value_system, value) base = DURATION_UNIT_LABELS[value_system.to_s] return value_system.to_s if base.nil? pluralize_unit?(value) ? "#{base}s" : base end |
#format_duration_calc(_duration_calc_sf, time_start, time_stop) ⇒ Object
296 297 298 |
# File 'lib/labimotion/libs/export_element.rb', line 296 def format_duration_calc(_duration_calc_sf, time_start, time_stop) compute_duration_calc(time_start, time_stop) end |
#format_duration_value(duration_sf) ⇒ Object
275 276 277 278 279 280 |
# File 'lib/labimotion/libs/export_element.rb', line 275 def format_duration_value(duration_sf) val = duration_sf&.dig('value') return '' if val.nil? || val.to_s.empty? "#{val} #{duration_unit_label(duration_sf['value_system'], val)}".strip end |
#format_precise_part(count, label) ⇒ Object
337 338 339 340 |
# File 'lib/labimotion/libs/export_element.rb', line 337 def format_precise_part(count, label) suffix = count == 1 ? '' : 's' "#{count} #{label}#{suffix}" end |
#html_labimotion ⇒ Object
668 669 670 671 672 673 674 675 676 |
# File 'lib/labimotion/libs/export_element.rb', line 668 def html_labimotion layers_html = build_layers_html html_body = <<-HTML.strip #{layers_html} HTML html_body rescue StandardError => e Labimotion.log_exception(e) end |
#parse_datetime_range_value(str) ⇒ Object
308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/labimotion/libs/export_element.rb', line 308 def parse_datetime_range_value(str) cleaned = str.to_s.strip return nil if cleaned.empty? parts = Date._parse(cleaned) return nil unless datetime_range_parts_complete?(parts) build_utc_from_parts(parts) rescue ArgumentError nil end |
#pluralize_unit?(value) ⇒ Boolean
289 290 291 292 293 294 |
# File 'lib/labimotion/libs/export_element.rb', line 289 def pluralize_unit?(value) numeric = Float(value.to_s) (numeric - 1.0).abs > Float::EPSILON rescue ArgumentError, TypeError true end |
#precise_diff_components(start_t, stop_t) ⇒ Object
342 343 344 345 346 347 348 349 350 351 352 353 |
# File 'lib/labimotion/libs/export_element.rb', line 342 def precise_diff_components(start_t, stop_t) y, m, d, h, mi, s = precise_diff_raw(start_t, stop_t) mi, s = borrow_unit(mi, s, 60) h, mi = borrow_unit(h, mi, 60) d, h = borrow_unit(d, h, 24) if d.negative? m -= 1 d += (Date.new(stop_t.year, stop_t.month, 1) - 1).day end y, m = borrow_unit(y, m, 12) [y, m, d, h, mi, s] end |
#precise_diff_humanize(start_t, stop_t) ⇒ Object
329 330 331 332 333 334 335 |
# File 'lib/labimotion/libs/export_element.rb', line 329 def precise_diff_humanize(start_t, stop_t) components = precise_diff_components(start_t, stop_t) parts = components.zip(DATETIME_RANGE_PRECISE_LABELS).reject { |n, _| n <= 0 } return '0 seconds' if parts.empty? parts.map { |n, label| format_precise_part(n, label) }.join(' ') end |
#precise_diff_raw(start_t, stop_t) ⇒ Object
361 362 363 364 365 366 367 368 369 370 |
# File 'lib/labimotion/libs/export_element.rb', line 361 def precise_diff_raw(start_t, stop_t) [ stop_t.year - start_t.year, stop_t.month - start_t.month, stop_t.day - start_t.day, stop_t.hour - start_t.hour, stop_t.min - start_t.min, stop_t.sec - start_t.sec ] end |
#res_name ⇒ Object
598 599 600 601 602 |
# File 'lib/labimotion/libs/export_element.rb', line 598 def res_name "#{@element_name}_#{Time.now.strftime('%Y%m%d%H%M')}.docx" rescue StandardError => e Labimotion.log_exception(e) end |
#sample_url ⇒ Object
43 44 45 46 47 |
# File 'lib/labimotion/libs/export_element.rb', line 43 def sample_url host = ENV['PUBLIC_URL'] || 'http://localhost:3000' api = 'mydb/collection/all/sample' "#{host}/#{api}" end |
#table_cell_element_text(val) ⇒ Object
437 438 439 440 441 442 |
# File 'lib/labimotion/libs/export_element.rb', line 437 def table_cell_element_text(val) parts = [] parts << "Short Label: [#{val['el_label']}]" if val['el_label'].present? parts << "Name: [#{val['el_name']}]" if val['el_name'].present? parts.join("\n") end |
#table_cell_molecule_text(val) ⇒ Object
428 429 430 431 432 433 434 435 |
# File 'lib/labimotion/libs/export_element.rb', line 428 def table_cell_molecule_text(val) parts = [] parts << "SMILES: [#{val['el_smiles']}]" if val['el_smiles'].present? parts << "InChiKey: [#{val['el_inchikey']}]" if val['el_inchikey'].present? parts << "IUPAC: [#{val['el_iupac']}]" if val['el_iupac'].present? parts << "MASS: [#{val['el_molecular_weight']}]" if val['el_molecular_weight'].present? parts.join("\n") end |
#table_cell_sample_text(val) ⇒ Object
418 419 420 421 422 423 424 425 426 |
# File 'lib/labimotion/libs/export_element.rb', line 418 def table_cell_sample_text(val) parts = [] parts << "Short Label: [#{val['el_label']}]" if val['el_label'].present? parts << "Name: [#{val['el_name']}]" if val['el_name'].present? parts << "Ext. Label: [#{val['el_external_label']}]" if val['el_external_label'].present? parts << "Mass: [#{val['el_molecular_weight']}]" if val['el_molecular_weight'].present? parts << "#{sample_url}/#{val['el_id']}" if val['el_id'].present? parts.join("\n") end |
#table_cell_sysdef_text(sub_field, cell) ⇒ Object
444 445 446 447 448 |
# File 'lib/labimotion/libs/export_element.rb', line 444 def table_cell_sysdef_text(sub_field, cell) fdef = Labimotion::Units::FIELDS.find { |o| o[:field] == sub_field['option_layers'] } unit = fdef&.fetch(:units, [])&.find { |u| u[:key] == cell['value_system'] }&.fetch(:label, '') "#{cell['value']} #{unit}".strip end |
#table_cell_text(sub_val, sub_field) ⇒ Object
407 408 409 410 411 412 413 414 415 416 |
# File 'lib/labimotion/libs/export_element.rb', line 407 def table_cell_text(sub_val, sub_field) return '' if sub_field.fetch('id', nil).nil? || sub_val[sub_field['id']].nil? cell = sub_val[sub_field['id']] renderer = TABLE_CELL_TEXT_RENDERERS[sub_field['type']] return renderer.call(sub_field, cell, self) if renderer raw = cell.is_a?(Hash) ? cell['value'] : cell raw.to_s end |
#to_docx ⇒ Object
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
# File 'lib/labimotion/libs/export_element.rb', line 464 def to_docx # location = Rails.root.join('lib', 'template', 'Labimotion.docx') location = Rails.root.join('lib', 'template', 'Labimotion_lines.docx') # location = Rails.root.join('lib', 'template', 'Labimotion_img.docx') template = Sablon.template(location) tempfile = Tempfile.new('labimotion.docx') template.render_to_file File.(tempfile), docx_context File.read(tempfile) rescue StandardError => e Labimotion.log_exception(e) ensure # Close and delete the temporary files tempfile&.close tempfile&.unlink close_cover_tempfiles end |
#xml_escape(str) ⇒ Object
395 396 397 |
# File 'lib/labimotion/libs/export_element.rb', line 395 def xml_escape(str) str.to_s.gsub('&', '&').gsub('<', '<').gsub('>', '>') end |