# encoding: utf-8
class Admin::AsksController < OrbitAdminController
helper Admin::AsksHelper
before_action ->(module_app = @app_title) { set_variables module_app }
before_action :set_askquestion, only: [:edit, :destroy, :update, :print]
layout :compute_layout
def compute_layout
if action_name=='print'
false
else
'back_end_with_jquery_first'
end
end
def initialize
super
@app_title = "ask"
end
def print_setting
@set = AskPrintSetting.first
@set = AskPrintSetting.create if @set.nil?
@url = print_setting_save_admin_asks_path
end
def print_setting_save
locale = I18n.locale
set = AskPrintSetting.first
set.update_attributes(print_format: params[:ask_print_setting][:print_format],save_name: params[:ask_print_setting][:save_name])
redirect_to "/#{locale}/admin/asks"
end
def category_print_setting_save
locale = I18n.locale
set = AskCategoryPrintSetting.where(category_id: params['category_id']).first
set = AskCategoryPrintSetting.create if set.nil?
set.update_attributes(print_format: params['print_format'],save_name: params['save_name'],category_id: params['category_id'])
redirect_to "/#{locale}/admin/asks/category_setting"
end
def filter_fields(categories, tags)
{
:situation=>[{:title=>"ask.is_waiting",:id=>"is_waiting"},{:title=>"ask.is_processed",:id=>"is_processed"},{:title=>"ask.is_referral",:id=>"is_referral"},{:title=>"ask.is_published",:id=>"is_published"}],
:category=>categories.map{|c| {:title=>(c.title.blank? ? " " : c.title), :id=>c.id}},
:identity=>tags.map{|tag| {:title=>(tag.name.blank? ? " " : tag.name), :id=>tag.id}}
}
end
# 抓取網址的狀態參數
def filter2(type)
case type
when "situation"
params[:filters][:situation].blank? ? [] : params[:filters][:situation] rescue []
when "identity"
params[:filters][:identity].blank? ? [] : params[:filters][:identity] rescue []
end
end
def setting_save
locale = I18n.locale
ask_setting = AskSetting.first
p1 = ask_setting_params(ask_setting,'ask_setting')
ask_setting.update_attributes(p1)
redirect_to "/#{locale}/admin/asks"
end
def category_setting_save
locale = I18n.locale
ask_setting = AskCategorySetting.where(category_id: params['category_id']).first
ask_setting = AskCategorySetting.create(category_id: params['category_id']) if ask_setting.nil?
p1 = ask_setting_params(ask_setting,'ask_category_setting')
ask_setting.update_attributes(p1)
redirect_to "/#{locale}/admin/asks/category_setting"
end
def setting
@ask_setting = AskSetting.first
@ask_setting = AskSetting.create() if @ask_setting.nil?
@url = setting_save_admin_asks_path
end
def get_new_setting_index
ask_setting_index = AskSettingIndex.first
ask_setting_index = AskSettingIndex.create() if ask_setting_index.nil?
ask_setting_index.key = ask_setting_index.key + 1
ask_setting_index.save
render :json => {key: ask_setting_index.key.to_i}
end
def get_new_category_setting_index
ask_setting_index = AskCategorySettingIndex.where(category_id: params['category_id']).first
ask_setting_index = AskCategorySettingIndex.create(category_id: params['category_id']) if ask_setting_index.nil?
ask_setting_index.key = ask_setting_index.key + 1
ask_setting_index.save
render :json => {key: ask_setting_index.key.to_i}
end
def index
AskPrintSetting.create() if AskPrintSetting.first.nil?
@ask_setting = AskSetting.first
@ask_setting = AskSetting.create() if @ask_setting.nil?
@tags = @module_app.tags
@categories = @module_app.categories
@filter_fields = filter_fields(@categories, @tags)
# 列表欄位
@table_fields = [:situation, :category, 'title' , 'ask.name', 'ask.phone', 'ask.appointment','ask.created_at']
# 列表排序
# debugger
if filter2("situation").blank? and filter2("identity").blank?
@askquestions = AskQuestion.order_by(sort)
.with_categories(filters("category"))
elsif filter2("situation").blank?
@askquestions = AskQuestion.order_by(sort)
.with_categories(filters("category"))
.any_in(:identity => filter2("identity"))
elsif filter2("identity").blank?
@askquestions = AskQuestion.order_by(sort)
.with_categories(filters("category"))
.any_in(:situation => filter2("situation"))
else
@askquestions = AskQuestion.order_by(sort)
.with_categories(filters("category"))
.any_in(:identity => filter2("identity"))
.any_in(:situation => filter2("situation"))
end
# 分頁
@askquestions = search_data(@askquestions,[:title]).page(params[:page]).per(10)
if request.xhr?
render :partial => "index"
end
end
def search_tag(tag)
Tag.find(tag).name_translations{}
end
def category_setting
@categories = @module_app.categories
@category_ids = @categories.pluck(:id)
@category_titles = @categories.pluck(:title).collect{|v| v[I18n.locale]}
@category_added = AskCategorySetting.all.asc(:created_at)
@category_added_ids = @category_added.pluck(:category_id)
@category_not_add_index = @category_ids.to_enum.with_index.select{|v,i| @category_added_ids.exclude? v.to_s}.collect{|v,i| i}
@category_not_add = @category_titles.values_at(*@category_not_add_index).zip(@category_ids.values_at(*@category_not_add_index))
@category_print_added = AskCategoryPrintSetting.all.asc(:created_at)
@category_print_added_ids = @category_print_added.pluck(:category_id)
@category_print_not_add_index = @category_ids.to_enum.with_index.select{|v,i| @category_print_added_ids.exclude? v.to_s}.collect{|v,i| i}
@category_print_not_add = @category_titles.values_at(*@category_print_not_add_index).zip(@category_ids.values_at(*@category_print_not_add_index))
end
def get_category_setting_field
ask_setting = AskCategorySetting.find(params['id'])
render partial: 'category_setting_field',locals: {ask_setting: ask_setting}
end
def category_print_setting_delete
print_setting = AskCategoryPrintSetting.find(params['id'])
print_setting.destroy
locale = I18n.locale
redirect_to "/#{locale}/admin/asks/category_setting"
end
def category_setting_delete
ask_setting = AskCategorySetting.find(params['id'])
ask_setting.destroy
locale = I18n.locale
redirect_to "/#{locale}/admin/asks/category_setting"
end
def process_format_text(text,custom_fields)
customs = text.scan(/
/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]
custom_exist_nums << k
end
customs.each do |custom|
tmp = custom_fields.keys.select{|key| custom_exist_nums.exclude? key}.collect do |k|
tp = custom.gsub(/{custom}/,"{custom#{k}}")
tp = tp.gsub(/{custom_title}/,"{custom#{k}_title}")
tp
end.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
k = custom_fields.keys[i-1]
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.ask_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 /custom\d+\|format/
i = format_text.scan(/\d+/)[0].to_i
k = custom_fields.keys[i-1]
if !k.blank?
v = custom_fields[k] rescue {}
text_tp = Admin::AsksHelper.show_on_front(k,v,@ask_question.custom_values[k],true,true)
text = text.gsub(format_text,text_tp.to_s)
end
when /custom\d+/
i = format_text.scan(/\d+/)[0].to_i
k = custom_fields.keys[i-1]
if !k.blank?
v = custom_fields[k] rescue {}
text_tp = Admin::AsksHelper.show_on_front(k,v,@ask_question.custom_values[k],true)
text = text.gsub(format_text,text_tp.to_s)
end
end
end
end
text
end
def print
@print_setting = AskCategoryPrintSetting.where(category_id: @ask_question.category_id.to_s).first
@print_setting = AskPrintSetting.first if @print_setting.nil?
@save_name = @print_setting.save_name rescue ''
@print_text = @print_setting.print_format rescue ''
ask_setting = AskCategorySetting.where(category_id: @ask_question.category_id.to_s).first
ask_setting = AskSetting.first if ask_setting.nil?
custom_fields = ask_setting.custom_fields
@print_text = process_format_text(@print_text,custom_fields)
@save_name = process_format_text(@save_name,custom_fields)
end
def edit
@ask_setting = AskCategorySetting.where(category_id: @ask_question.category_id.to_s).first
@ask_setting = AskSetting.first if @ask_setting.nil?
@url = admin_ask_path(@ask_question)
end
def destroy
locale = I18n.locale
@ask_question.destroy
redirect_to "/#{locale}/admin/asks"
end
def update
locale = I18n.locale
temp_params = params.require(:ask_question).permit!
all_to_save = []
ask_setting = AskCategorySetting.where(category_id: params['ask_question']['category_id']).first
if ask_setting.nil?
ask_setting = AskSetting.first
ask_setting = AskSetting.create() if ask_setting.nil?
end
ask_setting.custom_fields.select{|k,v| v['type']=='file' || v['type']=='image'}.each do |k,v|
file = temp_params['custom_values'][k] rescue nil
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
else
temp_params['custom_values'][k] = @ask_question.custom_values[k] rescue nil
end
end
flag = @ask_question.save
if flag
all_to_save.each do |to_save|
flag = flag && to_save[1].save
temp_params['custom_values'][to_save[0]] = [temp_params['custom_values'][to_save[0]].original_filename ,to_save[1].file.url]
end
end
@ask_question.update_attributes(temp_params)
if @ask_question.send_email?
build_email(@ask_question)
end
redirect_to "/#{locale}/admin/asks", notice: t('ask.reply_success')
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
@mail_sentdate = DateTime.now
site = Site.first
mail_from = site['title'][site['default_locale']]
email_er.email.update_attributes(
:mail_lang=> site['default_locale'],
:create_user=>current_user,
:mail_sentdate=>@mail_sentdate,
:module_app=>@module_app,
:mail_to=>@group_mail,
:mail_subject=>mail_from+" #{t('ask.reply')}:",
:template=>'admin/asks/email',
:template_data=>{
"reply" => email_er.reply
}
)
OrbitMailer.set_mail(email_er.email).deliver
end
def export
end
def do_export
Rails.application.config.mongoid.use_activesupport_time_zone = true
date_start = "#{params[:export]['start(1i)']}-#{params[:export]['start(2i)']}-#{params[:export]['start(3i)']}"
date_end = "#{params[:export]['end(1i)']}-#{params[:export]['end(2i)']}-#{params[:export]['end(3i)']}"
@ask_questions = AskQuestion.where(:created_at.gte => date_start.to_datetime, :created_at.lte => date_end.to_datetime+1)
csv = CSV.generate do |csv|
csv << [ t('category'),
AskQuestion.human_attribute_name(:name),
AskQuestion.human_attribute_name(:identity),
AskQuestion.human_attribute_name(:mail),
AskQuestion.human_attribute_name(:phone),
AskQuestion.human_attribute_name(:fax),
AskQuestion.human_attribute_name(:title),
AskQuestion.human_attribute_name(:content),
AskQuestion.human_attribute_name(:reply),
AskQuestion.human_attribute_name(:comment)]
@ask_questions.each do |ask_question|
Tag.where({:id => ask_question[:identity]}).each do |tag|
csv << [ ask_question.category.title,
ask_question.name,
tag.name,
ask_question.mail,
ask_question.phone,
ask_question.fax,
ask_question.title,
ask_question.content,
ask_question.reply,
ask_question.comment ]
end
end
end
send_data csv.encode('Big5'), type: 'text/csv', filename: "Questions-#{date_start}-#{date_end}.csv"
end
def set_askquestion
@ask_question = AskQuestion.find(params[:id])
end
private
def ask_setting_params(ask_setting,collection_name)
param = params.require(collection_name).permit!
param_clone = param.clone
param_clone['default_setting'].each { |k, v| param_clone['default_setting'][k] = (v == 'true'? true : false) }
param_clone.delete('custom_fields')
custom_fields = ask_setting['custom_fields'].clone
params_custom_fields = (params.require(collection_name).require('custom_fields') rescue {})
params_custom_fields.each do |k,v|
custom_fields[k] = v
end
field_to_delete = params['delete_field'].to_s.split(',').select{|v| !v.empty?}
field_to_delete.each do |k|
if custom_fields.keys.include? k
custom_fields[k]['delete'] = true
end
end
param_clone.merge({custom_fields: custom_fields})
end
end