aboutsummaryrefslogtreecommitdiffstats
path: root/perllib/FixMyStreet/DB/ResultSet/Problem.pm
blob: 8c1f95baeb861a4ef42eef0787ee8050fc95b911 (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
package FixMyStreet::DB::ResultSet::Problem;
use base 'DBIx::Class::ResultSet';

use strict;
use warnings;

my $site_restriction;
my $site_key;

sub set_restriction {
    my ( $rs, $sql, $key, $restriction ) = @_;
    $site_key = $key;
    $site_restriction = $restriction;
}

# Front page statistics

sub recent_fixed {
    my $rs = shift;
    my $key = "recent_fixed:$site_key";
    my $result = Memcached::get($key);
    unless ($result) {
        $result = $rs->search( {
            state => [ FixMyStreet::DB::Result::Problem->fixed_states() ],
            lastupdate => { '>', \"current_timestamp-'1 month'::interval" },
        } )->count;
        Memcached::set($key, $result, 3600);
    }
    return $result;
}

sub number_comments {
    my $rs = shift;
    my $key = "number_comments:$site_key";
    my $result = Memcached::get($key);
    unless ($result) {
        $result = $rs->search(
            { 'comments.state' => 'confirmed' },
            { join => 'comments' }
        )->count;
        Memcached::set($key, $result, 3600);
    }
    return $result;
}

sub recent_new {
    my ( $rs, $interval ) = @_;
    (my $key = $interval) =~ s/\s+//g;
    $key = "recent_new:$site_key:$key";
    my $result = Memcached::get($key);
    unless ($result) {
        $result = $rs->search( {
            state => [ FixMyStreet::DB::Result::Problem->visible_states() ],
            confirmed => { '>', \"current_timestamp-'$interval'::interval" },
        } )->count;
        Memcached::set($key, $result, 3600);
    }
    return $result;
}

# Front page recent lists

sub recent {
    my ( $rs ) = @_;
    my $key = "recent:$site_key";
    my $result = Memcached::get($key);
    unless ($result) {
        $result = [ $rs->search( {
            state => [ FixMyStreet::DB::Result::Problem->visible_states() ]
        }, {
            columns => [ 'id', 'title' ],
            order_by => { -desc => 'confirmed' },
            rows => 5,
        } )->all ];
        Memcached::set($key, $result, 3600);
    }
    return $result;
}

sub recent_photos {
    my ( $rs, $num, $lat, $lon, $dist ) = @_;
    my $probs;
    my $query = {
        state => [ FixMyStreet::DB::Result::Problem->visible_states() ],
        photo => { '!=', undef },
    };
    my $attrs = {
        columns => [ 'id', 'title' ],
        order_by => { -desc => 'confirmed' },
        rows => $num,
    };
    if (defined $lat) {
        my $dist2 = $dist; # Create a copy of the variable to stop it being stringified into a locale in the next line!
        my $key = "recent_photos:$site_key:$num:$lat:$lon:$dist2";
        $probs = Memcached::get($key);
        unless ($probs) {
            $attrs->{bind} = [ $lat, $lon, $dist ];
            $attrs->{join} = 'nearby';
            $probs = [ mySociety::Locale::in_gb_locale {
                $rs->search( $query, $attrs )->all;
            } ];
            Memcached::set($key, $probs, 3600);
        }
    } else {
        my $key = "recent_photos:$site_key:$num";
        $probs = Memcached::get($key);
        unless ($probs) {
            $probs = [ $rs->search( $query, $attrs )->all ];
            Memcached::set($key, $probs, 3600);
        }
    }
    return $probs;
}

# Problems around a location

sub around_map {
    my ( $rs, $min_lat, $max_lat, $min_lon, $max_lon, $interval, $limit ) = @_;
    my $attr = {
        order_by => { -desc => 'created' },
        columns => [
            'id', 'title' ,'latitude', 'longitude', 'state', 'confirmed'
        ],
    };
    $attr->{rows} = $limit if $limit;

    my $q = {
            state => [ FixMyStreet::DB::Result::Problem->visible_states() ],
            latitude => { '>=', $min_lat, '<', $max_lat },
            longitude => { '>=', $min_lon, '<', $max_lon },
    };
    $q->{'current_timestamp - lastupdate'} = { '<', \"'$interval'::interval" }
        if $interval;

    my @problems = mySociety::Locale::in_gb_locale { $rs->search( $q, $attr )->all };
    return \@problems;
}

# Admin functions

sub timeline {
    my ( $rs ) = @_;

    my $prefetch = 
        FixMyStreet::App->model('DB')->schema->storage->sql_maker->quote_char ?
        [ qw/user/ ] :
        [];

    return $rs->search(
        {
            -or => {
                created  => { '>=', \"ms_current_timestamp()-'7 days'::interval" },
                confirmed => { '>=', \"ms_current_timestamp()-'7 days'::interval" },
                whensent  => { '>=', \"ms_current_timestamp()-'7 days'::interval" },
            }
        },
        {
            prefetch => $prefetch,
        }
    );
}

sub summary_count {
    my ( $rs ) = @_;

    return $rs->search(
        undef,
        {
            group_by => ['state'],
            select   => [ 'state', { count => 'id' } ],
            as       => [qw/state state_count/]
        }
    );
}

sub unique_users {
    my ( $rs ) = @_;

    return $rs->search( {
        state => [ FixMyStreet::DB::Result::Problem->visible_states() ],
    }, {
        select => [ { count => { distinct => 'user_id' } } ],
        as     => [ 'count' ]
    } )->first->get_column('count');
}

sub categories_summary {
    my ( $rs ) = @_;

    my $fixed_case = "case when state IN ( '" . join( "', '", FixMyStreet::DB::Result::Problem->fixed_states() ) . "' ) then 1 else null end";
    my $categories = $rs->search( {
        state => [ FixMyStreet::DB::Result::Problem->visible_states() ],
        whensent => { '<' => \"NOW() - INTERVAL '4 weeks'" },
    }, {
        select   => [ 'category', { count => 'id' }, { count => \$fixed_case } ],
        as       => [ 'category', 'c', 'fixed' ],
        group_by => [ 'category' ],
        result_class => 'DBIx::Class::ResultClass::HashRefInflator'
    } );
    my %categories = map { $_->{category} => { total => $_->{c}, fixed => $_->{fixed} } } $categories->all;
    return \%categories;
}

1;
span>.activate(); } else if (fixmystreet.page == 'new') { fixmystreet_activate_drag(); } fixmystreet.map.addLayer(fixmystreet.markers); if ( fixmystreet.zoomToBounds ) { var bounds = fixmystreet.markers.getDataExtent(); if (bounds) { fixmystreet.map.zoomToExtent( bounds ); } } $('#hide_pins_link').click(function(e) { e.preventDefault(); var showhide = [ 'Show pins', 'Hide pins', 'Dangos pinnau', 'Cuddio pinnau', "Vis nåler", "Gjem nåler" ]; for (var i=0; i<showhide.length; i+=2) { if (this.innerHTML == showhide[i]) { fixmystreet.markers.setVisibility(true); this.innerHTML = showhide[i+1]; } else if (this.innerHTML == showhide[i+1]) { fixmystreet.markers.setVisibility(false); this.innerHTML = showhide[i]; } } }); $('#all_pins_link').click(function(e) { e.preventDefault(); fixmystreet.markers.setVisibility(true); var texts = [ 'en', 'Include old reports', 'Hide old reports', 'nb', 'Inkluder utdaterte problemer', 'Skjul utdaterte rapporter', 'cy', 'Cynnwys hen adroddiadau', 'Cuddio hen adroddiadau' ]; for (var i=0; i<texts.length; i+=3) { if (this.innerHTML == texts[i+1]) { this.innerHTML = texts[i+2]; fixmystreet.markers.protocol.options.params = { all_pins: 1 }; fixmystreet.markers.refresh( { force: true } ); lang = texts[i]; } else if (this.innerHTML == texts[i+2]) { this.innerHTML = texts[i+1]; fixmystreet.markers.protocol.options.params = { }; fixmystreet.markers.refresh( { force: true } ); lang = texts[i]; } } if (lang == 'cy') { document.getElementById('hide_pins_link').innerHTML = 'Cuddio pinnau'; } else if (lang == 'nb') { document.getElementById('hide_pins_link').innerHTML = 'Gjem nåler'; } else { document.getElementById('hide_pins_link').innerHTML = 'Hide pins'; } }); } $(function(){ set_map_config(); fixmystreet.map = new OpenLayers.Map("map", { controls: fixmystreet.controls, displayProjection: new OpenLayers.Projection("EPSG:4326") }); fixmystreet.layer_options = OpenLayers.Util.extend({ zoomOffset: fixmystreet.zoomOffset, transitionEffect: 'resize', numZoomLevels: fixmystreet.numZoomLevels }, fixmystreet.layer_options); var layer = new fixmystreet.map_type("", fixmystreet.layer_options); fixmystreet.map.addLayer(layer); if (!fixmystreet.map.getCenter()) { var centre = new OpenLayers.LonLat( fixmystreet.longitude, fixmystreet.latitude ); centre.transform( new OpenLayers.Projection("EPSG:4326"), fixmystreet.map.getProjectionObject() ); fixmystreet.map.setCenter(centre, fixmystreet.zoom || 3); } if ($('#map_box').data('size')=='full') { // TODO Work better with window resizing, this is pretty 'set up' only at present var q = $(window).width() / 4; // Need to try and fake the 'centre' being 75% from the left fixmystreet.map.pan(-q, -25, { animate: false }); fixmystreet.map.events.register("movestart", null, function(e){ fixmystreet.map.moveStart = { zoom: this.getZoom(), center: this.getCenter() }; }); fixmystreet.map.events.register("zoomend", null, function(e){ if ( !fixmystreet.map.moveStart || !this.getCenter().equals(fixmystreet.map.moveStart.center) ) { // Centre has moved, e.g. by double-click. Same whether zoom in or out fixmystreet.map.pan(-q, -25, { animate: false }); return; } var zoom_change = this.getZoom() - fixmystreet.map.moveStart.zoom; if (zoom_change == -1) { // Zoomed out, need to re'centre' fixmystreet.map.pan(-q/2, 0, { animate: false }); } else if (zoom_change == 1) { // Using a zoom button fixmystreet.map.pan(q, 0, { animate: false }); } }); } if (document.getElementById('mapForm')) { var click = new OpenLayers.Control.Click(); fixmystreet.map.addControl(click); click.activate(); } $(window).hashchange(function(){ if (location.hash) { return; } // Okay, back to around view. fixmystreet.bbox_strategy.activate(); fixmystreet.markers.refresh( { force: true } ); fixmystreet.drag.deactivate(); $('#side-form').hide(); $('#side').show(); $('#sub_map_links').show(); heightFix('#report-a-problem-sidebar:visible', '.content', 26); fixmystreet.page = 'around'; }); // Vector layers must be added onload as IE sucks if ($.browser.msie) { $(window).load(fixmystreet_onload); } else { fixmystreet_onload(); } }); /* Overridding the buttonDown function of PanZoom so that it does zoomTo(0) rather than zoomToMaxExtent() */ OpenLayers.Control.PanZoomFMS = OpenLayers.Class(OpenLayers.Control.PanZoom, { buttonDown: function (evt) { if (!OpenLayers.Event.isLeftClick(evt)) { return; } switch (this.action) { case "panup": this.map.pan(0, -this.getSlideFactor("h")); break; case "pandown": this.map.pan(0, this.getSlideFactor("h")); break; case "panleft": this.map.pan(-this.getSlideFactor("w"), 0); break; case "panright": this.map.pan(this.getSlideFactor("w"), 0); break; case "zoomin": this.map.zoomIn(); break; case "zoomout": this.map.zoomOut(); break; case "zoomworld": this.map.zoomTo(0); break; } OpenLayers.Event.stop(evt); } }); /* Overriding Permalink so that it can pass the correct zoom to OSM */ OpenLayers.Control.PermalinkFMS = OpenLayers.Class(OpenLayers.Control.Permalink, { updateLink: function() { var separator = this.anchor ? '#' : '?'; var href = this.base; if (href.indexOf(separator) != -1) { href = href.substring( 0, href.indexOf(separator) ); } href += separator + OpenLayers.Util.getParameterString(this.createParams(null, this.map.getZoom()+fixmystreet.zoomOffset)); // Could use mlat/mlon here as well if we are on a page with a marker if (this.anchor && !this.element) { window.location.href = href; } else { this.element.href = href; } } }); /* Pan data handler */ OpenLayers.Format.FixMyStreet = OpenLayers.Class(OpenLayers.Format.JSON, { read: function(json, filter) { if (typeof json == 'string') { obj = OpenLayers.Format.JSON.prototype.read.apply(this, [json, filter]); } else { obj = json; } var current, current_near; if (typeof(obj.current) != 'undefined' && (current = document.getElementById('current'))) { current.innerHTML = obj.current; } if (typeof(obj.current_near) != 'undefined' && (current_near = document.getElementById('current_near'))) { current_near.innerHTML = obj.current_near; } var markers = fms_markers_list( obj.pins, false ); return markers; }, CLASS_NAME: "OpenLayers.Format.FixMyStreet" }); /* Click handler */ OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, { defaultHandlerOptions: { 'single': true, 'double': false, 'pixelTolerance': 0, 'stopSingle': false, 'stopDouble': false }, initialize: function(options) { this.handlerOptions = OpenLayers.Util.extend( {}, this.defaultHandlerOptions); OpenLayers.Control.prototype.initialize.apply( this, arguments ); this.handler = new OpenLayers.Handler.Click( this, { 'click': this.trigger }, this.handlerOptions); }, trigger: function(e) { if ($('html').hasClass('mobile')) { this.locate_report_mobile(e); } else { this.locate_report(e); } }, locate_report_pin_and_council: function(e) { var lonlat = fixmystreet.map.getLonLatFromViewPortPx(e.xy); if (fixmystreet.page == 'new') { /* Already have a pin */ fixmystreet.markers.features[0].move(lonlat); } else { var markers = fms_markers_list( [ [ lonlat.lat, lonlat.lon, 'yellow' ] ], false ); fixmystreet.bbox_strategy.deactivate(); fixmystreet.markers.removeAllFeatures(); fixmystreet.markers.addFeatures( markers ); fixmystreet_activate_drag(); } fixmystreet_update_pin(lonlat); // check to see if markers are visible. We click the // link so that it updates the text in case they go // back if ( ! fixmystreet.markers.getVisibility() ) { $('#hide_pins_link').click(); } if (fixmystreet.page == 'new') { return true; } $.getJSON('/report/new/ajax', { latitude: $('#fixmystreet\\.latitude').val(), longitude: $('#fixmystreet\\.longitude').val() }, function(data) { $('#councils_text').html(data.councils_text); $('#form_category_row').html(data.category); /* Need to reset this here as it gets removed when we replace the HTML for the dropdown */ if ( data.has_open311 > 0 ) { $('#form_category').change( form_category_onchange ); } }); return false; }, locate_report_mobile: function(e) { if (this.locate_report_pin_and_council(e)) { return; } fixmystreet.page = 'new'; location.hash = 'report'; }, locate_report: function(e) { if (this.locate_report_pin_and_council(e)) { return; } $('#side-form, #site-logo').show(); /* For some reason on IOS5 if you use the jQuery show method it * doesn't display the JS validation error messages unless you do this * or you cause a screen redraw by changing the phone orientation. * NB: This has to happen after the call to show() */ if ( navigator.userAgent.match(/like Mac OS X/i)) { document.getElementById('side-form').style.display = 'block'; } $('#side').hide(); heightFix('#report-a-problem-sidebar:visible', '.content', 26); // If we clicked the map somewhere inconvenient var sidebar = $('#report-a-problem-sidebar'); if (sidebar.css('position') == 'absolute') { var w = sidebar.width(), h = sidebar.height(), o = sidebar.offset(); if (e.xy.y <= o.top) { // top of the page, pin hidden by header lonlat.transform( new OpenLayers.Projection("EPSG:4326"), fixmystreet.map.getProjectionObject() ); var p = fixmystreet.map.getViewPortPxFromLonLat(lonlat) p.x -= $(window).width() / 3; lonlat = fixmystreet.map.getLonLatFromViewPortPx(p); fixmystreet.map.panTo(lonlat); } else if (e.xy.x >= o.left && e.xy.x <= o.left + w + 24 && e.xy.y >= o.top && e.xy.y <= o.top + h + 64) { // underneath where the new sidebar will appear fixmystreet.map.pan(-w, 0, { animate: true }); } } fixmystreet.page = 'new'; location.hash = 'report'; } });