class OlympiamanagementsController < ApplicationController
include ActionView::Context #vary important (only add this can access @@session from view)
before_action :set_sign_up_setting,:create_first_fields
before_action :check_time , :except=>[:index,:download_school_code]
prepend_view_path "app/templates" #for_render_pages
layout :get_layout #for_render_pages
helper Admin::OlympiamanagementsHelper
before_action :check_login, except: [:login,:download_school_code]
def initialize
super
@app_title = "olympiamanagement"
end
def create_first_fields
StudentDataField.create if StudentDataField.all.length == 0
SchoolDataFields.create if SchoolDataFields.all.length == 0
SignUpSetting.create if SignUpSetting.all.length == 0
end
def check_time
@time_arr = ["year","month","day","o_clock","minute"]
start_time_str = @time_arr.map{|t| @sign_up_setting["start_"+t]}.join(' ')
end_time_str = @time_arr.map{|t| @sign_up_setting["end_"+t]}.join(' ')
time_now_str = Time.now.strftime("%Y %m %d %H %M")
@page = Page.where(:layout=>"olympia_managements_index",:parent_page_id=>(Page.where(:name=> ((I18n.locale.to_s == "en") ? "Home" : "首頁")).first.id)).first
if !(time_now_str <= end_time_str && time_now_str >= start_time_str)
redirect_to "/#{I18n.locale}#{@page.url}"
end
end
def check_login
begin
@@error
rescue
@@error = nil
end
@school = OlympiaSchoolDataFields.where(:sign_up_setting_id=>@sign_up_setting.id,:account_number=>request.session[:olympia_login_id],:approved=>true).first rescue nil
if @school.nil?
render_contents_in_index_page(render_to_string(:formats=> [:html] ,:partial=>'login',:locals=>{:@error=>@@error})) and return
end
end
def login
@@error = nil
if !params[:login_id].to_s.blank?
if OlympiaSchoolDataFields.where(:sign_up_setting_id=>@sign_up_setting.id,:account_number=>params[:login_id],:approved=>true).length == 0
@@error = "no_account"
else
@correct_password = OlympiaSchoolDataFields.where(:sign_up_setting_id=>@sign_up_setting.id,:account_number=>params[:login_id]).first.password
@correct_password = @sign_up_setting.default_password if @correct_password.blank?
if params[:login_pw] != @correct_password
@@error = "password_error"
else
session[:olympia_login_id] = params[:login_id]
end
end
end
if params[:PreviousPage].to_s.blank?
redirect_to :back
else
redirect_to params[:PreviousPage].to_s
end
end
def set_sign_up_setting
@key = Site.first.template rescue "" #for_render_pages
@sign_up_setting = SignUpSetting.where(:active=>true).last
data_arr = [{:url=>'/olympiamanagements/school_connection_data',:name=>t('olympiamanagement.school_connection_data')},
{:url=>'/olympiamanagements/add_sign_up_student_data',:name=>t('olympiamanagement.add_sign_up_student_data')},
{:url=>'/olympiamanagements/sign_up_student_data_list',:name=>t('olympiamanagement.sign_up_student_data_list')},
{:url=>'/olympiamanagements/edit_password',:name=>t('olympiamanagement.edit_password')},
{:url=>'/olympiamanagements/print_registration_form',:name=>t('olympiamanagement.print_registration_form')},
{:url=>'/olympiamanagements/logout',:name=>t('olympiamanagement.logout')}]
@breadcumb = render_to_string(:formats=> [:html] ,:partial=>'breadcumb',:locals=>{:data_arr=>data_arr,:@title=>I18n.t('olympiamanagement.sign_up_title')})
end
def index
uid = OrbitHelper.params[:uid] rescue ""
tags = OrbitHelper.widget_tags
categories = OrbitHelper.widget_categories || []
set_sign_up_setting
@time_arr = ["year","month","day","o_clock","minute"]
start_time_str = @time_arr.map{|t| @sign_up_setting["start_"+t]}.join(' ')
end_time_str = @time_arr.map{|t| @sign_up_setting["end_"+t]}.join(' ')
time_now_str = Time.now.strftime("%Y %m %d %H %M")
@instructions_name = {}
Site.first.in_use_locales.each do |locale|
I18n.with_locale(locale) do
@instructions_name[locale.to_s] = I18n.t('olympiamanagement.registration_instructions')
end
end
@page = Page.where(:layout=>"olympia_managements_index",:parent_page_id=>(Page.where(:name=> ((I18n.locale.to_s == "en") ? "Home" : "首頁")).first.id)).first
@instructions_pages = Page.where(:parent_page_id=>@page.id).select{|page| page.name_translations==@instructions_name}
if @instructions_pages.count == 0 #auto create instruction page
@newpage = Page.create(:layout=> "olympia_managements_instructions_index",:data_count=>@page.data_count,:parent_page_id=>@page.id,:url=>"/olympia_instructions",
:menu_enabled_for=>@page.menu_enabled_for,:enabled_for_sitemap=>@page.enabled_for_sitemap,:enabled_for=>@page.enabled_for,:module=>@page[:module],:page_id=>'olympia_instructions')
@newpage.name_translations = @instructions_name
@newpage.save
end
case OrbitHelper.params[:layout_type]
when "olympia_managements_instructions_index"
#if (time_now_str <= end_time_str && time_now_str >= start_time_str)
@olympiamanagement_instruction = @sign_up_setting.registration_instructions[I18n.locale.to_s].to_s
@sign_up_setting.attributes.to_h.each do |key,value|
@olympiamanagement_instruction = @olympiamanagement_instruction.gsub("{{#{key}}}",value.to_s)
end
if !OrbitHelper.current_user.nil?
@edit_link = '/admin/olympiamanagements/sign_up_setting#registration_instructions'
@edit_text = (I18n.locale.to_s == "zh_tw") ? "編輯" : "Edit"
if !OrbitHelper.current_user.nil?
@olympiamanagement_instruction += '
'+@edit_text+'
'
end
end
data_arr = @page.child_page.map{|page| {:url=>"/#{I18n.locale}#{page.url}",:name=>page.name}}
@breadcumb = render_to_string(:formats=> [:html] ,:partial=>'breadcumb',:locals=>{:data_arr=>data_arr,:@title=>I18n.t('olympiamanagement.sign_up_title')})
@olympiamanagement_instruction = @breadcumb + @olympiamanagement_instruction.html_safe
#else
#if !@instructions_pages.empty?
# @instructions_pages.each{|page| page.destroy}
#end
#@olympiamanagement_instruction = ''+t('olympiamanagement.sign_up_hint')+'
'
#end
{
"olympiamanagement" => [],
"extras"=>{"instructions"=> @olympiamanagement_instruction}
}
when "olympia_managements_index"
if Page.where(:parent_page_id=>@page.id,:name=>@page.name).length == 0
@newpage = Page.create(:layout=> @page.layout,:data_count=>@page.data_count,:parent_page_id=>@page.id,:url=>@page.url,
:menu_enabled_for=>@page.menu_enabled_for,:enabled_for_sitemap=>@page.enabled_for_sitemap,:enabled_for=>@page.enabled_for,:module=>@page[:module],:page_id=>@page.page_id)
@newpage.name_translations = @page.name_translations
@newpage.save
@newpage = Page.create(:layout=> "olympia_managements_instructions_index",:data_count=>@page.data_count,:parent_page_id=>@page.id,:url=>"/olympia_instructions",
:menu_enabled_for=>@page.menu_enabled_for,:enabled_for_sitemap=>@page.enabled_for_sitemap,:enabled_for=>@page.enabled_for,:module=>@page[:module],:page_id=>'olympia_instructions')
@newpage.name_translations = @instructions_name
@newpage.save
end
@error = @@error rescue nil
@page_content
if (time_now_str <= end_time_str && time_now_str >= start_time_str)
if @instructions_pages.empty?
@newpage = Page.create(:layout=> "olympia_managements_instructions_index",:data_count=>@page.data_count,:parent_page_id=>@page.id,:url=>"/olympia_instructions",
:menu_enabled_for=>@page.menu_enabled_for,:enabled_for_sitemap=>@page.enabled_for_sitemap,:enabled_for=>@page.enabled_for,:module=>@page[:module],:page_id=>'olympia_instructions')
@newpage.name_translations = @instructions_name
@newpage.save
elsif @instructions_pages.length != 1
@instructions_pages.slice(1,@instructions_pages.length).each{|page| page.destroy}
end
@school = OlympiaSchoolDataFields.where(:account_number=>@@session[:olympia_login_id],:approved=>true,:sign_up_setting_id=>@sign_up_setting.id).first rescue nil
if @school.nil?
@page_content = render_to_string(:formats=> [:html] ,:partial=>'login',:locals=>{:@error=>@error})
else
@@error = nil
@school_data_fields = [{'account_number'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_name'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_code'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_address'=>{'type'=>'String','size'=>'40','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'class_number'=>{'type'=>'String','size'=>'5','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'enrollment_limited'=>{'type'=>'Fixnum','size'=>'5','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_contact_person_name'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'department_job_title'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'office_tel_number'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'fax'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'mobile_number'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'email'=>{'type'=>'String','size'=>'40','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}}]
@olympia_school_data_field = OlympiaSchoolDataFields.where(:account_number=>@@session[:olympia_login_id],:approved=>true,:sign_up_setting_id=>@sign_up_setting.id).first
@page_content = @breadcumb
@page_content += render_to_string(:formats=> [:html] ,:partial=>'edit_school_data_for_index.html',:locals=>{:@school_data_fields=>@school_data_fields,:@olympia_school_data_field=>@olympia_school_data_field,:@@session=>@@session}) #form_for not work for rendering in Pagescontroller => edit to form
end
else
# if !@instructions_pages.empty?
# @instructions_pages.each{|page| page.destroy}
# end
data_arr = @page.child_page.map{|page| {:url=>"/#{I18n.locale}#{page.url}",:name=>page.name}}
@breadcumb = render_to_string(:formats=> [:html] ,:partial=>'breadcumb',:locals=>{:data_arr=>data_arr,:@title=>I18n.t('olympiamanagement.sign_up_title')})
@page_content = ''+t('olympiamanagement.sign_up_hint')+'
'
end
{
"olympiamanagement" => [],
"extras"=>{"page_content"=> @page_content}
}
end
end
def school_connection_data
@time_arr = ["year","month","day","o_clock","minute"]
start_time_str = @time_arr.map{|t| @sign_up_setting["start_"+t]}.join(' ')
end_time_str = @time_arr.map{|t| @sign_up_setting["end_"+t]}.join(' ')
time_now_str = Time.now.strftime("%Y %m %d %H %M")
if (time_now_str <= end_time_str && time_now_str >= start_time_str)
@school_data_fields = [{'account_number'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_name'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_code'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_address'=>{'type'=>'String','size'=>'40','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'class_number'=>{'type'=>'String','size'=>'5','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'enrollment_limited'=>{'type'=>'Fixnum','size'=>'5','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true",'readonly'=>"readonly"}},
{'school_contact_person_name'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'department_job_title'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'office_tel_number'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'fax'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'mobile_number'=>{'type'=>'String','size'=>'20','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}},
{'email'=>{'type'=>'String','size'=>'40','hint'=>{'zh_tw'=>'','en'=>''},'required'=>"true"}}]
@olympia_school_data_field = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first
@page_content = render_to_string(:formats=> [:html] ,:partial=>'edit_school_data.html',:locals=>{:@school_data_fields=>@school_data_fields,:@olympia_school_data_field=>@olympia_school_data_field})
render_contents_in_index_page(@breadcumb+@page_content)#redirect_to :back
else
begin
redirect_to :back
rescue
@page = Page.where(:layout=>"olympia_managements_index",:parent_page_id=>(Page.where(:name=> ((I18n.locale.to_s == "en") ? "Home" : "首頁")).first.id)).first
redirect_to "/#{I18n.locale}#{@page.url}"
end
end
end
def add_sign_up_student_data
@time_arr = ["year","month","day","o_clock","minute"]
start_time_str = @time_arr.map{|t| @sign_up_setting["start_"+t]}.join(' ')
end_time_str = @time_arr.map{|t| @sign_up_setting["end_"+t]}.join(' ')
time_now_str = Time.now.strftime("%Y %m %d %H %M")
if !(time_now_str <= end_time_str && time_now_str >= start_time_str)
redirect_to :back
else
@olympia_school_data_field = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first
redirect_to :back if @olympia_school_data_field.nil?
@required_fields = [:school_contact_person_name,:department_job_title,:office_tel_number,:fax,:mobile_number,:email]
@flag = true
@required_fields.each do |field|
if @olympia_school_data_field[field].to_s.blank?
@flag = false
break
end
end
if !@flag
I18n.t('olympiamanagement.please_set_school_connect_data')
render_contents_in_index_page(@breadcumb+"#{I18n.t('olympiamanagement.please_set_school_connect_data')}
".html_safe)
else
@student_data_field = StudentDataField.first
@olympia_student_data = (OlympiaStudentDataField.find(params[:id]) rescue OlympiaStudentDataField.new)
@page_content = render_to_string(:formats=> [:html] ,:partial=>'add_student_data.html',:locals=>{:@error=>(@@error rescue nil),:@student_data_field=>@student_data_field,:@olympia_student_data=>@olympia_student_data})
render_contents_in_index_page(@breadcumb+@page_content.html_safe)
end
end
end
def sign_up_student_data_list
page_num = params[:page] || 1
@field_infos = StudentDataField.first.student_data_fields
@olympia_school_data_fields_id = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first.id
@sign_up_setting_id = @sign_up_setting.id
@student_fields = OlympiaStudentDataField.where(:olympia_school_data_fields_id=>@olympia_school_data_fields_id,:sign_up_setting_id=>@sign_up_setting_id).asc(:id).page(page_num).per(10)
@page_content = render_to_string(:formats=> [:html] ,:partial=>'student_data_list.html',:locals=>{:@student_fields=>(@student_fields rescue [])}).html_safe
render_contents_in_index_page(@breadcumb+@page_content)
end
def edit_password
if !session[:olympia_login_id].to_s.blank?
if params[:confirm_password].nil? && params[:new_password].nil?
@page_content = render_to_string(:formats=> [:html] ,:partial=>'edit_password.html',:locals=>{:@error=>(@@error rescue nil)})
render_contents_in_index_page(@breadcumb+@page_content)
else
@@error = nil
if params[:confirm_password].to_s != params[:new_password].to_s
@@error = "confirm_password_error"
elsif params[:confirm_password].to_s.blank? && params[:new_password].to_s.blank?
@@error = "password_all_empty"
elsif params[:confirm_password].to_s.blank?
@@error = "confirm_password_empty"
elsif params[:new_password].to_s.blank?
@@error = "new_password_empty"
else
@olympia_school_data_field = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first
@olympia_school_data_field.password = params[:new_password]
@olympia_school_data_field.save
end
redirect_to edit_password_olympiamanagements_path
end
else
@page = Page.where(:layout=>"olympia_managements_index",:parent_page_id=>(Page.where(:name=> ((I18n.locale.to_s == "en") ? "Home" : "首頁")).first.id)).first
redirect_to "/#{I18n.locale}#{@page.url}"
end
end
def print_registration_form
@page = Page.where(:layout=>"olympia_managements_index",:parent_page_id=>(Page.where(:name=> ((I18n.locale.to_s == "en") ? "Home" : "首頁")).first.id)).first
data_arr = @page.child_page.map{|page| {:url=>"#{request.protocol}#{request.host_with_port}/#{I18n.locale}#{page.url}",:name=>page.name}}
@breadcumb = render_to_string(:formats=> [:html] ,:partial=>'breadcumb',:locals=>{:data_arr=>data_arr,:@title=>I18n.t('olympiamanagement.sign_up_title')})
@remark_texts = @sign_up_setting.remark_field[I18n.locale.to_s].html_safe
@sign_up_setting.attributes.to_h.each do |key,value|
@remark_texts = @remark_texts.gsub("{{#{key}}}",value.to_s)
end
@remark_texts = @remark_texts.html_safe
@record_form_title = ((I18n.locale.to_s == "zh_tw") ? "#{@sign_up_setting.end_year}年國中科學奧林匹亞競賽國家代表隊選拔初選報名表" : "#{Time.now.year} Year International Junior Science Olympiad National Team Selection First Stage Sign up Form")
@school_data = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first
@record_fields = [['school_name','school_code'],['school_address'],['class_number','enrollment_limited'],
['office_tel_number','fax'],['mobile_number','email'],['principal_signature','dean_signature']]
@student_fields = ['serial_number','StudentName','StudentSex','StudentClass','StudentIDNO','birth_date','StudentArea','StudentIdentity']
@field_infos = StudentDataField.first.student_data_fields
@olympia_school_data_fields_id = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first.id
@sign_up_setting_id = @sign_up_setting.id
@student_data_list = OlympiaStudentDataField.where(:olympia_school_data_fields_id=>@olympia_school_data_fields_id,:sign_up_setting_id=>@sign_up_setting_id)
@head = render_to_string(:formats=>[:html],:file=>"#{Rails.root}/app/templates/#{@key}/partial/_head.html")
end
def logout
session[:olympia_login_id] = ""
@page = Page.where(:layout=>"olympia_managements_index",:parent_page_id=>(Page.where(:name=> ((I18n.locale.to_s == "en") ? "Home" : "首頁")).first.id)).first
redirect_to "/#{I18n.locale}#{@page.url}"#render :html => session.to_hash
end
def widget
uid = OrbitHelper.params[:uid] rescue ""
tags = OrbitHelper.widget_tags
categories = OrbitHelper.widget_categories || []
@olympiamanagement_instruction = @sign_up_setting.registration_instructions[I18n.locale.to_s].to_s
@sign_up_setting.attributes.to_h.each do |key,value|
@olympiamanagement_instruction = @olympiamanagement_instruction.gsub("{{#{key}}}",value.to_s)
end
{
"olympiamanagement" => [],
"extras"=>{"instructions"=> @olympiamanagement_instruction}
}
end
def download_school_code
@OlympiaSchoolDataFields = OlympiaSchoolDataFields.where(:sign_up_setting_id=>@sign_up_setting.id).asc(:id)
dir_path = 'tmp/olympiamanagement/'
#FileUtils.rm_r(dir_path, :force => true) if Dir.exist?(dir_path)
FileUtils.mkdir dir_path if !Dir.exist?(dir_path) #create dir for storing tmp_file if dir doesn't exist
@filename = 'download_school_code.xlsx'
Dir.chdir(dir_path) do
File.open(@filename, 'w') do |f|
f.write render_to_string( :handlers=> [:axlsx], :formats=> [:xlsx] ,:partial=> 'school_code.xlsx',:locals=> {:@OlympiaSchoolDataFields=>@OlympiaSchoolDataFields} )
end
end
tmp_filename_data = File.read(dir_path +@filename)
send_data(tmp_filename_data, type: 'application/xlsx', disposition: 'attachment', filename: "#{Time.now.year}#{Time.now.month}#{Time.now.day}_download_school_code.xlsx")
end
def render_contents_in_index_page(contents=@breadcumb)
doc = Nokogiri::HTML(render_final_page("page",Page.where(:layout=>"olympia_managements_index").first,true), nil, "UTF-8")
viewarea = doc.css("*[data-content='true']")[0]
viewarea.inner_html = contents
render :html => doc.to_html.html_safe
end
def change_to_language(final_html) #for_render_pages
if session[:zh_cn]
final_html = ZhConv.convert("zh-cn", final_html,false)
final_html.gsub!('/zh_tw/','/zh_cn/')
final_html.sub!('繁体中文','繁体中文')
end
final_html
end
def get_layout #for_render_pages
if request[:action] == "edit_view"
page = Page.find(params[:id])
if page.page_id == "" || page.page_id == nil
false
else
File.join("../../templates", "#{@key}", "/home/page.html.erb")
end
# elsif request[:action] == "show" || request[:action] == "moduleShow"
# File.join("../../templates", "themes", "#{@key}", '/home/page.html.erb')
else
false
end
end
def render_final_page(original_view=get_view,page,layout) #for_render_pages
final_html_for_render = ""
OrbitHelper.set_css_to_render_to_empty
if layout
parts = $mobile.blank? ? (page.page_parts rescue []) : (page.mobile_page_parts rescue [])
@part_partials = {}
parts.each do |part|
subparts = part.sub_parts.asc(:created_at)
partials = []
subparts.each do |subpart|
if subpart.kind == "module_widget"
OrbitHelper.set_current_widget subpart
OrbitHelper.set_widget_data_count subpart.data_count
OrbitHelper.set_widget_module_app subpart.module
OrbitHelper.set_widget_item_url subpart
OrbitHelper.render_meta_tags []
OrbitHelper.set_widget_title subpart.title
OrbitHelper.set_widget_categories subpart.categories || ["all"]
OrbitHelper.set_widget_tags subpart.tags || ["all"]
custom_value = subpart.custom_string_field || subpart.custom_array_field rescue nil
if !custom_value.nil?
OrbitHelper.set_widget_custom_value custom_value
end
if @editmode
partials << " " + render_widget_for_frontend(subpart.module,subpart.widget_method,subpart.widget_type,subpart.id.to_s) + "
"
else
# widget_html = Rails.cache.fetch("subpart_#{subpart.module}_#{subpart.id.to_s}_"+I18n.locale.to_s,{ race_condition_ttl: 2, expires_in: 5.minutes}) do
# render_widget_for_frontend(subpart.module,subpart.widget_method,subpart.widget_type,subpart.id.to_s)
# end
widget_html = render_widget_for_frontend(subpart.module,subpart.widget_method,subpart.widget_type,subpart.id.to_s)
partials << widget_html
end
elsif subpart.kind == "text"
if @editmode
partials << ""
else
# change from px and pt and cm to em #start
have_change = false
if Site.all.first.page_sets.last.auto_convert_flag
if subpart.content.include? 'px'
have_change = true
inner_text = subpart.content
get_px = inner_text.enum_for(:scan,/:.*[+-]?(\d*[.])?\d+px[;\" ]/).map{Regexp.last_match.to_s}
get_px = get_px.uniq.sort_by(&:length).reverse!
get_px.each do |child_px|
convert_em = child_px.enum_for(:scan,/[+-]?(\d*[.])?\d+px/).map{Regexp.last_match.to_s}.sort_by(&:length).reverse!
calc_em = convert_em.collect{|v| "#{Float(v[0...v.length-2])/16}em"}
cp_child = child_px
(0...convert_em.length).each do |i|
cp_child = cp_child.gsub(convert_em[i],calc_em[i])
end
inner_text = inner_text.gsub(child_px,cp_child)
end
subpart.content = inner_text
end
if subpart.content.include? 'pt'
have_change = true
inner_text = subpart.content
get_pt = inner_text.enum_for(:scan,/:.*[+-]?(\d*[.])?\d+pt[;\" ]/).map{Regexp.last_match.to_s}
get_pt = get_pt.uniq.sort_by(&:length).reverse!
get_pt.each do |child_pt|
convert_em = child_pt.enum_for(:scan,/[+-]?(\d*[.])?\d+pt/).map{Regexp.last_match.to_s}.sort_by(&:length).reverse!
calc_em = convert_em.collect{|v| "#{Float(v[0...v.length-2])/12}em"}
cp_child = child_pt
(0...convert_em.length).each do |i|
cp_child = cp_child.gsub(convert_em[i],calc_em[i])
end
inner_text = inner_text.gsub(child_pt,cp_child)
end
subpart.content = inner_text
end
if subpart.content.include? 'cm'
have_change = true
inner_text = subpart.content
get_cm = inner_text.enum_for(:scan,/:.*[+-]?(\d*[.])?\d+cm[;\" ]/).map{Regexp.last_match.to_s}
get_cm = get_cm.uniq.sort_by(&:length).reverse!
get_cm.each do |child_cm|
convert_em = child_cm.enum_for(:scan,/[+-]?(\d*[.])?\d+cm/).map{Regexp.last_match.to_s}.sort_by(&:length).reverse!
calc_em = convert_em.collect{|v| "#{Float(v[0...v.length-2])*6/2.54}em"}
cp_child = child_cm
(0...convert_em.length).each do |i|
cp_child = cp_child.gsub(convert_em[i],calc_em[i])
end
inner_text = inner_text.gsub(child_cm,cp_child)
end
subpart.content = inner_text
end
# change from px and pt and cm to em #end
if have_change
subpart.save
end
end
partials << subpart.content
end
end
end
@part_partials["data-pp='#{part.part_id}'"] = partials
end
@file = nil
@layout_html = nil
if original_view == "home"
@file = File.join("#{@key}", "/home/index.html.erb")
else
@file = File.join("#{@key}", "/home/page.html.erb")
end
@layout_html = render_to_string(@file , :formats => :html)
doc = Nokogiri::HTML(@layout_html, nil, "UTF-8")
head = doc.css("head")
@part_partials.each do |key, partial|
html_string = ""
partial.each do |p|
if !p.nil?
html_string = html_string + p
end
end
pp = doc.css("*[#{key}]")
if !pp.blank?
pp = pp[0]
pp.inner_html = html_string
end
end
if @editmode
pps = doc.css("*[data-pp]")
pps.each do |pp|
number = pp.attributes["data-pp"].value
if pp.inner_html.strip == ""
pp.inner_html = " "
else
inner_html = pp.inner_html
pp.inner_html = inner_html + " "
end
end
end
if original_view != "home"
viewarea = doc.css("*[data-content='true']")[0]
if params["target_controller"].to_s == "page_contents"
viewarea_id = Page.where("page_id"=>params["page_id"].to_s).first.id.to_s
@page_contents = PageContext.where("page_id" => viewarea_id).last
viewarea.inner_html = @page_contents.content.to_s rescue ""
# change from px and pt and cm to em #start
have_change = false
if Site.all.first.page_sets.last.auto_convert_flag
if viewarea.inner_html.include? 'px'
have_change = true
inner_text = viewarea.inner_html
get_px = inner_text.enum_for(:scan,/:.*[+-]?(\d*[.])?\d+px[;\" ]/).map{Regexp.last_match.to_s}
get_px = get_px.uniq.sort_by(&:length).reverse!
get_px.each do |child_px|
convert_em = child_px.enum_for(:scan,/[+-]?(\d*[.])?\d+px/).map{Regexp.last_match.to_s}.sort_by(&:length).reverse!
calc_em = convert_em.collect{|v| "#{Float(v[0...v.length-2])/16}em"}
cp_child = child_px
(0...convert_em.length).each do |i|
cp_child = cp_child.gsub(convert_em[i],calc_em[i])
end
inner_text = inner_text.gsub(child_px,cp_child)
end
viewarea.inner_html = inner_text
end
if viewarea.inner_html.include? 'pt'
have_change = true
inner_text = viewarea.inner_html
get_pt = inner_text.enum_for(:scan,/:.*[+-]?(\d*[.])?\d+pt[;\" ]/).map{Regexp.last_match.to_s}
get_pt = get_pt.uniq.sort_by(&:length).reverse!
get_pt.each do |child_pt|
convert_em = child_pt.enum_for(:scan,/[+-]?(\d*[.])?\d+pt/).map{Regexp.last_match.to_s}.sort_by(&:length).reverse!
calc_em = convert_em.collect{|v| "#{Float(v[0...v.length-2])/12}em"}
cp_child = child_pt
(0...convert_em.length).each do |i|
cp_child = cp_child.gsub(convert_em[i],calc_em[i])
end
inner_text = inner_text.gsub(child_pt,cp_child)
end
viewarea.inner_html = inner_text
end
if viewarea.inner_html.include? 'cm'
have_change = true
inner_text = viewarea.inner_html
get_cm = inner_text.enum_for(:scan,/:.*[+-]?(\d*[.])?\d+cm[;\" ]/).map{Regexp.last_match.to_s}
get_cm = get_cm.uniq.sort_by(&:length).reverse!
get_cm.each do |child_cm|
convert_em = child_cm.enum_for(:scan,/[+-]?(\d*[.])?\d+cm/).map{Regexp.last_match.to_s}.sort_by(&:length).reverse!
calc_em = convert_em.collect{|v| "#{Float(v[0...v.length-2])*6/2.54}em"}
cp_child = child_cm
(0...convert_em.length).each do |i|
cp_child = cp_child.gsub(convert_em[i],calc_em[i])
end
inner_text = inner_text.gsub(child_cm,cp_child)
end
viewarea.inner_html = inner_text
end
# change from px and pt and cm to em #end
if have_change && (viewarea.inner_html != "")
@page_contents.content = viewarea.inner_html
@page_contents.save
end
end
viewarea.inner_html = render_to_string(original_view) rescue ""
else
viewarea.inner_html = render_to_string(original_view) rescue ""
end
head[0].inner_html = OrbitHelper.meta_tags_html + head.inner_html
end
head[0].inner_html = head.inner_html + OrbitHelper.get_css_to_render_in_head
link = doc.css("link")[0]
link.attributes["href"].value = current_site.favicon.url.nil? ? "/assets/favicon.ico" : current_site.favicon.url
final_html_for_render = doc.to_html
else
final_html_for_render = render_to_string(original_view) rescue ""
end
final_html_for_render = change_to_language(final_html_for_render)
if @editmode
session[:mobile] = $temp_mobile
end
format_date(final_html_for_render,(original_view == "home" ? "home" : page.module)) rescue final_html_for_render
end
def render_widget_for_frontend(controller_name, widget_method, widget_file, subpart_id=nil)
def widget_parsing_repeats_again(elements,d,level)
newhtml = []
oldhtml = []
elements.each do |el|
html_to_render = ""
data_name = el.attr("data-list")
wrap_elements = el.css("*[data-list][data-level='#{level}']")
if d["#{data_name}"]
d["#{data_name}"].each_with_index do |item,i|
element = el.inner_html
if wrap_elements.count > 0
htmls = widget_parsing_repeats_again(wrap_elements,d["#{data_name}"][i], level + 1)
htmls[0].each_with_index do |html,i|
element = element.gsub(html,htmls[1][i])
end
end
item.each do |key,value|
if !value.kind_of?(Array)
value = value.nil? ? "" : value
element = element.gsub("{{#{key}}}",value.to_s.html_safe)
element = element.gsub("%7B%7B#{key}%7D%7D",value.to_s)
end
end
html_to_render = html_to_render + element
end
temp = el.to_s
oldhtml << temp
temp = temp.gsub(el.inner_html, html_to_render)
newhtml << temp
end
end
[oldhtml,newhtml]
end
@key = Site.first.template if @key.nil?
controller_name = controller_name.downcase.singularize
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', "#{controller_name}", "_#{widget_file}.html.erb");
if !File.exists?f
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'widgets', "#{controller_name}", "_#{widget_file}.html.erb");
if !File.exists?f
f = File.join(Rails.root, 'app', 'templates', "#{@key}", 'modules', "#{controller_name}", "_widget.html.erb");
if File.exists?f
f = File.join("#{@key}", 'modules', "#{controller_name}", "_widget.html.erb");
else
return "Maybe the administrator has changed the theme, please select the widget design again from the page settings.
".html_safe
end
else
f = File.join("#{@key}", 'widgets', "#{controller_name}", "_#{widget_file}.html.erb");
end
else
f = File.join("#{@key}", 'modules', "#{controller_name}", "_#{widget_file}.html.erb");
end
s = render_to_string(f)
doc = Nokogiri::HTML(s, nil, "UTF-8")
if !subpart_id.nil?
doc.css("body").children.first.set_attribute("data-subpart-id", subpart_id) rescue nil
end
wrap_elements = doc.css("*[data-repeat]")
controller = "#{controller_name.capitalize.pluralize}_controller".classify.constantize.new
OrbitHelper.set_current_widget_module controller_name
begin
data = controller.send("#{widget_method}") #rescue nil
rescue Exception => e
write_widget_debug_file(e,controller_name,widget_method,subpart_id) if Site::DEBUG
end
if !data.nil?
wrap_elements = doc.css("*[data-list][data-level='0']")
htmls = widget_parsing_repeats_again(wrap_elements,data,1)
html = doc.to_s
htmls[0].each_with_index do |h,i|
html = html.gsub(h,htmls[1][i])
end
extras = data['extras'] || {}
extras["subpart-id"] = subpart_id if !subpart_id.nil?
extras["widget-title"] = OrbitHelper.widget_title
extras.each do |key,value|
html = html.gsub("{{#{key}}}",value.to_s.html_safe)
html = html.gsub("%7B%7B#{key}%7D%7D",value.to_s)
end
html.html_safe
else
return "No content to show.
".html_safe
end
end
def update_school_data
@readonly_fields = ['account_number','password','school_name','school_code','school_address','class_number','enrollment_limited']
@olympia_school_data_field = OlympiaSchoolDataFields.where(:account_number=>params[:olympia_user_name],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first
redirect_to :back if @olympia_school_data_field.nil?
params['add_school_data'].keys.each do |field|
if !@readonly_fields.include?(field)
@olympia_school_data_field[field] = params['add_school_data'][field]
end
end
@olympia_school_data_field.save
redirect_to add_sign_up_student_data_olympiamanagements_path
#render_contents_in_index_page(@olympia_school_data_field.attributes.to_s)
end
def update_student_data
if params[:type] == 'add_student_data'
@error_msg = []
@student_params = params.require(:add_student_data).permit!
@edit_unenable = ['StudentIdentity']
@olympia_student_data = OlympiaStudentDataField.find(params[:id]) rescue nil
if !@olympia_student_data.nil?
@edit_unenable.each do |key|
@student_params[key] = @olympia_student_data[key]
end
end
@all_fields_name = (StudentDataField.first || StudentDataField.new).student_data_fields.map{|hash| hash.keys[0]}
if @student_params.select{|key,value| !value.to_s.blank?}.count < @all_fields_name.slice(0,@all_fields_name.count-1).count
@error_msg << "缺少#{@all_fields_name.slice(0,@all_fields_name.count-1).count-@student_params.select{|key,value| !value.to_s.blank?}.count}個欄位值"
end
@student_params.select{|key,value| value.to_s.blank?}.keys.each do |key|
@error_msg << "#{I18n.t('olympiamanagement.'+key)}欄位值為空"
end
@id_error_msg = checkid(@student_params['StudentIDNO'])
if @id_error_msg.length != 0
@error_msg << I18n.t('olympiamanagement.id_number_error')
end
if (@student_params['StudentIdentity'] == '1' || @student_params['StudentIdentity'] == '2') && (@student_params['remove_image']=='true' || (@student_params['olympia_student_images']['0']['student_file'].nil? rescue true))
if @student_params['remove_image']=='true' || (@olympia_student_data.olympia_student_images.empty? || !@olympia_student_data.olympia_student_images.first.student_file.file.present? rescue true)
@error_msg << I18n.t('olympiamanagement.StudentFile')
end
end
@olympia_school_data_field = OlympiaSchoolDataFields.where(:account_number=>session[:olympia_login_id],:sign_up_setting_id=>@sign_up_setting.id,:approved=>true).first
@enrollment_limited = ((@olympia_school_data_field.enrollment_limited.nil? || @olympia_school_data_field.enrollment_limited == 0) ? (ClassSettingFields.all.select{|class_setting_field| class_setting_field.class_number_range[0] <= @olympia_school_data_field.class_number.to_i && class_setting_field.class_number_range[1] >= @olympia_school_data_field.class_number.to_i}.first.enrollment_available.to_i rescue ClassSettingFields.all.desc(:enrollment_available).first.enrollment_available.to_i) : @olympia_school_data_field.enrollment_limited.to_i)
@student_fields = OlympiaStudentDataField.where(:olympia_school_data_fields_id=>@olympia_school_data_field.id,:sign_up_setting_id=>@sign_up_setting.id,:StudentIdentity=>'0')
@olympia_student_data = OlympiaStudentDataField.find(params[:id]) rescue nil
extra_num = 0
extra_num = 1 if(@olympia_student_data.nil? && @student_params['StudentIdentity'] == '0')
if (@student_fields.length + extra_num) > @enrollment_limited
@error_msg << ((I18n.locale.to_s == "zh_tw") ? ("一般身分報名人數上限為 #{@enrollment_limited} 人。") : ("Enrollment limited of General identity is #{@enrollment_limited} people."))
@error_msg << I18n.t('olympiamanagement.already_exceed_enrollment_limited')
end
if @error_msg.empty?
@olympia_student_data = OlympiaStudentDataField.find(params[:id]) rescue nil
if @olympia_student_data.nil?
@olympia_student_data = OlympiaStudentDataField.create(@student_params.merge({
:olympia_school_data_fields_id=>@olympia_school_data_field.id,:sign_up_setting_id => @sign_up_setting.id}))
else
@olympia_student_data.update_attributes(@student_params)
end
redirect_to sign_up_student_data_list_olympiamanagements_path
else
@page_content = render_to_string(:formats=>[:html],:partial=>'import_error_msg.html',:locals=>{:@error_msg=>@error_msg})
render_contents_in_index_page(@page_content)
end
elsif params[:type] == 'delete_student_data'
@olympia_student_data = OlympiaStudentDataField.find(params[:id]) rescue nil
@olympia_student_data.destroy if !@olympia_student_data.nil?
redirect_to :back
else
render :html => '404'
end
end
def checkid(id_number)
@ALP_STR = "ABCDEFGHJKLMNPQRSTUVXYWZIO"
@NUM_STR = "0123456789"
def CheckPID(id_number)
@sMsg = ""
sPID = id_number
if(sPID == '')
@sMsg = "請輸入身分證字號"
elsif (sPID.length != 10)
@sMsg = "身分證字號長度應為 10 !"
else
sPID = sPID.upcase.strip
@sMsg = chkPID_CHAR(sPID)
if (@sMsg.length != 0)
return @sMsg
end
@iChkNum = getPID_SUM(sPID)
if (@iChkNum % 10 != 0)
iLastNum = sPID[9].to_i
for i in 0 .. 10
xRightAlpNum = @iChkNum - iLastNum + i
if ((xRightAlpNum % 10) == 0)
@sMsg = "身分證字號最後一個數應為:#{i}"
break
end
end
end
end
return @sMsg;
end
# 身分證字號檢查器 - 檢查合法字元
def chkPID_CHAR(sPID)
@sMsg = ""
#sPID = sPID.upcase.strip;
iPIDLen = String(sPID).length
sChk = @ALP_STR + @NUM_STR
for i in 0 ... iPIDLen
if (sChk.index(sPID[i]) < 0)
@sMsg = "這個身分證字號含有不正確的字元!"
break
end
end
if (@sMsg.length == 0)
if (@ALP_STR.index(sPID[0]) < 0)
@sMsg = "身分證字號第 1 碼應為英文字母(A~Z)。"
elsif ((sPID[1] != "1") && (sPID[1] != "2"))
@sMsg = "身分證字號第 2 碼應為數字(1~2)。"
else
for i in 2 ... iPIDLen
if (@NUM_STR.index(sPID[i]) < 0)
@sMsg = "第 #{i + 1} 碼應為數字(0~9)。"
break
end
end
end
end
return @sMsg
end
#身份證字號檢查器 - 累加檢查碼
def getPID_SUM(sPID)
@iChkNum = 0
#第 1 碼
@iChkNum = @ALP_STR.index(sPID[0]) + 10
@iChkNum = (@iChkNum / 10) + (@iChkNum % 10 * 9)
# 第 2 - 9 碼
for i in 1 ... (sPID.length - 1)
@iChkNum += sPID[i].to_i * (9 - i)
end
# 第 10 碼
@iChkNum += sPID[9].to_i;
return @iChkNum;
end
return CheckPID(id_number);
end
end