ask/app/controllers/asks_controller.rb

899 lines
35 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.

class AsksController < ApplicationController
helper Admin::AsksHelper
include Admin::AsksHelper
include ActionView::Helpers::FormHelper
include ActionView::Helpers::FormOptionsHelper
helper ActionView::Helpers::UrlHelper
include ActionController::RequestForgeryProtection
include RuCaptcha::ViewHelpers
FrontendMethods = ["thank", "sorry", "see_email"]
def widget
subpart = OrbitHelper.get_current_widget
case subpart.widget_type
when /.*_form/
read_more_page = Page.where(id: subpart.read_more_page_id).first || Page.where(:module => 'ask').first
referer_url = read_more_page ? "/#{I18n.locale}#{read_more_page.url}" : "/#{I18n.locale}/asks"
module_app = ModuleApp.where(:key => "ask").first
if OrbitHelper.widget_categories.include?('all')
categories = module_app.categories.enabled
else
categories = Category.where(:id.in=>OrbitHelper.widget_categories).enabled
end
unless Category.respond_to?(:sorted)
if (module_app.asc rescue true)
categories = categories.sort_by{|category| (category.sort_number.to_i rescue category.id)}
else
categories = categories.sort_by{|category| (-category.sort_number.to_i rescue category.id)}
end
end
tags = module_app.tags
ask_question = AskQuestion.new
locale = I18n.locale
category_ids = categories.collect{|v| v.id.to_s}
ask_settings = AskCategorySetting.enabled.where(:category_id.in=> category_ids).to_a
first_category_id = category_ids.first
ask_setting = ask_settings.select{|a| a.category_id == first_category_id}.first
if ask_settings.count != categories.count
ask_settings = [AskSetting.first]+ask_settings
end
if ask_setting.nil?
ask_setting = AskSetting.first
@default_ask_setting = ask_setting
else
@default_ask_setting = AskSetting.first
end
all_fields = cal_form_from_setting(ask_setting,categories)
request = OrbitHelper.request
csrf_value = OrbitHelper.request.session[:_csrf_token] || SecureRandom.base64(32)
token_tag = hidden_field_tag('authenticity_token',csrf_value)
switch_form = cal_switch_form(ask_settings,categories,token_tag,referer_url, OrbitHelper.params[:id])
email_regex = @default_ask_setting.get_email_regex(true)
{
'fields' => all_fields,
'extras'=>{
'switch_form' => switch_form,
'email_regex' => email_regex
}
}
when /.*_pub.*/
data_count = OrbitHelper.widget_data_count.to_i
category_ids = OrbitHelper.widget_categories || []
if category_ids.blank?
module_app = ModuleApp.where(:key => "ask").first
category_ids = module_app.categories.enabled.pluck(:id)
end
default_ask_setting = AskSetting.first
ask_settings_info = category_ids.map do |category_id|
ask_setting = AskCategorySetting.enabled.where(category_id: category_id.to_s).first
ask_setting = default_ask_setting if ask_setting.nil?
custom_fields = ask_setting.custom_fields.map do |k,field_info|
options = nil
multiple = false
ext_type = 0
case field_info["type"]
when "select", "radio_button", "checkbox"
multiple = (field_info["type"] == "checkbox")
options = field_info[:options].map do |i, opt_vals|
opt_val = opt_vals[I18n.locale]
if opt_val.blank?
opt_val = opt_vals.values.select{|s| s.present?}
end
[i, opt_val]
end.to_h
when "file", "image"
ext_type = 1
when "date"
ext_type = 2
end
[k, {
options: options,
multiple: multiple,
ext_type: ext_type
}]
end
if custom_fields.present?
sort_number = ask_setting.get_cache_sort_number
custom_fields = custom_fields.sort_by do |k, v|
if k.start_with?('default@')
sort_number[k]
else
sort_number["custom@#{ask_setting.id}@#{k}"]
end
end
end
[category_id,
{
setting: ask_setting,
custom_fields: custom_fields.to_h
}
]
end.to_h
ask_questions = AskQuestion.where(:situation => 'is_published', :category_id.in => category_ids)
if data_count != 0
ask_questions = ask_questions.page(1).per(data_count)
end
ask_index_page = OrbitHelper.widget_more_url rescue nil
ask_questions = ask_questions.collect do |v|
url = ((ask_index_page+"?item=#{v.id}") rescue "javascript:alert('#{t('ask.no_index_page')}')")
category_id = v.category_id.to_s
extra_info = ask_settings_info[category_id]
d = {
"category_id" => category_id,
"link_url" => link_to(v.title,"#{url}",title: v.title),
"identity" => v[:identity],
"title" => v.title,
"name" => v.name,
"sex" => v.sex,
"content" => v.content,
"category" => v.category.title
}
ext_fields = [
{
"fk" => "ask-sex-#{v.sex}",
"fv" => ""
}
]
if extra_info.present? && extra_info[:custom_fields].present?
ext_fields += extra_info[:custom_fields].map do |k, field_opt|
fv = v.custom_values[k]
if fv.present?
options = field_opt[:options]
if options
if field_opt[:multiple]
fv = fv.values rescue []
else
fv = Array(fv)
end
fv = fv.map{|vv| options[vv]}.join("<br>").html_safe
else
case field_opt[:ext_type]
when 1 # file, image
fv = "<a href=\"#{fv[1]}\">#{fv[0]}</a>".html_safe
when 2 # date
fv = fv["datetime"].values[0].values rescue []
if fv.count == 2
fv = fv[0].to_s.gsub('-', '/') + " ~ " + fv[1].to_s.gsub('-', '/')
else
fv = fv[0].to_s.gsub('-', '/')
end
end
end
end
{
"fk"=> "ask-q-#{k}",
"fv"=> fv
}
end
end
d["ext_fields"] = ext_fields
d
end
{
'ask_questions' => ask_questions,
'extras' => {'more_title'=>I18n.t('ask.more_title'),
'more_href'=>ask_index_page}
}
else
data_count = OrbitHelper.widget_data_count.to_i
category_ids = OrbitHelper.widget_categories || []
if category_ids.blank?
module_app = ModuleApp.where(:key => "ask").first
category_ids = module_app.categories.enabled.pluck(:id)
end
ask_questions = AskQuestion.where(:situation => 'is_published', :category_id.in => category_ids)
if data_count != 0
ask_questions = ask_questions.page(1).per(data_count)
end
ask_index_page = OrbitHelper.widget_more_url rescue nil
ask_questions = ask_questions.collect do |v|
url = ((ask_index_page+"?item=#{v.id}") rescue "javascript:alert('#{t('ask.no_index_page')}')")
{'td'=> [
{'content' =>v.category.title},
{'content' => link_to(v.title,"#{url}",title: v.title)}
]
}
end
{
'ask_questions' => ask_questions,
'th' => [{'td'=>t('categories')},{'td'=>t('title')}],
'extras' => {'more_title'=>I18n.t('ask.more_title'),
'more_href'=>ask_index_page}
}
end
end
def get_layout_type
@params = OrbitHelper.params
page = Page.where(url:@params['url']).first
@layout_type = 'index'
if page.methods.include? 'select_option_items'.to_sym
ModuleApp.all.select{|tmp| tmp.key.to_s=='ask'}.each do |modile_app|
@show_option_items = modile_app.show_option_items rescue nil
end
page.select_option_items.each do |select_option_item|
if !(@show_option_items.nil?) && select_option_item.field_name == @show_option_items.keys.first.to_s
value = YAML.load(select_option_item.value)
I18n.with_locale(:en) do
if value[locale] == t('ask.widget.index')
@layout_type = 'index'
elsif value[locale] == t('ask.is_published')
@layout_type = 'published_index'
end
end
end
end
end
end
def initialize
super
@app_title = 'ask'
self.request = OrbitHelper.request
end
def show
ask_question = AskQuestion.where(id: @params['item']).first
ask_setting = AskCategorySetting.enabled.where(category_id: ask_question.category_id.to_s).first
ask_setting = AskSetting.first if ask_setting.nil?
{'ask_question' => ask_question,'layout_type'=>'show','ask_setting'=>ask_setting}
end
def index
@params = OrbitHelper.params
referer_url = OrbitHelper.request.path
if @params['item'].to_s.empty?
get_layout_type
else
@layout_type = 'show'
end
if @layout_type == 'index'
module_app = ModuleApp.where(:key => "ask").first
if OrbitHelper.page_categories.include? 'all'
categories = module_app.categories.enabled
else
categories = Category.where(:id.in=>OrbitHelper.page_categories).enabled
end
unless Category.respond_to?(:sorted)
if (module_app.asc rescue true)
categories = categories.sort_by{|category| (category.sort_number.to_i rescue category.id)}
else
categories = categories.sort_by{|category| (-category.sort_number.to_i rescue category.id)}
end
end
category_ids = categories.collect{|v| v.id.to_s}
ask_settings = AskCategorySetting.enabled.where(:category_id.in=> category_ids).to_a
first_category_id = category_ids.first
ask_setting = ask_settings.select{|a| a.category_id == first_category_id}.first
if ask_settings.count != categories.count
ask_settings = [AskSetting.first]+ask_settings
end
if ask_setting.nil?
ask_setting = AskSetting.first
ask_setting = AskSetting.create() if ask_setting.nil?
@default_ask_setting = ask_setting
else
@default_ask_setting = AskSetting.first
end
csrf_value = OrbitHelper.request.session[:_csrf_token] || SecureRandom.base64(32)
token_tag = hidden_field_tag('authenticity_token',csrf_value)
switch_form = cal_switch_form(ask_settings,categories,token_tag,referer_url, @params[:id])
tags = module_app.tags
ask_question = AskQuestion.new(id: nil)
email_regex = @default_ask_setting.get_email_regex(true)
{
'layout_type' => 'index',
'ask_question' => ask_question,
'categories' => categories,
'tags' => tags,
'module_app' => module_app,
'switch_form' => switch_form,
'ask_setting' => ask_setting,
'default_ask_setting' => @default_ask_setting,
'email_regex' => email_regex
}
elsif @layout_type == 'published_index'
page_number = OrbitHelper.page_number.to_i
page_number = 1 if page_number == 0
page_data_count = OrbitHelper.page_data_count.to_i
category_ids = OrbitHelper.page_categories || []
if category_ids.blank?
module_app = ModuleApp.where(:key => "ask").first
category_ids = module_app.categories.enabled.pluck(:id)
end
default_ask_setting = AskSetting.first
ask_settings_info = category_ids.map do |category_id|
ask_setting = AskCategorySetting.enabled.where(category_id: category_id.to_s).first
ask_setting = default_ask_setting if ask_setting.nil?
custom_fields = ask_setting.custom_fields.map do |k,field_info|
options = nil
multiple = false
ext_type = 0
case field_info["type"]
when "select", "radio_button", "checkbox"
multiple = (field_info["type"] == "checkbox")
options = field_info[:options].map do |i, opt_vals|
opt_val = opt_vals[I18n.locale]
if opt_val.blank?
opt_val = opt_vals.values.select{|s| s.present?}
end
[i, opt_val]
end.to_h
when "file", "image"
ext_type = 1
when "date"
ext_type = 2
end
[k, {
options: options,
multiple: multiple,
ext_type: ext_type
}]
end
if custom_fields.present?
sort_number = ask_setting.get_cache_sort_number
custom_fields = custom_fields.sort_by do |k, v|
if k.start_with?('default@')
sort_number[k]
else
sort_number["custom@#{ask_setting.id}@#{k}"]
end
end
end
[category_id,
{
setting: ask_setting,
custom_fields: custom_fields.to_h
}
]
end.to_h
ask_questions = AskQuestion.where(:situation => 'is_published', :category_id.in => category_ids)
if page_data_count != 0
ask_questions = ask_questions.page(1).per(page_data_count)
end
{
'layout_type' => 'published_index',
'ask_questions' => ask_questions,
'ask_settings_info' => ask_settings_info,
'url' => @params['url']
}
else
show
end
end
def create
if !params[:referer_url].blank? && !params[:referer_url].to_s.start_with?("/")
render :file => "#{Rails.root}/app/views/errors/403.html", :layout => false, :status => 403 and return
end
temp_params = create_params
if temp_params[:id].present?
@ask_question = AskQuestion.where(id: temp_params[:id]).first
if @ask_question.nil?
render_404 and return
end
else
@ask_question = AskQuestion.new(:ip=>request.remote_ip)
end
new_record = @ask_question.new_record?
all_to_save = []
ask_setting = AskCategorySetting.enabled.where(category_id: params['ask_question']['category_id']).first
override_sort_number = nil
if ask_setting && ask_setting.use_default
override_sort_number = ask_setting.default_sort_number
ask_setting = nil
end
if ask_setting.nil?
ask_setting = AskSetting.first
ask_setting = AskSetting.create() if ask_setting.nil?
end
@ask_setting = ask_setting
@must_verify_email = ask_setting.must_verify_email && new_record
if @must_verify_email
only_email = true
@ask_question.is_hidden = true
else
only_email = false
check_fields = ask_setting.default_setting.select{|k,v| v}.keys & ask_setting.default_setting_required.select{|k,v| v}.keys - AskSetting::No_required
unless new_record
@ask_question.is_hidden = false
check_fields.delete('mail')
end
flag = true
check_fields.each do |f|
next if f == 'ask_category_id' || f == 'recaptcha'
if temp_params[f].blank?
flag = false
break
end
end
end
custom_values = temp_params[:custom_values]
custom_values = {} if custom_values.nil?
if flag
check_custom_fields = ask_setting.custom_fields.select{|k,v| v["required"] == 'true' }
if check_custom_fields.count != 0
check_custom_fields.each do |k,v|
next if v['type'] == 'instructions'
tmp = custom_values[k]
v_type = v['type']
is_date = false
if v_type == "checkbox"
tmp = tmp.values rescue []
elsif v_type == 'date'
is_date = true
tmp = tmp["datetime"].values[0].values rescue []
end
if tmp.present?
if is_date && v["range_flag"] == 'true'
if (tmp.class != Array) || (tmp.select{|v| v.blank?}.count != 0)
flag = false
break
end
end
else
flag = false
break
end
end
end
end
if !flag && !only_email
redirect_to "#{params[:referer_url]}?method=sorry" and return
end
email_regex = ask_setting.get_email_regex
unless only_email
ask_setting.custom_fields.select{|k,v| v['type']=='file' || v['type']=='image'}.each do |k,v|
file = custom_values[k]
if !file.blank?
if v['type']=='image'
all_to_save += [[k,AskImage.new(file: file,ask_question_id: @ask_question.id)]]
else
all_to_save += [[k,AskFile.new(file: file,ask_question_id: @ask_question.id)]]
end
end
end
end
flag = !ask_setting.default_setting['recaptcha'] || gotcha_valid?
if flag && !only_email
all_to_save.each do |to_save|
flag = flag && to_save[1].save
custom_values[to_save[0]] = [custom_values[to_save[0]].original_filename ,to_save[1].file.url]
end
end
if (email_regex ? ::Regexp.new(email_regex).match(temp_params["mail"].to_s) : true) && flag
@disp_fields_infos = AskSetting.get_disp_fields_infos(true, ask_setting, true, override_sort_number, true)
@usage_rule = ask_setting.usage_rule
if temp_params['mail'].blank?
temp_params = temp_params.merge({
situation: AskTicketStatus::DefaultKeys[1]
})
end
@ask_question.update_attributes(temp_params)
if @must_verify_email
referer_url = "#{params[:referer_url]}?id=#{@ask_question.id}"
else
referer_url = nil
end
if @must_verify_email || (ask_setting.validate_enable && AskSafeEmail.where(:email=> @ask_question.mail).count == 0)
build_verification_email(@ask_question, referer_url)
else
@ask_question.update(:situation => AskTicketStatus::DefaultKeys[1])
build_email(@ask_question)
end
if @must_verify_email
redirect_to "#{params[:referer_url]}?method=see_email"
else
redirect_to "#{params[:referer_url]}?method=thank"
end
else
redirect_to "#{params[:referer_url]}?method=sorry"
end
end
def thank
acknowledgement = AskAcknowledgement.last
{
"acknowledgement" => acknowledgement
}
end
def sorry
{}
end
def see_email
end
def render_404
render :file => "#{Rails.root}/app/views/errors/404", :layout => false, :status => :not_found, :formats => [:html]
end
def verify_email
@ask_question = AskQuestion.where(:id=>params[:id]).first
if @ask_question.nil?
render_404 and return
elsif @ask_question.situation != AskTicketStatus::DefaultKeys[0]
@already_verify = true
else
@already_verify = false
@ask_question.update(:situation => AskTicketStatus::DefaultKeys[1])
AskSafeEmail.create(:email=> @ask_question.mail)
build_email(@ask_question)
end
end
def build_verification_email(email_er, referer_url)
email = Email.new
email.save
email_er.email_id = email.id
email_er.save
group_mail = email_er.mail
manager_emails = email_er.reviewer_emails
mail_sentdate = DateTime.now
site = current_site rescue Site.first
mail_from = site.title_translations[site.default_locale]
host_url = Site.first.root_url rescue "http://"
if host_url == "http://"
host_url = request.protocol + request.host_with_port
end
verify_url = "#{host_url}/#{I18n.locale}/xhr/asks/verify_email/#{email_er.id}"
verify_link = "<a title=\"#{t('ask.verify_link')}\" href=\"#{verify_url}\" target=\"_blank\">#{verify_url}</a>"
if referer_url
referer_url = host_url + referer_url
referer_link = "<a title=\"#{I18n.t('ask.go_to_form')}\" href=\"#{referer_url}\" target=\"_blank\">#{referer_url}</a>"
else
referer_link = nil
end
mail_subject = mail_from+": #{t('ask.email_verification_notification')}"
email_er.email.update_attributes(
:mail_lang=> site.default_locale,
:create_user=>(current_user rescue nil),
:mail_sentdate=>mail_sentdate,
:module_app=>@module_app,
:mail_to=>group_mail,
:mail_subject=>mail_subject,
:template=>'asks/email_verification',
:template_data=>{
"validation_email_content" => @ask_setting.validation_email_content,
"verify_link" => verify_link,
"referer_link" => referer_link,
"site_host" => host_url
},
:mail_reply_to => (manager_emails.empty? ? nil : manager_emails)
)
# email_er.email.deliver
end
def build_email(email_er)
email = Email.new
email.save
email_er.email_id = email.id
email_er.save
group_mail = email_er.mail
manager_emails = email_er.reviewer_emails
mail_sentdate = DateTime.now
site = current_site rescue Site.first
mail_from = site.title_translations[site.default_locale]
host_url = Site.first.root_url rescue "http://"
if host_url == "http://"
host_url = request.protocol + request.host_with_port
end
mail_subject = mail_from+" #{t('ask.new_question')}"
email_er.email.update_attributes(
:mail_lang=> site.default_locale,
:create_user=>(current_user rescue nil),
:mail_sentdate=>mail_sentdate,
:module_app=>@module_app,
:mail_to=>group_mail,
:mail_subject=>mail_subject,
:template=>'asks/email',
:template_data=>{
# "title" => email_er.title,
"name" => email_er.name,
"identity" => email_er[:identity],
"mail" => email_er.mail,
"phone" => email_er.phone,
# "fax" => email_er.fax,
# "content" => email_er.content
"appointment" => email_er.appointment,
"disp_fields_infos" => @disp_fields_infos,
"ask_question_id" => email_er.id.to_s,
"site_host" => host_url,
"usage_rule" => @usage_rule
},
:mail_reply_to => (manager_emails.empty? ? nil : manager_emails)
)
if !manager_emails.empty?
Email.new(
:mail_lang=> site.default_locale,
:create_user=>(current_user rescue nil),
:mail_sentdate=>mail_sentdate,
:module_app=>@module_app,
:mail_to=>manager_emails,
:mail_subject=>mail_subject+" #{group_mail}",
:template=>'asks/email',
:template_data=>{
# "title" => email_er.title,
"name" => email_er.name,
"identity" => email_er[:identity],
"mail" => email_er.mail,
"phone" => email_er.phone,
# "fax" => email_er.fax,
# "content" => email_er.content
"appointment" => email_er.appointment,
"disp_fields_infos" => @disp_fields_infos,
"ask_question_id" => email_er.id.to_s,
"site_host" => host_url,
"usage_rule" => @usage_rule,
"edit_url" => "#{host_url}/#{site.default_locale}/admin/asks/#{email_er.id}/edit"
}
).save
end
# email_er.email.deliver
end
def create_params
params.require(:ask_question).permit!
end
private
def cal_form_from_setting(ask_setting,categories,show_categories=false,filter_fields=nil)
is_cat_record = (ask_setting.class == AskCategorySetting)
override_sort_number = nil
if is_cat_record
category_id = ask_setting.category_id
if ask_setting.use_default
override_sort_number = ask_setting.default_sort_number
ask_setting = @default_ask_setting
if @default_fields
return @default_fields.sort_by{|h| override_sort_number[h['field']].to_i}
end
is_cat_record = false
end
else
category_id = (categories[0].id.to_s rescue '')
end
tmp_ask_cat_id = (is_cat_record ? ask_setting.id.to_s : '')
disp_fields_infos = AskSetting.get_disp_fields_infos(true, ask_setting, true, override_sort_number, true)
if filter_fields
disp_fields_infos = disp_fields_infos.select{|field, info| filter_fields.include?(field)}
end
# tmp = 'mongoid.attributes.ask_question'
all_fields = []
set_input_name_for_ask("ask_question")
has_ask_category_id = false
if ask_setting.must_verify_email && @ask_question.nil?
field = "mail"
field_name = "ask_question[#{field}]"
id = field_name
required = true
placeholder = @default_ask_setting.prompt_word(field)
f1 = {'style_html'=>''}
f1['content'] = text_field_tag(field_name,nil,data: (required ? {"fv-validation" => "required;check_email;", "fv-messages" => "必填欄位;Email不正確;"} : {}),required: required,placeholder: placeholder)
f1['field'] = field
f1['label'] = ask_label(id, @default_ask_setting.field_name("#{field}"),required.to_s)
all_fields << f1
field = "recaptcha"
id = "ask_rucaptcha"
f1 = {'style_html'=>''}
f1['content'] = "#{gotcha_error(:espeak=>true)}#{gotcha(id: id)}"
f1['field'] = field
f1['label'] = ask_label(id, @default_ask_setting.field_name("#{field}"),required.to_s)
all_fields << f1
all_fields << {'field'=>'must_verify_email','style_html'=>'display: block; text-align: center;','label'=>'','content'=> I18n.t('ask.must_verify_email')}
else
disp_fields_infos.each do |field, info|
if field.start_with?("default@")
k = is_cat_record ? field : field[8..-1]
v = ask_setting.custom_fields[k]
if v
field_name = info['trans']
if field_name.present?
id = "#{get_input_name_for_ask}[custom_values][#{k}]"
all_fields << {'field'=>field,'label'=>ask_label(id, field_name, v['required']),'content'=>show_on_front(k,v)}
end
end
elsif field.start_with?("custom@") && is_cat_record
if field.include?(tmp_ask_cat_id)
k = field[8+tmp_ask_cat_id.length..-1]
v = ask_setting.custom_fields[k]
if v
field_name = info['trans']
if field_name.present?
id = "#{get_input_name_for_ask}[custom_values][#{k}]"
all_fields << {'field'=>field,'label'=>ask_label(id, v['field'][I18n.locale],v['required']),'content'=>show_on_front(k,v)}
end
end
end
else
if field == 'ask_category_id'
has_ask_category_id = true
if show_categories || ask_setting.default_setting[field]
if categories.count > 1
id = "ask_question[category_id]"
all_fields << {'field'=>field,'style_html'=>'','label'=>ask_label(id, @default_ask_setting.field_name("ask_category_id"),'true'),'content'=>select_tag('ask_question[category_id]', options_for_select(categories.collect{|t| [ t.title, t.id ]}))}
else
all_fields << {'field'=>field,'style_html'=>'','label'=>ask_label(nil, @default_ask_setting.field_name("ask_category_id"),'true'),'content'=>"<span>#{(categories[0].title rescue '')}</span>"+hidden_field_tag('ask_question[category_id]', (categories[0].id.to_s rescue ''))}
end
else
all_fields << {'field'=>field,'style_html'=>'display: none;','label'=>'','content'=>hidden_field_tag('ask_question[category_id]', (categories[0].id.to_s rescue ''))}
end
else
if ask_setting.default_setting[field] || field == "usage_rule"
required = ask_setting.is_required(field)
f1 = {'style_html'=>''}
field_name = "ask_question[#{field}]"
placeholder = @default_ask_setting.prompt_word(field)
id = field_name
case field
when 'title'
f1['content'] = text_field_tag(field_name,nil,placeholder: placeholder,required: required)
when 'name'
f1['content'] = text_field_tag(field_name,nil,data: (required ? {"fv-validation" => "required;", "fv-messages" => "必填欄位;"} : {}),required: required,placeholder: placeholder)
when 'sex'
id += "_male"
f1['content'] = "<label class=\"radio-inline\">
#{radio_button_tag(field_name,'male', false, {required: required})}#{I18n.t('users.male')}
</label>
<label class=\"radio-inline\">
#{radio_button_tag(field_name,'female', false, {required: required})}#{I18n.t('users.female')}
</label>"
when 'mail'
if @ask_question
f1['content'] = @ask_question.mail
else
f1['content'] = text_field_tag(field_name,nil,data: (required ? {"fv-validation" => "required;check_email;", "fv-messages" => "必填欄位;Email不正確;"} : {}),required: required,placeholder: placeholder)
end
when 'phone'
f1['content'] = text_field_tag(field_name,nil,placeholder: placeholder,required: required)
when 'appointment'
if @appointment_idx.nil?
@appointment_idx = 0
else
@appointment_idx += 1
end
id = "ask_question_appointment_#{@appointment_idx}"
f1['content'] = "<div class=\"default_picker\">#{text_field_tag(field_name,nil,placeholder: placeholder,data: {format: 'yyyy/MM/dd hh:mm'},required: required, id: id)}</div>"
when 'recaptcha'
id = "ask_rucaptcha"
f1['content'] = "#{gotcha_error(:espeak=>true)}#{gotcha(id: id)}"
when 'usage_rule'
next if ask_setting.usage_rule.blank?
f1['content'] = ask_setting.usage_rule
when 'agree_show'
f1['content'] = check_box_tag(field_name, "1", false, {required: required})
when 'agree_usage'
f1['content'] = check_box_tag(field_name, "1", false, {required: required})
end
f1['field'] = field
f1['label'] = ask_label(id, @default_ask_setting.field_name("#{field}"),required.to_s)
all_fields << f1
end
end
end
end
if @ask_question
all_fields << {'field'=>'ask_question_id','style_html'=>'display: none;','label'=>'','content'=>hidden_field_tag('ask_question[id]', @ask_question.id)}
end
end
unless has_ask_category_id
all_fields << {'field'=>'ask_category_id','style_html'=>'display: none;','label'=>'','content'=>hidden_field_tag('ask_question[category_id]', category_id)}
end
unless is_cat_record
@default_fields = all_fields
end
all_fields
end
def cal_html(fields,token_tag,form_id,referer_url,is_hidden=true,ask_setting=None)
form_url = "/#{I18n.locale.to_s}/asks"
submit_tag = submit_tag(t('submit'), :class=> 'btn btn-primary', :id => 'button-mail')
close_tag = button_tag(t('cancel'), type: 'reset', :class=> 'btn')
multi_col_class = (ask_setting.title_layout>0 rescue false) ? ' multi-col' : ' single-col'
col_class = (ask_setting.title_layout==1 rescue false) ? ' col-sm-6' : ''
tmp = fields.collect do |field|
style_html = field['style_html']
label = field['label']
content = field['content']
"<div class=\"control-group#{col_class}\" style=\"#{style_html}\">
#{label}
<div class=\"controls\">
#{content}
</div>
</div>"
end.join
"<form id=\"#{form_id}\" action=\"#{form_url}\" enctype=\"multipart/form-data\" method=\"post\" class=\"form-horizontal ask-question-form#{multi_col_class}\" accept-charset=\"UTF-8\" style=\"#{is_hidden ? 'display: none;' : ''}\">
#{token_tag}
<div data-level=\"0\" data-list=\"fields\">
#{tmp}
</div>
<div class=\"form-actions\">
<input type=\"hidden\" name=\"referer_url\" value=\"#{referer_url}\">
#{submit_tag}
#{close_tag}
</div>
</form>"
end
def script_text
"<script type=\"text/javascript\">
$(document).ready(function(){
$('select[name=\"ask_question[category_id]\"]').change(function(){
var category_id = $(this).val()
$(this).parents('.ask-question').eq(0).find('select[name=\"ask_question[category_id]\"]').val(category_id)
var id
if ($('form#'+category_id).length != 0){
id = category_id
}
else{
id = 'ask-default-form'
}
if (id != $(this).parents('form').eq(0).attr('id')){
var self = $(this)
var old_controls = self.parents('form').eq(0).find('.control-group')
var old_inputs = old_controls.children('label').map(function(){
return $.trim($(this).text().replace(/\\\*/g,''));
}).get()
var new_controls = self.parents('.ask-question').eq(0).find('form#'+id).find('.control-group')
var new_inputs = new_controls.children('label').map(function(){
return $.trim($(this).text().replace(/\\\*/g,''));
}).get()
$(new_inputs).each(function(i,v){
var i0 = old_inputs.indexOf(v)
if (i0 != -1 && new_controls.eq(i).find('select#ask_question_category_id').length==0){
var new_ = new_controls.eq(i).find('.controls').eq(0),
old_ = old_controls.eq(i0).find('.controls').eq(0),
new_input = new_.find('input, select'),
old_input = old_.find('input, select');
if(new_input.length != 0 && old_input.length != 0){
if(new_input.length == old_input.length){
var old_clone = old_.clone();
old_clone.find('input, select').attr('name', new_input.attr('name'));
old_clone.replaceAll(new_);
}
}
}
})
self.parents('.ask-question').eq(0).find('form').hide()
self.parents('.ask-question').eq(0).find('form#'+id).show()
}
})
})
</script>"
end
def cal_switch_form(ask_settings,categories,token_tag,referer_url, ask_question_id)
switch_form = ''
default_idx = 0
if ask_question_id.present?
@ask_question = AskQuestion.where(:id=> ask_question_id).first
if @ask_question && !(@ask_question.is_hidden)
@ask_question = nil
end
if @ask_question
AskSafeEmail.create(:email=> @ask_question.mail) if AskSafeEmail.where(:email=> @ask_question.mail).count == 0
ask_settings = AskCategorySetting.enabled.where(:category_id=> @ask_question.category_id).to_a
if ask_settings.blank?
ask_settings = [AskSetting.first]
end
end
else
@ask_question = nil
end
if categories.count != 0
default_idx = ask_settings[1..-1].to_a.map{|a| a.category_id.to_s}.index(categories[0].id.to_s)
default_idx = default_idx.nil? ? 0 : default_idx + 1
end
@default_ask_setting ||= AskSetting.first
switch_form = script_text + ask_settings.collect.with_index do |ask_setting,i|
fields = cal_form_from_setting(ask_setting,categories,true)
is_hidden = (i != default_idx)
if ask_setting.class == AskSetting
form_id = 'ask-default-form'
else
form_id = ask_setting.category_id
end
cal_html(fields,token_tag,form_id,referer_url,is_hidden,ask_setting)
end.join
switch_form
end
end