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

use Moo;
extends 'Open311::UpdatesBase';

use DateTime::Format::W3CDTF;

has '+send_comments_flag' => ( default => 1 );
has start_date => ( is => 'ro', default => sub { undef } );
has end_date => ( is => 'ro', default => sub { undef } );

Readonly::Scalar my $AREA_ID_BROMLEY     => 2482;
Readonly::Scalar my $AREA_ID_OXFORDSHIRE => 2237;

sub parse_dates {
    my $self = shift;
    my $body = $self->current_body;

    my @args = ();

    my $dt = DateTime->now();
    # Oxfordshire uses local time and not UTC for dates
    FixMyStreet->set_time_zone($dt) if $body->areas->{$AREA_ID_OXFORDSHIRE};

    # default to asking for last 2 hours worth if not Bromley
    if ($self->start_date) {
        push @args, DateTime::Format::W3CDTF->format_datetime( $self->start_date );
    } elsif ( ! $body->areas->{$AREA_ID_BROMLEY} ) {
        my $start_dt = $dt->clone->add( hours => -2 );
        push @args, DateTime::Format::W3CDTF->format_datetime( $start_dt );
    }

    if ($self->end_date) {
        push @args, DateTime::Format::W3CDTF->format_datetime( $self->end_date );
    } elsif ( ! $body->areas->{$AREA_ID_BROMLEY} ) {
        push @args, DateTime::Format::W3CDTF->format_datetime( $dt );
    }

    return @args;
}

sub process_body {
    my $self = shift;

    my $open311 = $self->current_open311;
    my $body = $self->current_body;
    my @args = $self->parse_dates;
    my $requests = $open311->get_service_request_updates( @args );

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

    for my $request (@$requests) {
        next unless defined $request->{update_id};

        my $p = $self->find_problem($request, @args) or next;
        my $c = $p->comments->search( { external_id => $request->{update_id} } );
        next if $c->first;

        $self->process_update($request, $p);
    }

    return 1;
}

sub _find_problem {
    my ($self, $criteria) = @_;
    my $problem = $self->schema->resultset('Problem')
        ->to_body($self->current_body)
        ->search( $criteria );
    return $problem->first;
}

1;