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

use Moose;
use Open311;
use FixMyStreet::App;

has council_list => ( is => 'ro' );
has system_user => ( is => 'ro' );

sub update_comments {
    my ( $self, $open311, $council_details ) = @_;

    my $service_requests = $open311->get_service_request_updates( );

    my $requests;

    # XML::Simple is a bit inconsistent in how it structures
    # things depending on the number of children an element has :(
    if ( ref $service_requests->{request_update } eq 'ARRAY' ) {
        $requests = $service_requests->{requesti_update};
    }
    else {
        $requests = [ $service_requests->{request_update} ];
    }

    for my $request (@$requests) {
        # if it's a ref that means it's an empty element
        # however, if there's no updated date then we can't
        # tell if it's newer that what we have so we should skip it
        next if ref $request->{updated_datetime} || ! exists $request->{updated_datetime};

        my $request_id = $request->{service_request_id};

        my $problem =
          FixMyStreet::App->model('DB::Problem')
          ->search( {
                  external_id => $request_id,
                  council     => { like => '%' . $council_details->{areaid} . '%' },
          } );

        if (my $p = $problem->first) {
            my $c = $p->comments->search( { external_id => $request->{update_id} } );

            if ( !$c->first ) {
                my $comment = FixMyStreet::App->model('DB::Comment')->new(
                    {
                        problem => $p,
                        user => $self->system_user,
                        external_id => $request->{update_id},
                        text => $request->{description},
                        mark_fixed => 0,
                        mark_open => 0,
                        anonymous => 0,
                        name => $self->system_user->name
                    }
                );
                $comment->confirm;


                if ( $p->is_open and $request->{status} eq 'closed' ) {
                    $p->state( 'fixed - council' );
                    $p->update;

                    $comment->mark_fixed( 1 );
                } elsif ( ( $p->is_closed || $p->is_fixed ) and $request->{status} eq 'open' ) {
                    $p->state( 'confirmed' );
                    $p->update;

                    $comment->mark_open( 1 );
                }

                $comment->insert();
            }
        }
    }

    return 1;
}

1;