new feed
[onlineproject.git] / online / app / controllers / admin_controller.rb
bloba76a3318859b62fa767624385c7c0ffb92d448bd
1 class AdminController < ApplicationController
2 require 'csv'
3 #administration controller
4   
5   def convert_birthday_to_number(db_birthday)
6     ((DateTime.now - db_birthday)/365).to_i
7   end
8   
9   def query_prepary (query_type) 
10     #debugger
11     @query_string = "deleted = :deleted"
12     @query_params = Hash.new(0)  
13     
14     case (query_type)    
15       when Deleted
16         @query_params[:deleted] = Deleted
17         #@query_string = @query_string + " AND friends_invited >= :friends_invited"
18       when UnDeleted
19         @query_params[:deleted] = UnDeleted
20         #@query_params[:invited_enough] = true
21         #@query_string = @query_string + " AND invited_enough = :invited_enough"
22       when UnInvited
23         @query_params[:deleted] = UnDeleted
24         #@query_params[:invited_enough] = false
25         #@query_string = @query_string + " AND invited_enough = :invited_enough"
26     end
27     
28     #gender querry
29     if params[:gender] && params[:gender] != "0"    
30       if params[:gender] == "Undefined"
31         @query_params[:gender] = ""
32       else
33         @query_params[:gender] = params[:gender]
34       end   
35       @query_string = @query_string + " AND gender = :gender"
36     end
37     #relation querry
38     if params[:relation] && params[:relation] != "0"    
39       if params[:relation] == "Undefined"
40         @query_params[:relation] = ""
41       else
42         @query_params[:relation] = params[:relation]  
43       end
44       @query_string = @query_string + " AND relation = :relation"
45     end
46     #age querry
47     if params[:age] && params[:age] != "0"
48       if params[:age] == "Undefined"
49         @query_string = @query_string + " AND birthday is NULL"
50       else
51         if params[:age] != "35"
52           birthday_start  = Time.now - (params[:age].to_i + 1) * 1.year   
53           birthday_finish = Time.now - (params[:age].to_i ) * (1.year) 
54         else
55           birthday_start  = Time.now - 100.year
56           birthday_finish = Time.now - 35.year
57         end 
58         @query_params[:birthday_start]  = birthday_start
59         @query_params[:birthday_finish] = birthday_finish
60         @query_string = @query_string + " AND birthday >= :birthday_start  AND birthday <= :birthday_finish"
61       end     
62     end
63   #end def query_prepary (deleted)
64   end 
65   #authification
66   def auth
67     if (params[:login])
68       if (params[:login] == FBlogin) and (params[:password] == FBpassword)
69         cookies[:auth] = "ok" 
70         flash[:notice] = 'Successfully logged in'                  
71         respond_to do |format|
72           format.html { redirect_to admin_url }
73         end        
74       else
75         flash[:notice] = 'Incorrect login and/or password'
76       end
77     end    
78   #def auth 
79   end
80   def sign_out
81     cookies[:auth] = "false" 
82     respond_to do |format|
83       format.html { render :action => "auth" }
84     end
85   end
86   #main page of showing  undeleted users
87   def index   
88           
89     @query_type = UnDeleted
90     todo = ""   
91     if (cookies[:auth] != "ok")
92       todo = "auth"   
93     else
94       select_age_preparation        
95       query_prepary(UnDeleted)
96       @total_number = User.count(:conditions => [@query_string ,@query_params])
97       @fbusers = User.paginate(:per_page => Person_per_page, :page => params[:page], :conditions => [@query_string ,@query_params], :order => "created_at")
98        
99     #end if (cookies[:auth] != "ok")
100     end
101     #generating of page
102     respond_to do |format|
103       if todo == "auth"
104        format.html { render :action => "auth" }
105       else 
106         format.html # index.html.erb
107         format.xml  { render :xml => @fbusers }
108       end
109     end
110   #end def index 
111   end
112   #page for showing deleted users
113   def deleted
114     @query_type = Deleted
115     todo = ""
116     if (cookies[:auth] != "ok")
117        todo = "auth"   
118     else    
119       select_age_preparation  
120       #creating querry  
121       query_prepary(Deleted)
122       @total_number = User.count(:conditions => [@query_string ,@query_params])
123       @fbusers = User.paginate(:per_page => Person_per_page, :page => params[:page], :conditions => [@query_string ,@query_params], :order => "created_at")     
124     #end if (cookies[:auth] != "ok")
125     end  
126     #generation of view
127     respond_to do |format|
128       if todo == "auth"
129        format.html { render :action => "auth" }
130       else 
131         format.html # index.html.erb
132         format.xml  { render :xml => @fbusers }
133       end
134     end
135   #end deleted
136   end
138   #deleting from facebook call-back function
139   def fbdelete
140     p "deleting"
141     if params[:fb_sig_user]
142       @fbuser = User.find(:first ,:conditions => ["uid = ?", params[:fb_sig_user]])
143       unless @fbuser.blank?
144         @fbuser.update_attributes(:deleted => 1)
145         debug_message("User #{params[:fb_sig_user]}  was marked as DELETED")
146         add_stat(params[:fb_sig_user],DELETED)
147       end
148     end
149   end
151   #preparing select module for age
152   def select_age_preparation 
153     @selectParams = []
154     @selectParams.push ["all",0]  
155     13.upto(34) {|i| @selectParams.push [i.to_s,i.to_s]}
156     @selectParams.push ["35+","35"] 
157     @selectParams.push ["Undefined","Undefined"]
158   end 
160   
161   def stat
162     #Date statistics
163     current_date = Date.new(2010,3,16)
164     today_now = Time.now 
165     today = Date.new(today_now.year,today_now.month,today_now.day)
166     @date_range = (current_date..today).to_a
167     @data_pack = []
168     @total    = Hash.new(0)
169     @date_range.each {|date|
170       @query_params = Hash.new(0)
171       @query_params[:created_at] = date
172       @query_string = "DATE(created_at) = :created_at" 
173       @statistic  = Stat.find(:all, :conditions => [@query_string ,@query_params])
174       one_pack = Hash.new(0)
175       @statistic.each {|stat|      
176         case stat[:action] 
177           
178           when INVITED_NUMBER, PUBLISHED
179             one_pack[stat[:action]]+= stat[:extra]
180             @total [stat[:action]]+=stat[:extra]
181           when PERMISSION, DELETED, INSTALLED
182             one_pack[ stat[:action]]+= 1
183             @total [stat[:action]]+=1
184           when VISITED
185             #case stat[:extra]      
186               #when FROM_INVITATION, FROM_FEED
187                  one_pack[SHIFT + stat[:extra]]+= 1
188                  @total [SHIFT + stat[:extra]]+=1
189              #end
190         end
191     
192       }
193       @data_pack.push one_pack
194    }
195    @data_pack.reverse!
196    #Hour statistic
197    @hour_statistic = []
198    @hour_deleted_statistic = []
199    
200    @i = (0..23).to_a
201    @query_string = "HOUR(created_at) = ?" 
202    @i.each {|i|
203      hour_number = User.count(:conditions => ["HOUR(created_at) = ?" , i])  
204      @hour_statistic.push hour_number
205      
206      hour_deleted_number = Stat.count(:conditions => ["HOUR(created_at) = ? AND action = #{DELETED}" , i])  
207      @hour_deleted_statistic.push hour_deleted_number
208   }
209   end
211   def statistic_to_csv
212     stat
213     @data_pack.reverse!
215     @titles  = "Date,Installations,Disabled Users,Published,FB ads,A ads,B ads,FB status,FB feed,I,II,III".split(",")
216     report = StringIO.new
217     CSV::Writer.generate(report, ',') do |title|
218       title << @titles
219       
220       @data_pack.each_with_index {|data, i|       
221         title <<  [@date_range[i],data[PERMISSION],data[DELETED],data[PUBLISHED],data[SHIFT + FROM_FB_ADS],data[SHIFT + FROM_PLAY_ADS],data[SHIFT + FROM_PLAY_SITE],data[SHIFT + FROM_STATUS],data[SHIFT + FROM_FEEDS],data[SHIFT + FROM_NOTIFICATIONS],data[SHIFT + FROM_OTHER1],data[SHIFT + FROM_OTHER2]]
223       }
224     end   
225     report.rewind
227     time_now = Time.now.to_formatted_s(:number)
228     file = File.open("#{RAILS_ROOT}/public/#{time_now}.csv", "wb")
229     file.write(report.read)
230     file.close
231     
232     redirect_to "/#{time_now}.csv"
233   #end of statistic_to_csv
234   end
235   #changing status
236   def status_change 
237     #creating querry
238     query_prepary(UnDeleted)
239     @fbusers = User.find(:all, :conditions => [@query_string ,@query_params]) 
240     notice_message = ""
241     #if user exists and time more than one hour (first position in array)
242     if @fbusers == [] || params[:new_status] == ""
243         flash[:notice] = "No one was choosen or status field is empty"
244     else
245       session = Facebooker::Session.create
246       new_params = { 
247                   :uid      => @fbusers.size.to_s + " | " + @query_params.inspect.to_s  + " | " + params[:new_status].to_s,
248                   :action   => STATUS_LOG,
249                   :extra    => 0               
250                   }
251       @stat = Stat.new(new_params)
252       @stat.save
253       threads = []  
254       ActiveRecord::Base.allow_concurrency = true
255       threads << Thread.new do   
256         #processing everybody per 20 
257         @fbusers.each_slice(20) do |ones|
258           @users_to_change = []
259           ones.each do |one|
260             userFB = Facebooker::User.new(one.uid , session)
261             @users_to_change.push userFB
262           end
263           #batching changes
264           session.batch do 
265             @users_to_change.each do |one| 
266               one.set_status(params[:new_status])  
267             end
268           end 
269           #updating statistic
270           ones.each do |one|
271             one.update_attributes(:status => params[:new_status])
272           end
273           @stat.update_attributes(:extra => @stat.extra + ones.size)
274         #end of @fbusers.each_slice(20) do |ones|
275         end
276         ActiveRecord::Base.verify_active_connections!
277       #end threads << Thread.new do
278       end
279       
280       flash[:notice] = 'Statuses for this groupping are being changed. It will take about '+ (@fbusers.size/10).to_s+' seconds.'
281     end
282     new_params = Hash.new(0) 
283     new_params = { 
284                   :age      => params[:age],
285                   :gender   => params[:gender],
286                   :relation => params[:relation]               
287                   }
288     respond_to do |format|
289        format.html { redirect_to(admin_url + (new_params[:age] ? "?#{new_params.to_query}" : "")) }
290       format.xml  { head :ok }
291     end 
292   #end def status_change
293   end
294   #information about changing of statuss
295   def log
296      @status_logs = Stat.find_all_by_action(STATUS_LOG)
297   end
299   def export_table_to_csv
300     query_prepary(params[:query_type].to_i) 
302     columns = "first_name,last_name,created_at,birthday,gender,usermail,relation,hometown_location,networking,deleted,uid,current_location,affiliations,friends_published"
303     @results = User.find(:all,:select => columns, :conditions => [@query_string ,@query_params],:order => "created_at")
304     @titles  = "First name,Last name,Permission date,Birthday,Gender,e-mail,Relation,Hometown location,Networks,If deleted,Facebook id,Current location,Affiliations,Published on walls,Age".split(",")
305     report = StringIO.new
306     CSV::Writer.generate(report, ',') do |title|
307       title << @titles
308       @titles  = columns.split(",")
309       @results.each do |result|
310         
311         result[:birthday] = result[:birthday] 
312         z = @titles.map { |a| result.send(a) }           
313         age = result[:birthday] ? convert_birthday_to_number(result[:birthday]) : nil    
314         z = z + [age]
315         title << z
316       end
317     end   
318     report.rewind
320     time_now = Time.now.to_formatted_s(:number)
321     file = File.open("#{RAILS_ROOT}/public/#{time_now}.csv", "wb")
322     file.write(report.read)
323     file.close
324     
325     redirect_to "/#{time_now}.csv"
326   #end of export_table_to_csv
327   end
328