aboutsummaryrefslogtreecommitdiffstats
path: root/perllib/Open311/GetServiceRequests.pm
blob: e5fd6438e7c63be502d5b680b7d508f54416f6f9 (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 Open311::GetServiceRequests;

use Moo;
use Open311;
use FixMyStreet::DB;
use FixMyStreet::MapIt;
use FixMyStreet::App::Model::PhotoSet;
use DateTime::Format::W3CDTF;

has system_user => ( is => 'rw' );
has start_date => ( is => 'ro', default => sub { undef } );
has end_date => ( is => 'ro', default => sub { undef } );
has body => ( is => 'ro', default => sub { undef } );
has fetch_all => ( is => 'rw', default => 0 );
has verbose => ( is => 'ro', default => 0 );
has schema => ( is =>'ro', lazy => 1, default => sub { FixMyStreet::DB->schema->connect } );
has convert_latlong => ( is => 'rw', default => 0 );

sub fetch {
    my $self = shift;

    my $bodies = $self->schema->resultset('Body')->search(
        {
            send_method     => 'Open311',
            fetch_problems  => 1,
            comment_user_id => { '!=', undef },
            endpoint        => { '!=', '' },
        }
    );

    if ( $self->body ) {
        $bodies = $bodies->search( { name => $self->body } );
    }

    while ( my $body = $bodies->next ) {
        my $o = $self->create_open311_object( $body );

        $self->system_user( $body->comment_user );
        $self->convert_latlong( $body->convert_latlong );
        $self->fetch_all( $body->get_extra_metadata('fetch_all_problems') );
        $self->create_problems( $o, $body );
    }
}

# this is so we can test
sub create_open311_object {
    my ($self, $body) = @_;

    my $o = Open311->new(
        endpoint     => $body->endpoint,
        api_key      => $body->api_key,
        jurisdiction => $body->jurisdiction,
    );

    return $o;
}

sub create_problems {
    my ( $self, $open311, $body ) = @_;

    my $args = {};

    my $dt = DateTime->now();
    if ($self->start_date) {
        $args->{start_date} = DateTime::Format::W3CDTF->format_datetime( $self->start_date );
    } elsif ( !$self->fetch_all ) {
        $args->{start_date} = DateTime::Format::W3CDTF->format_datetime( $dt->clone->add(hours => -1) );
    }

    if ($self->end_date) {
        $args->{end_date} = DateTime::Format::W3CDTF->format_datetime( $self->end_date );
    } elsif ( !$self->fetch_all ) {
        $args->{end_date} = DateTime::Format::W3CDTF->format_datetime( $dt );
    }

    my $requests = $open311->get_service_requests( $args );

    unless ( $open311->success ) {
        warn "Failed to fetch ServiceRequest Updates for " . $body->name . ":\n" . $open311->error
            if $self->verbose;
        return 0;
    }

    my $contacts = $self->schema->resultset('Contact')
        ->active
        ->search( { body_id => $body->id } );

    for my $request (@{$requests->{request}}) {
        # no point importing if we can't put it on the map
        unless ($request->{service_request_id} && $request->{lat} && $request->{long}) {
            warn "Not creating request '$request->{description}' for @{[$body->name]} as missing one of id, lat or long"
                if $self->verbose;
            next;
        }
        my $request_id = $request->{service_request_id};

        my ($latitude, $longitude) = ( $request->{lat}, $request->{long} );

        ($latitude, $longitude) = Utils::convert_en_to_latlon_truncated( $longitude, $latitude )
            if $self->convert_latlong;

        my $all_areas =
          FixMyStreet::MapIt::call('point', "4326/$longitude,$latitude");

        # skip if it doesn't look like it's for this body
        my @areas = grep { $all_areas->{$_->area_id} } $body->body_areas;
        unless (@areas) {
            warn "Not creating request id $request_id for @{[$body->name]} as outside body area"
                if $self->verbose;
            next;
        }

        my $updated_time = eval {
            DateTime::Format::W3CDTF->parse_datetime(
                $request->{updated_datetime} || ""
            )->set_time_zone(FixMyStreet->local_time_zone);
        };
        if ($@) {
            warn "Not creating problem $request_id for @{[$body->name]}, bad update time"
                if $self->verbose;
            next;
        }
        my $updated = DateTime::Format::W3CDTF->format_datetime(
            $updated_time->clone->set_time_zone('UTC')
        );

        my $created_time = eval {
            DateTime::Format::W3CDTF->parse_datetime(
                $request->{requested_datetime} || ""
            )->set_time_zone(FixMyStreet->local_time_zone);
        };
        $created_time = $updated_time if $@;

        # Updated time must not be before created time, check and adjust as necessary.
        # (This has happened with some fetched reports, oddly.)
        $updated_time = $created_time if $updated_time lt $created_time;

        my $problems;
        my $criteria = {
            external_id => $request_id,
        };

        # Skip if this problem already exists (e.g. it may have originated from FMS and is being mirrored back!)
        next if $self->schema->resultset('Problem')->to_body($body)->search( $criteria )->count;

        if ($args->{start_date} && $args->{end_date} && ($updated lt $args->{start_date} || $updated gt $args->{end_date}) ) {
            warn "Problem id $request_id for @{[$body->name]} has an invalid time, not creating: "
                . "$updated either less than $args->{start_date} or greater than $args->{end_date}"
                if $self->verbose;
            next;
        }

        my $cobrand = $body->get_cobrand_handler;
        if ( $cobrand ) {
            my $filtered = $cobrand->call_hook('filter_report_description', $request->{description});
            $request->{description} = $filtered if defined $filtered;
        }

        my @contacts = grep { $request->{service_code} eq $_->email } $contacts->all;
        my $contact = $contacts[0] ? $contacts[0]->category : 'Other';

        my $state = $open311->map_state($request->{status});

        my $non_public = $request->{non_public} ? 1 : 0;
        $non_public ||= $contacts[0] ? $contacts[0]->non_public : 0;

        my $problem = $self->schema->resultset('Problem')->new(
            {
                user => $self->system_user,
                external_id => $request_id,
                detail => $request->{description} || $request->{service_name} . ' problem',
                title => $request->{title} || $request->{service_name} . ' problem',
                anonymous => 0,
                name => $self->system_user->name,
                confirmed => $created_time,
                created => $created_time,
                lastupdate => $updated_time,
                whensent => $created_time,
                state => $state,
                postcode => '',
                used_map => 1,
                latitude => $latitude,
                longitude => $longitude,
                areas => ',' . $body->id . ',',
                bodies_str => $body->id,
                send_method_used => 'Open311',
                category => $contact,
                send_questionnaire => 0,
                non_public => $non_public,
            }
        );

        next if $cobrand && $cobrand->call_hook(open311_skip_report_fetch => $problem);

        $open311->add_media($request->{media_url}, $problem)
            if $request->{media_url};

        $problem->insert();
    }

    return 1;
}

1;