ask/app/helpers/admin/asks_helper.rb

687 lines
32 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

module Admin::AsksHelper
extend self
extend ActionView::Helpers::FormTagHelper
extend ActionView::Helpers::FormOptionsHelper
extend ActionView::Helpers::DateHelper
extend ActionView::Helpers::TagHelper
extend ActionView::Helpers::RenderingHelper
extend ActionView::Context
extend OrbitBasis::RenderAnywhere
extend ActionView::Helpers::UrlHelper
extend OrbitFormHelper
extend Ckeditor::Helpers::FormHelper
def mask_ask_name(name)
return name if name.blank?
first_char = name[0]
if first_char =~ /\p{Han}/
cleaned = name.gsub(/[^\p{Han}\s]/, '')
char_count = cleaned.scan(/\p{Han}/).length
if char_count <= 1
cleaned
elsif char_count <= 3
cleaned[0] + ''
else
cleaned[0..1] + ''
end
else
cleaned = name.gsub(/\p{Han}/, '')
words = cleaned.split(' ').reject(&:blank?)
if words.length <= 1
words[0].to_s
else
words[1] + '..'
end
end
end
def get_categories_info_for_ask
current_user = OrbitHelper.current_user
OrbitHelper.set_params(params,current_user)
OrbitHelper.set_this_module_app("ask")
cats_relations = []
access_level = OrbitHelper.user_access_level?
include_all = false
cats = []
if access_level == "sub_manager"
cats = current_user.approved_categories_for_module(@module_app)
elsif access_level && access_level != "user"
cats = @module_app.categories.enabled
include_all = true
end
if (@module_app.asc rescue true)
cats = cats.sort_by{|category| (category.sort_number.to_i rescue category.id) }
else
cats = cats.sort_by{|category| (-category.sort_number.to_i rescue category.id)}
end
cats_relations = cats.map{|c| [c.id.to_s, c.title]}
if include_all && cats_relations.count != 1
cats_relations.insert(0, ["",t(:all)])
end
cats_relations
end
def set_input_name_for_ask(input_name)
@input_name = input_name
end
def get_input_name_for_ask
@input_name
end
def create_lang_panel_for_ask(field)
tmp2 = content_tag(:div,:class => 'btn-group', :data=>{:toggle=>"buttons-radio"}) do
I18n.available_locales.collect do |key|
link_entry_ary = ["##{field}", "_#{key}", @field_postfix]
link_entry = link_entry_ary.join
link_to(I18n.t(key),link_entry,:data=>{:toggle=>"tab"},:class=>"btn #{(key == I18n.locale ? "active" : nil)}",:for=>key)
end.join.html_safe
end
end
def multiple_lang_show_tag_for_ask(field_name, index1,field,value=nil,combine_element='',exteral_options={},sortable=false, extra_tr_class="",only_contents=false)
if !index1.nil?
all_field = (get_input_name_for_ask + "[#{index1}][#{field}][parant]").gsub(/[\[@]/,'_').gsub(/\]/,'')
else
all_field = (get_input_name_for_ask + "[#{field}][parant]").gsub(/[\[@]/,'_').gsub(/\]/,'')
end
if @field_postfix.nil?
@field_postfix = 1
else
@field_postfix += 1
end
tmp = (I18n.available_locales.collect do |locale|
active_flag = ((locale == I18n.locale) ? ' active' : '')
content_tag(:div,:class => "tab-content#{active_flag}",:id=>"#{all_field}_#{locale}#{@field_postfix}") do
value_locale = value[locale.to_s] rescue nil
"<div class=\"show_field\" id=\"#{index1 ? "#{get_input_name_for_ask}[#{index1}][#{field}][#{locale}]" : "#{get_input_name_for_ask}[#{field}][#{locale}]"}\">#{value_locale}</div>".html_safe
end
end.join + create_lang_panel_for_ask(all_field)).html_safe + combine_element
if sortable
if exteral_options['style'].nil?
exteral_options['style'] = 'display: flex;align-items: center;flex-wrap: nowrap;'
else
exteral_options['style'] = exteral_options['style'] + 'display: flex;align-items: center;flex-wrap: nowrap;'
end
tmp = content_tag(:div,{:class => "tab-panel border"}.merge(exteral_options)) do
("<i class=\"icons-list-2\" style=\"cursor: grab;font-size: x-large;\"></i>" +content_tag(:div) do
tmp
end).html_safe
end
else
tmp = content_tag(:div,{:class => "tab-panel"}.merge(exteral_options)) do
tmp
end
end
if only_contents
tmp
else
tmp = "<tr class=\"#{extra_tr_class}\"><td>#{field_name}".html_safe + ":</td><td>".html_safe + tmp + "</td></tr>".html_safe
end
end
def multiple_lang_tag_for_ask(index1,type_of_tag,field,value=nil,custom_options={},combine_element='',exteral_options={},sortable=false)
if !index1.nil?
all_field = (get_input_name_for_ask + "[#{index1}][#{field}][parant]").gsub(/[\[@]/,'_').gsub(/\]/,'')
else
all_field = (get_input_name_for_ask + "[#{field}][parant]").gsub(/[\[@]/,'_').gsub(/\]/,'')
end
if @field_postfix.nil?
@field_postfix = 1
else
@field_postfix += 1
end
tmp = (I18n.available_locales.collect do |locale|
active_flag = ((locale == I18n.locale) ? ' active' : '')
content_tag(:div,:class => "tab-content#{active_flag}",:id=>"#{all_field}_#{locale}#{@field_postfix}") do
value_locale = value[locale.to_s] rescue nil
if !index1.nil?
self.__send__("#{type_of_tag}_tag","#{get_input_name_for_ask}[#{index1}][#{field}][#{locale}]",value_locale,custom_options)
else
self.__send__("#{type_of_tag}_tag","#{get_input_name_for_ask}[#{field}][#{locale}]",value_locale,custom_options)
end
end
end.join + create_lang_panel_for_ask(all_field)).html_safe + combine_element
if sortable
if exteral_options['style'].nil?
exteral_options['style'] = 'display: flex;align-items: center;flex-wrap: nowrap;'
else
exteral_options['style'] = exteral_options['style'] + 'display: flex;align-items: center;flex-wrap: nowrap;'
end
content_tag(:div,{:class => "tab-panel border"}.merge(exteral_options)) do
("<i class=\"icons-list-2\" style=\"cursor: grab;font-size: x-large;\"></i>" +content_tag(:div) do
tmp
end).html_safe
end
else
content_tag(:div,{:class => "tab-panel"}.merge(exteral_options)) do
tmp
end
end
end
def time_setting_block(key,value={})
class_block = (value['type'] != 'date') ? "time_setting_block" : "time_setting_block active"
format_selected = (value['type'] != 'date') ? nil : value['format']
range_selected = (value['type'] != 'date') ? nil : value['range_flag']
options1 = [['YYYY / MM / DD HH:mm','format1'],['YYYY / MM / DD','format2'],['YYYY / MM','format3'],['YYYY','format4']]
options2 = [[t('yes'),'true'],[t('no'),'false']]
format_setting_tag = field_select_tag_for_ask(key,'format',options1,format_selected)
range_setting_tag = field_select_tag_for_ask(key,'range_flag',options2,range_selected)
"<div class=\"#{class_block}\">
<table>
<tbody>
<tr>
<td>#{t('ask.format')}:</td><td>#{format_setting_tag}</td>
</tr>
<tr>
<td>#{t('ask.enable_range_setting')}:</td><td>#{range_setting_tag}</td>
</tr>
</tbody>
</table>
</div>"
end
def field_select_tag_for_ask(index1,field,options,selected=nil,custom_options={})
select_tag("#{get_input_name_for_ask}[#{index1}][#{field}]",options_for_select(options,selected: selected),custom_options)
end
def field_radio_button_tag(index1,field,show_value,checked,custom_options={})
radio_button_tag("#{get_input_name_for_ask}[#{index1}][#{field}]",show_value,checked,custom_options)
end
def render_date_block(field_name,v,i,value, prefix_contents="")
case v['format']
when 'format1'
t1 = text_field_tag("#{field_name}[datetime][date][#{i}]",(value['datetime']['date']["#{i}"] rescue nil),{:required => v['required']=='true',autocomplete: 'off',placeholder: t('ask.datepicker'),title: t('ask.datepicker')})
t1 = prefix_contents + t1
#t2_value = value['datetime']['h']["#{i}"] rescue nil
#t3_value = value['datetime']['m']["#{i}"] rescue nil
#t2 = select_tag("#{field_name}[datetime][h][#{i}]",options_for_select((1..24).collect{|v1| v1.to_s.rjust(2, "0")},selected: t2_value))
#t3 = select_tag("#{field_name}[datetime][m][#{i}]",options_for_select((0..59).collect{|v1| v1.to_s.rjust(2, "0")},selected: t3_value))
#t4 = "#{t2}<b style=\"padding: 0 0.1em;\">:</b>#{t3}"
"<div class=\"datetime_selector\">#{t1}</div>
<script>
jQuery(document).ready(function( $ ) {
$(\"input[name='#{field_name}[datetime][date][#{i}]']\").ui_datetimepicker({dateFormat: 'yy-mm-dd',controlType: 'select',timeInput: true,oneLine: true,timeFormat: 'HH:mm'});
})
</script>".html_safe
when 'format2'
t1 = text_field_tag("#{field_name}[datetime][date][#{i}]",(value['datetime']['date']["#{i}"] rescue nil),{:required => v['required']=='true',autocomplete: 'off',placeholder: t('ask.datepicker'),title: t('ask.datepicker')})
t1 = prefix_contents + t1
"<div class=\"datetime_selector\">#{t1}</div>
<script>
jQuery(document).ready(function( $ ) {
$(\"input[name='#{field_name}[datetime][date][#{i}]']\").ui_datepicker({dateFormat: 'yy-mm-dd'});
})
</script>".html_safe
when 'format3'
t1 = text_field_tag("#{field_name}[datetime][date][#{i}]",(value['datetime']['date']["#{i}"] rescue nil),{:required => v['required']=='true',autocomplete: 'off',placeholder: t('ask.datepicker'),title: t('ask.datepicker'),:class => 'yearpicker'})
t1 = prefix_contents + t1
"<div class=\"datetime_selector\">#{t1}</div>
<script>
jQuery(document).ready(function( $ ) {
$(\"input[name='#{field_name}[datetime][date][#{i}]']\").ui_datepicker({dateFormat: 'yy-mm',show_view: 'month'});
})
</script>
"
when 'format4'
t1 = text_field_tag("#{field_name}[datetime][date][#{i}]",(value['datetime']['date']["#{i}"] rescue nil),{:required => v['required']=='true',autocomplete: 'off',placeholder: t('ask.datepicker'),title: t('ask.datepicker'),:class => 'yearpicker'})
t1 = prefix_contents + t1
"<div class=\"datetime_selector\">#{t1}</div>
<script>
jQuery(document).ready(function( $ ) {
$(\"input[name='#{field_name}[datetime][date][#{i}]']\").ui_datepicker({dateFormat: 'yy',show_view: 'year'});
})
</script>
"
end
end
def ask_label(id, value, required='false')
label_tag(id,value,{:class=>"control-label#{required=='true' ? ' required' : ''}"})
end
def format_checkbox(options,value,multple_choose=false)
options.select{|index1,option| option['disabled'] != 'true'}.collect do |index1,option|
if multple_choose
if value && value[index1]==index1
"#{option[I18n.locale]}"
else
"#{option[I18n.locale]}"
end
else
if index1 == value
"#{option[I18n.locale]}"
else
"#{option[I18n.locale]}"
end
end
end.join('&nbsp;&nbsp;')
end
def show_on_front(k,v,object=nil,readonly=false,lock=false)
value = nil
if !object.nil?
value = object.custom_values[k]
if value.nil?
if k.start_with?("default@")
value = object.custom_values[k.sub(/.*@/,'')]
elsif k.start_with?("custom@")
category_id, k = k.scan(/custom@((?:(?!@).)*)@\w+/)[0][0]
if category_id==object.category_id.to_s
value = object.custom_values[k]
end
end
end
end
field_name = "#{get_input_name_for_ask}[custom_values][#{k}]"
begin
case v['type']
when 'text_field'
readonly ? value : text_field_tag(field_name,value,{:required => v['required']=='true',placeholder: v['prompt_word'][I18n.locale],title: v['prompt_word'][I18n.locale]})
when 'instructions'
(v['instructions'][I18n.locale].html_safe rescue "")
when 'select'
prompt_hash = v['prompt_word'][I18n.locale].blank? ? {} : {prompt: v['prompt_word'][I18n.locale]}
prompt_hash.merge!(required: v['required']=='true')
options_hash = Hash(v['options'])
if lock
format_checkbox(options_hash,value)
else
if v['default_option'].present?
default_idx = v['default_option'].to_i
default_key = options_hash.keys[default_idx]
value ||= default_key
end
readonly ? (v['options'][value.to_s][I18n.locale] rescue '') : select_tag(field_name,options_for_select(options_hash.select{|index1,option| option['disabled'] != 'true'}.collect{|index1,option| [option[I18n.locale],index1]},selected: value),prompt_hash)
end
when 'date'
if value.nil?
value = {}
end
if v['range_flag']=='true'
if readonly
format_str = "%Y/%m/%d %H:%M"
case v['format']
when 'format1'
format_str = "%Y/%m/%d %H:%M"
when 'format2'
format_str = "%Y/%m/%d"
when 'format3'
format_str = "%Y/%m"
when 'format4'
format_str = "%Y"
end
tmp = value['datetime']['date'] rescue {}
"#{DateTime.parse(tmp['0']).strftime(format_str) rescue ''}~#{DateTime.parse(tmp['1']).strftime(format_str) rescue ''}"
else
"<div style=\"display:inline-flex;flex-direction:column;\">
#{render_date_block(field_name,v,0,value, t('ask.start') + ': ')}
<div style=\"display: inline-flex;align-items: center;writing-mode: tb-rl;padding: 0.3em;\">~</div>
#{render_date_block(field_name,v,1,value, t('ask.end') + ': ')}
</div>".html_safe
end
else
if readonly
format_str = "%Y/%m/%d %H:%M"
case v['format']
when 'format1'
format_str = "%Y/%m/%d %H:%M"
when 'format2'
format_str = "%Y/%m/%d"
when 'format3'
format_str = "%Y/%m"
when 'format4'
format_str = "%Y"
end
tmp = value['datetime']['date'] rescue {}
(DateTime.parse(tmp['0']).strftime(format_str) rescue '')
else
render_date_block(field_name,v,0,value)
end
end
when 'text_area'
readonly ? value.to_s.gsub("\n", "<br/>").gsub("\r", "").html_safe : text_area_tag(field_name,value,{:required => v['required']=='true',:placeholder=> v['prompt_word'][I18n.locale],:title=> v['prompt_word'][I18n.locale],:class=>'ckeditor'})
when 'radio_button'
options_hash = Hash(v['options'])
if lock
format_checkbox(options_hash,value)
else
field_name_underscre = field_name.gsub(/(\[|\])/,'_').gsub('__','_').chomp('_')
default_idx = v['default_option'].to_i
value ||= options_hash.keys[default_idx]
readonly ? (options_hash[value.to_s][I18n.locale] rescue '') : options_hash.collect do |index1,option|
next if option['disabled'] == 'true'
"<label class=\"radio-inline\" for=\"#{field_name_underscre}_#{index1}\">#{radio_button_tag(field_name,index1,value==index1,{:required => v['required']=='true'})}#{option[I18n.locale]}</label>"
end.compact.join
end
when 'checkbox'
options_hash = Hash(v['options'])
if lock
format_checkbox(options_hash,value,true)
else
default_idx = v['default_option'].to_i
default_key = options_hash.keys[default_idx]
options_values = options_hash.values
value ||= {default_key=>default_key}
field_name_underscre = field_name.gsub(/(\[|\])/,'_').gsub('__','_').chomp('_')
readonly ? value.collect{|k1,v1| options_values[v1.to_i][I18n.locale]}.join(', ') : ("<span class=\"checkbox\">" + options_hash.collect do |index1,option|
next if option['disabled'] == 'true'
checkbox_option = option[I18n.locale]
"<label class=\"checkbox-inline\" for=\"#{field_name_underscre}_#{index1}\">#{check_box_tag("#{field_name}[#{index1}]",index1,value[index1]==index1,{title: checkbox_option})}#{checkbox_option}</label>"
end.compact.join + "</span>")
end
when 'file'
file_value = value[0] rescue nil
file_path = value[1] rescue nil
file_required = v['required']=='true'
if file_path
file_path = file_path.match(%r{/uploads/ask_file/file/([^/]+)/})[1]
file_path = "/#{I18n.locale}/admin/asks/#{file_path}/download"
end
readonly ? (file_path ? "<a href=\"#{file_path}\" title=\"file\">#{file_value}</a>".html_safe : "") : "<div class=\"file-selector\"><label class=\"ui-button\">
#{file_field_tag(field_name, {:data => {:src => file_path}, style: "position: absolute;width:0.1em;opacity: 0;padding: 0;border: 0;opacity: 0;left: 50%;top: 0;", :class => 'upload', :required => file_required, value: file_value, accept: ".doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.pdf,.jpg,.jpeg,.bmp,.gif,.png,.odf,.ods,.odt",
onchange: "
var file = this.files[0];
if (!file) return;
var maxSize = 20 * 1024 * 1024; // 20MB
var allowedExtensions = /\.(doc|docx|xls|xlsx|ppt|pptx|txt|pdf|jpg|jpeg|bmp|gif|png|odf|ods|odt)$/i;
if (file.size > maxSize) {
alert('File exceeds 20MB limit.');
this.value = '';
} else if (!allowedExtensions.test(file.name)) {
alert('Invalid file type. Allowed: doc, docx, xls, xlsx, ppt, pptx, txt, pdf, jpg, jpeg, bmp, gif, png, odf, ods, odt');
this.value = '';
}
"})}
<i class=\"fa fa-file\"></i> #{t('ask.upload_file')}
</label><div class=\"filename\"></div></div>"
when 'image'
file_value = value[0] rescue nil
file_path = value[1] rescue nil
file_required = v['required']=='true'
readonly ? (file_value ? "<img src=\"#{file_path}\" alt=\"#{file_value}\">".html_safe : "") : "<div class=\"file-selector\"><label class=\"ui-button\">
#{file_field_tag(field_name, {:data => {'image-src' => file_path}, style: "position: absolute;width:0.1em;padding: 0;border: 0;opacity: 0;left: 50%;top: 0;", :class => 'upload', :required => file_required, value: file_value, accept: "image/*"})}
<i class=\"fa fa-photo\"></i> #{t('ask.upload_image')}
</label><div class=\"filename\"></div></div>"
end
rescue => e
"<pre>#{e.inspect}<br>#{e.backtrace.to_yaml}</pre>"
end
end
def custom_field_block_for_ask(k,v={},show_only=false, other_first_rows="",extra_class="")
markups = LIST[:markups].select{|k,v| k != 'member_relationship' && k != 'address'}.collect{|key,val| [t("lists.markups."+key),key]} +[[t('ask.file_field'),'file'],[t('ask.image_field'),'image'],[t('ask.instructions'),'instructions']]
if show_only
multi_lang_tag = multiple_lang_show_tag_for_ask(t('ask.field_name'),k,'field',v['field'])
require_ask_tag = "<tr><td>#{t('ask.required')}:</td><td>#{v['required']=='true' ? t('ask.yes') : t('ask.no')}</td></tr>"
markups = markups.map{|k,v| [v,k]}.to_h
tmp = markups[v['type']]
tmp = markups.values[0] if tmp.nil?
options_hash = Hash(v['options'])
tmp_field_select_tag_for_ask = "<tr><td>#{t('ask.setting_type')}:</td><td><div id=\"#{get_input_name_for_ask}[#{k}][type]\">#{tmp}</div></td></tr>"
active_prompt_class = (v['type'] != 'instructions' ? '' : ' hide')
active_class = (['select','radio_button','checkbox'].include?(v['type']) ? '' : ' hide')
multi_lang_prompt_tag = multiple_lang_show_tag_for_ask(t('ask.prompt_word'),k,'prompt_word',v['prompt_word'],'',{},false, active_prompt_class)
multi_lang_default_option = multiple_lang_show_tag_for_ask(t('ask.default_option'),k,'default_option',v['default_option'].present? ? options_hash.values[v['default_option'].to_i] : I18n.t('ask.please_select'),'',{},false, active_class)
options_area = options_hash.collect do |key,value|
"#{multiple_lang_show_tag_for_ask("",k,"options][#{key}",value,'',{},false,"",true)}"
end.join
options_area = "<tr><td>#{I18n.t('ask.options')}</td><td>#{options_area}</td></tr>"
field_html = "
<style>
.show_field {
border: 1px solid black;
padding: 3px;
min-width: 1em;
height: 20px;
overflow-y: auto;
}
</style>
<tbody class=\"custom_field #{extra_class}\" data-key=\"#{k}\">
#{other_first_rows}
#{multi_lang_tag}
#{require_ask_tag}
#{tmp_field_select_tag_for_ask}
#{multi_lang_prompt_tag}
#{multi_lang_default_option}
#{options_area}
</tbody>"
else
not_editable = k.to_s.include?('default@')
hint_text = ""
if not_editable
hint_text = "<div style=\"font-weight: bold;\">" + t('ask.this_field_is_default_custom_fields') + "</div>"
end
disabled_attr = (not_editable ? 'disabled' : nil)
multi_lang_tag = multiple_lang_tag_for_ask(k,'text_field','field',v['field'],{placeholder: t('ask.field_name'), title: t('ask.field_name'), disabled: disabled_attr})
tmp_field_select_tag_for_ask = field_select_tag_for_ask(k,'type',markups,v['type'],{:onchange=>'check_available_setting_block(this)', :disabled=>disabled_attr})
key = hidden_field_tag "#{get_input_name_for_ask}[#{k}][key]",k,{'class' => 'key'}
options_hash = Hash(v['options'])
all_new_options = options_hash.collect do |key,value|
tmp = create_delete_button_for_ask('delete_added_select_option').html_safe+hidden_field_tag("#{get_input_name_for_ask}[#{k}][options][#{key}][disabled]",value['disabled'],{'class' => 'disabled_field'})
hidden_style = value['disabled'] == 'true' ? {style: 'display:none;'} : {}
"#{multiple_lang_tag_for_ask(k,'text_field',"options][#{key}",value,{ placeholder: t('ask.option_name'), class: 'option_name_field', title: t('ask.option_name'), disabled: disabled_attr},tmp,hidden_style,true)}"
end.join
tmp_count = {}
options_hash.each{|k,v| v.each{|l,vv| tmp_count[l] = tmp_count[l].to_i + 1 if vv.present?}}
current_locale = I18n.locale.to_s
maximum_locale = tmp_count.sort_by{|k,v| [v, k == current_locale]}[0][0] rescue nil
maximum_locale = I18n.locale.to_s if maximum_locale.nil?
locale_options_for_field = options_hash.map.with_index{|(k, v), i| [v[maximum_locale], i] rescue ""}
is_selection_field = ['select','radio_button','checkbox'].include?(v['type'])
active_class = is_selection_field ? ' active' : ''
active_prompt_class = (v['type'] != 'instructions' ? ' active' : '')
multi_lang_prompt_tag = "<div class=\"prompt_word#{active_prompt_class}\">#{multiple_lang_tag_for_ask(k,'text_field','prompt_word',v['prompt_word'],{ placeholder: t('ask.prompt_word'), title: t('ask.prompt_word'), disabled: disabled_attr})}</div>"
multi_lang_default_option = "<div class=\"default_option#{active_class}\">#{field_select_tag_for_ask(k,'default_option',locale_options_for_field,v['default_option'],{ title: t('ask.default_option'), class: 'default_option_select', disabled: disabled_attr, data: {locale: maximum_locale}, prompt: I18n.t('ask.please_select')})}</div>"
instructions_text_area = "<div class=\"instructions_text_area#{v['type'] == 'instructions' ? '' : ' hide'}\">#{multiple_lang_tag_for_ask(k,'text_area','instructions',v['instructions'],{ placeholder: t('ask.prompt_word'), title: t('ask.prompt_word'), class: 'ckeditor', disabled: disabled_attr})}</div>"
require_ask_tag = "<div>#{t('ask.required')}:&nbsp;&nbsp;#{field_radio_button_tag(k,'required','true',v['required']=='true',{disabled: disabled_attr})}#{t('ask.yes')}#{field_radio_button_tag(k,'required','false',v['required']!='true',{disabled: disabled_attr})}#{t('ask.no')}</div>"
tmp = "<div class=\"add_new_options#{active_class}\">#{all_new_options}<input class=\"btn btn-info\" type=\"button\" value=\"#{t('ask.add_new_options')}\" onclick=\"add_new_options_for_field(this,#{k})\"></div>"
field_html = "<tr class=\"custom_field #{extra_class}\" data-key=\"#{k}\">
<td>
#{other_first_rows}
#{hint_text}
#{multi_lang_tag}
#{require_ask_tag}
#{tmp_field_select_tag_for_ask}<br>
#{multi_lang_prompt_tag}
#{multi_lang_default_option}
#{instructions_text_area}
#{time_setting_block(k,v)}
#{tmp}
#{key}
</td>
<td>
#{create_delete_button_for_ask('delete_field_func')}
</td>
</tr>"
end
end
def create_delete_button_for_ask(func_name)
"<input class=\"btn btn-danger\" type=\"button\" value=\"#{t('delete_')}\" onclick=\"#{func_name}(this)\">"
end
def page_for_askquestion(askquestion)
ann_page = nil
pages = Page.where(:module=>'ask')
pages.each do |page|
if page.categories.count ==1
if page.categories.include?(askquestion.category.id.to_s)
ann_page = page
end
end
break if !ann_page.nil?
end
if ann_page.nil?
pages.each do |page|
if page.categories.include?(askquestion.category.id.to_s)
ann_page = page
end
break if !ann_page.nil?
end
end
ann_page = pages.first if ann_page.nil?
request.protocol+(request.host_with_port+ann_page.url+'/'+askquestion.to_param).gsub('//','/') rescue "/"
end
def process_format_text(text,custom_fields,show_recommendation=false)
customs = text.scan(/<tr(?:(?!<tr).)+\{custom\}(?:(?!<tr).)+<\/tr>/m).uniq
if customs.length != 0
custom_exist_nums = []
custom_exists = text.scan(/{custom\d+}/)
custom_exists.each do |custom_exist|
k = custom_exist[6...-1].to_i - 1
custom_exist_nums << k
end
customs.each do |custom|
tmp = custom_fields.keys.collect.with_index do |k,i|
if custom_exist_nums.exclude?(i)
tp = custom.gsub(/{custom}/,"{custom#{i+1}}")
tp = tp.gsub(/{custom_title}/,"{custom#{i+1}_title}")
tp
else
nil
end
end.compact.join
text = text.gsub(custom,tmp)
end
end
format_texts = text.scan(/{\w+\|*\w+}/).uniq
format_texts.each do |format_text|
if format_text[-7...-1] == '_title'
case format_text[1...-7]
when /custom\d+/
i = format_text.scan(/\d+/)[0].to_i - 1
k = custom_fields.keys[i] rescue nil
if !k.blank?
text_tp = custom_fields[k]['field'][I18n.locale] rescue ''
text = text.gsub(format_text,text_tp)
end
when 'title'
text = text.gsub(format_text,I18n.t('title'))
when 'ask_time'
text = text.gsub(format_text,I18n.t('ask.ask_time'))
when 'category'
text = text.gsub(format_text,I18n.t('mongoid.attributes.ask_question.ask_category_id'))
when 'name','sex','mail','phone','appointment','agree_show'
text = text.gsub(format_text,I18n.t("mongoid.attributes.ask_question.#{format_text[1...-7]}"))
end
else
case format_text[1...-1]
when 'ask_time'
text = text.gsub(format_text,@ask_question.created_at.strftime('%Y/%m/%d %H:%M'))
when 'title','name','mail','phone','appointment'
text = text.gsub(format_text,@ask_question.send(format_text[1...-1]).to_s)
when 'category'
cat = Category.find(@ask_question.category_id).title rescue ''
text = text.gsub(format_text,cat)
when 'name|mask'
name_tp = @ask_question.name.to_s
if name_tp.length>1
name_tp = name_tp[0] + '*'*(name_tp.length-1)
end
text = text.gsub(format_text,name_tp)
when 'sex'
sex = @ask_question.sex
if ['male','female'].include? sex.to_s
sex = I18n.t("mongoid.attributes.ask_question.#{sex}")
else
sex = ''
end
text = text.gsub(format_text,sex)
when 'agree_show'
if @ask_question.agree_show
text = text.gsub(format_text,I18n.t('ask.yes'))
else
text = text.gsub(format_text,I18n.t('ask.no'))
end
when 'recommendation'
if show_recommendation
recommendation_tp = "<h3>" + I18n.t('ask.recommendation') + "</h3><p>" + @ask_question.recommendation.to_s.gsub("\n", "<br/>").gsub("\r", "") + "</p>".html_safe
text = text.gsub(format_text,recommendation_tp)
else
text = text.gsub(format_text,"")
end
when /custom\d+\|format/
i = format_text.scan(/\d+/)[0].to_i - 1
k = custom_fields.keys[i] rescue nil
if !k.blank?
v = custom_fields[k] rescue {}
text_tp = Admin::AsksHelper.show_on_front(k,v,@ask_question,true,true)
text = text.gsub(format_text,text_tp.to_s)
end
when /custom\d+/
i = format_text.scan(/\d+/)[0].to_i - 1
k = custom_fields.keys[i] rescue nil
if !k.blank?
v = custom_fields[k] rescue {}
text_tp = Admin::AsksHelper.show_on_front(k,v,@ask_question,true)
text = text.gsub(format_text,text_tp.to_s)
end
end
end
end
text
end
# Adding this helper method for PDF generation
def generate_pdf(ask_question, show_recommendation=false)
@ask_question = ask_question # Set instance variable for process_format_text
# Get settings similar to print method
print_setting = AskCategoryPrintSetting.where(category_id: ask_question.category_id.to_s).first
print_setting = AskPrintSetting.first if print_setting.nil?
# Get custom fields
ask_setting = AskCategorySetting.where(category_id: ask_question.category_id.to_s, :use_default.ne=>true).first
ask_setting = AskSetting.first if ask_setting.nil?
custom_fields = ask_setting.custom_fields
print_text = print_setting.print_format rescue ''
print_text = "<style>img{width: 100%;}</style>"+ print_text
print_text = process_format_text(print_text,custom_fields, show_recommendation)
# Render the print format explanation partial
html_content = <<-HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
font-family: Arial, sans-serif;
font-size: 12px;
line-height: 1.4;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
#{print_text}
</body>
</html>
HTML
# Generate PDF using WickedPDF
WickedPdf.new.pdf_from_string(
html_content,
encoding: 'UTF-8',
page_size: 'A4',
margin: {
top: 20,
bottom: 20,
left: 20,
right: 20
},
print_media_type: true,
zoom: 1,
dpi: 300,
footer: {
font_size: 8,
right: '[page] of [topage]',
spacing: 5
}
)
end
end