ask/app/controllers/admin/asks_controller.rb

525 lines
21 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.

# encoding: utf-8
class Admin::AsksController < OrbitAdminController
helper Admin::AsksHelper
include 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 = nil
@cats_relations = get_categories_info
@category_id = (params[:category] || @cats_relations[0][0] rescue nil)
if @category_id.blank?
@set = AskPrintSetting.first
else
@set = AskCategoryPrintSetting.where(:category_id=>@category_id).first
@set = AskPrintSetting.first if @set.nil?
end
@set = AskPrintSetting.create if @set.nil?
@url = print_setting_save_admin_asks_path
end
def print_setting_save
locale = I18n.locale
if params[:ask_print_setting][:category_id].present?
set = AskCategoryPrintSetting.where(:category_id=>params[:ask_print_setting][:category_id]).first
set = AskCategoryPrintSetting.create(:category_id=>params[:ask_print_setting][:category_id]) if set.nil?
else
set = AskPrintSetting.first
end
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 switch_to_default_setting
if AskCategorySetting.where(:id=>params[:id]).update_all(:use_default=>params[:use_default] == "true").documents[0]["nModified"] != 0
render :json => {success: true}
else
render :json => {success: false}
end
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')
puts ask_setting.inspect
puts ["update!", p1]
ask_setting.update!(p1)
redirect_to "/#{locale}/admin/asks/category_setting"
end
def setting
@ask_setting = AskSetting.first
@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
@tags = @module_app.tags
@categories = @module_app.categories.enabled.sort_by{|category| (((@module_app.asc rescue true) ? category.sort_number.to_i : -category.sort_number.to_i) rescue category.id)}
@filter_fields = filter_fields(@categories, @tags)
# 列表欄位
@table_fields = [:situation, :category, 'title' , 'ask.name', 'ask.phone', 'ask.appointment','ask.created_at','ask.ip']
# 列表排序
# 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
@default_ask_setting = AskSetting.first
@categories = current_user.approved_categories_for_module(@module_app).sort_by{|category| (((@module_app.asc rescue true) ? category.sort_number.to_i : -category.sort_number.to_i) rescue category.id)}
@category_ids = @categories.collect(&:id)
@category_titles = @categories.collect{|v| v.title}
@category_added = AskCategorySetting.all.asc(:created_at).map{|a| [a.category_id, a]}.to_h
@category_added_ids = @category_added.map{|k,v| k}
@url = category_setting_save_admin_asks_path
end
def get_category_setting_field
@default_ask_setting = AskSetting.first
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(/<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.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 - 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.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 - 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.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
end
if temp_params['custom_values'].nil?
temp_params['custom_values'] = {}
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
temp_params['custom_values'] = @ask_question.custom_values.merge(temp_params['custom_values'])
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
def order_fields
@cats_relations = get_categories_info
@category_id = (params[:category] || @cats_relations[0][0] rescue nil)
@disp_fields_infos = AskSetting.get_disp_fields_infos(false,@category_id)
end
def update_order_fields
ask_setting = AskCategorySetting.where(:category_id=>params[:category]).first
use_default = ask_setting && ask_setting.use_default
sort_number = params[:sort_number].map{|k,v| [k,v.to_i]}.to_h
if params[:category].present? && !use_default
if ask_setting.nil?
default_setting = AskSetting.first
ask_setting = AskCategorySetting.create(category_id: params[:category])
p1 = default_setting.get_attrs
ask_setting.update_attributes(p1)
ask_setting.update(:use_default => true)
end
ask_setting.update(:sort_number=> sort_number)
default_ask_setting = AskSetting.first
default_sort_number = default_ask_setting.sort_number
ask_setting_id = ask_setting.id.to_s
part_sort_number = sort_number.select{|k,v| k.include?('default@')}.map{|k,v| ["custom@#{ask_setting_id}@#{k.split('@')[-1]}", v]}.to_h
intersect_keys = default_sort_number.keys & part_sort_number.keys
non_intersect_keys = part_sort_number.keys - default_sort_number.keys
if intersect_keys.count != 0
org_order = intersect_keys.map{|k| [k, default_sort_number[k]]}
default_sort_number = default_sort_number.merge(intersect_keys.zip(org_order.sort_by{|k, v| part_sort_number[k]}.map{|k,v| v}).to_h)
end
preserve_count = AskSetting::All_default_fields.count
if non_intersect_keys.count != 0
max_sort_number = default_sort_number.map{|k,v| v.to_i}.max.to_i
max_sort_number += 1
max_sort_number += preserve_count
part_sort_number = non_intersect_keys.map.with_index{|(k,v), i| [k, max_sort_number + i]}
default_sort_number = default_sort_number.merge(part_sort_number.to_h)
end
default_ask_setting.update(:sort_number=>default_sort_number)
else
ask_setting = AskSetting.first
if use_default
sort_number = ask_setting.sort_number.merge(sort_number)
end
AskSetting.update_all(:sort_number=>sort_number)
unless use_default
custom_sort_number = sort_number.select{|k, v| k.include?('custom@')}
all_custom_sort_numbers = custom_sort_number.group_by{|k, v| k.split('@')[1]}
preserve_count = AskSetting::All_default_fields.count
all_custom_sort_numbers.each do |ask_category_setting_id, part_sort_number|
ask_setting = AskCategorySetting.find(ask_category_setting_id) rescue nil
if ask_setting
sort_number = ask_setting.sort_number
part_sort_number = part_sort_number.map{|k,v| ["default@#{k.split('@')[-1]}", v]}.to_h
intersect_keys = sort_number.keys & part_sort_number.keys
non_intersect_keys = part_sort_number.keys - sort_number.keys
if intersect_keys.count != 0
org_order = intersect_keys.map{|k| [k, sort_number[k]]}
sort_number = sort_number.merge(intersect_keys.zip(org_order.sort_by{|k, v| part_sort_number[k]}.map{|k,v| v}).to_h)
end
if non_intersect_keys.count != 0
max_sort_number = sort_number.map{|k,v| v.to_i}.max.to_i
max_sort_number += 1
max_sort_number += preserve_count
part_sort_number = non_intersect_keys.map.with_index{|(k,v), i| [k, max_sort_number + i]}
sort_number = sort_number.merge(part_sort_number.to_h)
end
ask_setting.update(:sort_number=>sort_number)
end
end
end
end
render :json => {:success=>true}
end
def ticket_status
@ticket_statuses = AskTicketStatus.all
if request.xhr?
render 'ticket_status', :layout => false
end
end
def get_ticket_status
ticket_status = AskTicketStatus.where(:id=>params[:id]).first
render :json => {
"id"=>params[:id],
"title_translations"=> (ticket_status ? ticket_status.get_title_translations : {})
}
end
def update_ticket_status
if params[:id].blank?
ticket_status = AskTicketStatus.new
else
ticket_status = AskTicketStatus.where(:id=>params[:id]).first
end
ticket_status.update_attributes(params.require(:ask_ticket_status).permit!)
render :json => {:success=>true}
end
def delete_ticket_status
ticket_status = AskTicketStatus.where(:id=>params[:id]).first
unless ticket_status.is_default
ticket_status.destroy
end
render :json => {:success=>true}
end
private
def ask_setting_params(ask_setting,collection_name)
param = params.require(collection_name).except("id").permit!
param_clone = param.clone
param_clone['default_setting'].each { |k, v| param_clone['default_setting'][k] = (v == 'true'? true : false) if param_clone['default_setting'][k].class==String}
param_clone['default_setting_required'].each { |k, v| param_clone['default_setting_required'][k] = (v == 'true'? true : false) if param_clone['default_setting_required'][k].class==String}
param_clone.delete('custom_fields')
param_clone.delete('email_regex')
custom_fields = params['not_clone_attrs'] ? {} : 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?}
puts ["field_to_delete", field_to_delete]
puts ["custom_fields", custom_fields]
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