aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/public_body_controller.rb
blob: 9f692c5ba4eb7d588126e5f858c4e73ec7181682 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# -*- coding: utf-8 -*-
# app/controllers/public_body_controller.rb:
# Show information about a public body.
#
# Copyright (c) 2007 UK Citizens Online Democracy. All rights reserved.
# Email: hello@mysociety.org; WWW: http://www.mysociety.org/

require 'fastercsv'
require 'confidence_intervals'

class PublicBodyController < ApplicationController
    # XXX tidy this up with better error messages, and a more standard infrastructure for the redirect to canonical URL
    def show
        long_cache
        if MySociety::Format.simplify_url_part(params[:url_name], 'body') != params[:url_name]
            redirect_to :url_name =>  MySociety::Format.simplify_url_part(params[:url_name], 'body'), :status => :moved_permanently
            return
        end
        @locale = self.locale_from_params()
        I18n.with_locale(@locale) do
            @public_body = PublicBody.find_by_url_name_with_historic(params[:url_name])
            raise ActiveRecord::RecordNotFound.new("None found") if @public_body.nil?
            if @public_body.url_name.nil?
                redirect_to :back
                return
            end
            # If found by historic name, or alternate locale name, redirect to new name
            if  @public_body.url_name != params[:url_name]
                redirect_to :url_name => @public_body.url_name
                return
            end

            set_last_body(@public_body)

            top_url = frontpage_url
            @searched_to_send_request = false
            referrer = request.env['HTTP_REFERER']
            if !referrer.nil? && referrer.match(%r{^#{top_url}search/.*/bodies$})
                @searched_to_send_request = true
            end
            @view = params[:view]
            query = make_query_from_params(params.merge(:latest_status => @view))
            query += " requested_from:#{@public_body.url_name}"
            # Use search query for this so can collapse and paginate easily
            # XXX really should just use SQL query here rather than Xapian.
            sortby = "described"
            begin
                @xapian_requests = perform_search([InfoRequestEvent], query, sortby, 'request_collapse')
                if (@page > 1)
                    @page_desc = " (page " + @page.to_s + ")"
                else
                    @page_desc = ""
                end
            rescue
                @xapian_requests = nil
            end

            @track_thing = TrackThing.create_track_for_public_body(@public_body)
            @feed_autodetect = [ { :url => do_track_url(@track_thing, 'feed'), :title => @track_thing.params[:title_in_rss], :has_json => true } ]

            respond_to do |format|
                format.html { @has_json = true; render :template => "public_body/show"}
                format.json { render :json => @public_body.json_for_api }
            end

        end
    end

    def view_email
        @public_body = PublicBody.find_by_url_name_with_historic(params[:url_name])
        raise ActiveRecord::RecordNotFound.new("None found") if @public_body.nil?

        I18n.with_locale(self.locale_from_params()) do
            if params[:submitted_view_email]
                if verify_recaptcha
                    flash.discard(:error)
                    render :template => "public_body/view_email"
                    return
                end
                flash.now[:error] = _("There was an error with the words you entered, please try again.")
            end
            render :template => "public_body/view_email_captcha"
        end
    end

    def list
        long_cache
        # XXX move some of these tag SQL queries into has_tag_string.rb
        @query = "%#{params[:public_body_query].nil? ? "" : params[:public_body_query]}%"
        @tag = params[:tag]
        @locale = self.locale_from_params()
        default_locale = I18n.default_locale.to_s
        locale_condition = "(upper(public_body_translations.name) LIKE upper(?)
                            OR upper(public_body_translations.notes) LIKE upper (?))
                            AND public_body_translations.locale = ?
                            AND public_bodies.id <> #{PublicBody.internal_admin_body.id}"
        if @tag.nil? or @tag == "all"
            @tag = "all"
            conditions = [locale_condition, @query, @query, default_locale]
        elsif @tag == 'other'
            category_list = PublicBodyCategories::get().tags().map{|c| "'"+c+"'"}.join(",")
            conditions = [locale_condition + ' AND (select count(*) from has_tag_string_tags where has_tag_string_tags.model_id = public_bodies.id
                and has_tag_string_tags.model = \'PublicBody\'
                and has_tag_string_tags.name in (' + category_list + ')) = 0', @query, @query, default_locale]
        elsif @tag.size == 1
            @tag.upcase!
            conditions = [locale_condition + ' AND public_body_translations.first_letter = ?', @query, @query, default_locale, @tag]
        elsif @tag.include?(":")
            name, value = HasTagString::HasTagStringTag.split_tag_into_name_value(@tag)
            conditions = [locale_condition + ' AND (select count(*) from has_tag_string_tags where has_tag_string_tags.model_id = public_bodies.id
                and has_tag_string_tags.model = \'PublicBody\'
                and has_tag_string_tags.name = ? and has_tag_string_tags.value = ?) > 0', @query, @query, default_locale, name, value]
        else
            conditions = [locale_condition + ' AND (select count(*) from has_tag_string_tags where has_tag_string_tags.model_id = public_bodies.id
                and has_tag_string_tags.model = \'PublicBody\'
                and has_tag_string_tags.name = ?) > 0', @query, @query, default_locale, @tag]
        end

        if @tag == "all"
            @description = ""
        elsif @tag.size == 1
            @description = _("beginning with ‘{{first_letter}}’", :first_letter=>@tag)
        else
            category_name = PublicBodyCategories::get().by_tag()[@tag]
            if category_name.nil?
                @description = _("matching the tag ‘{{tag_name}}’", :tag_name=>@tag)
            else
                @description = _("in the category ‘{{category_name}}’", :category_name=>category_name)
            end
        end
        I18n.with_locale(@locale) do
            @public_bodies = PublicBody.where(conditions).joins(:translations).order("public_body_translations.name").paginate(
              :page => params[:page], :per_page => 100
            )
            respond_to do |format|
                format.html { render :template => "public_body/list" }
            end
        end
    end

    # Used so URLs like /local/islington work, for use e.g. writing to a local paper.
    def list_redirect
        @tag = params[:tag]
        redirect_to list_public_bodies_url(:tag => @tag)
    end

    def list_all_csv
        send_data(PublicBody.export_csv, :type=> 'text/csv; charset=utf-8; header=present',
                  :filename => 'all-authorities.csv',
                  :disposition =>'attachment', :encoding => 'utf8')
    end

    def statistics
        unless AlaveteliConfiguration::public_body_statistics_page
            raise ActiveRecord::RecordNotFound.new("Page not enabled")
        end

        per_graph = 8
        minimum_requests = AlaveteliConfiguration::minimum_requests_for_statistics
        # Make sure minimum_requests is > 0 to avoid division-by-zero
        minimum_requests = [minimum_requests, 1].max
        total_column = 'info_requests_count'

        @graph_list = []

        [[total_column,
          [{
               :title => 'Public bodies with the most requests',
               :y_axis => 'Number of requests',
               :highest => true}]],
         ['info_requests_successful_count',
          [{
               :title => 'Public bodies with the most successful requests',
               :y_axis => 'Percentage of total requests',
               :highest => true},
           {
               :title => 'Public bodies with the fewest successful requests',
               :y_axis => 'Percentage of total requests',
               :highest => false}]],
         ['info_requests_overdue_count',
          [{
               :title => 'Public bodies with most overdue requests',
               :y_axis => 'Percentage of requests that are overdue',
               :highest => true}]],
         ['info_requests_not_held_count',
          [{
               :title => 'Public bodies that most frequently replied with "Not Held"',
               :y_axis => 'Percentage of total requests',
               :highest => true}]]].each do |column, graphs_properties|

            graphs_properties.each do |graph_properties|

                percentages = (column != total_column)
                highest = graph_properties[:highest]

                data = nil
                if percentages
                    data = PublicBody.get_request_percentages(column,
                                                              per_graph,
                                                              highest,
                                                              minimum_requests)
                else
                    data = PublicBody.get_request_totals(per_graph,
                                                         highest,
                                                         minimum_requests)
                end

                data_to_draw = {
                    'id' => "#{column}-#{highest ? 'highest' : 'lowest'}",
                    'x_axis' => 'Public Bodies',
                    'y_axis' => graph_properties[:y_axis],
                    'errorbars' => percentages,
                    'title' => graph_properties[:title]}

                if data
                    data_to_draw.update(data)
                    data_to_draw['x_values'] = data['public_bodies'].each_with_index.map { |pb, i| i }
                    data_to_draw['x_ticks'] = data['public_bodies'].each_with_index.map { |pb, i| [i, pb.name] }
                end

                @graph_list.push data_to_draw
            end
        end

        respond_to do |format|
            format.html { render :template => "public_body/statistics" }
            format.json { render :json => @graph_list }
        end
    end

    # Type ahead search
    def search_typeahead
        # Since acts_as_xapian doesn't support the Partial match flag, we work around it
        # by making the last work a wildcard, which is quite the same
        query = params[:query]
        @xapian_requests = perform_search_typeahead(query, PublicBody)
        render :partial => "public_body/search_ahead"
    end
end