#!/usr/bin/perl
use warnings;
use strict;
use List::MoreUtils qw(uniq);
use ServiceNow::SOAP;

my $instance = "dev15413";
my $user = "soap.perl";
my $pass = "12345678";

my $sn = ServiceNow($instance, $user, $pass, trace=>1);

my $start_date = "2015-01-01";
my $end_date = "2015-04-30";
my $filter = "opened_at>=$start_date^opened_at<$end_date";

my @inc_recs = $sn->table("incident")->query($filter)->fetchAll();

my @grp_keys = uniq map { $_->{assignment_group} } @inc_recs;
my @grp_recs = $sn->table("sys_user_group")->asQuery(@grp_keys)->fetchAll();
my %grp_hash = map { $_->{sys_id} => $_ } @grp_recs;

my @mgr_keys = uniq map { $_->{manager} } @grp_recs;
my @mgr_recs = $sn->table("sys_user")->asQuery(@mgr_keys)->fetchAll();
my %mgr_hash = map { $_->{sys_id} => $_ } @mgr_recs;

foreach my $inc_rec (@inc_recs) {
    my $number = $inc_rec->{number};
    my $opened = $inc_rec->{opened_at};
    my $grp_rec = $grp_hash{$inc_rec->{assignment_group}};
    my $grp_name = $grp_rec ? $grp_rec->{name} : "";
    my $mgr_rec = $grp_name ? $mgr_hash{$grp_rec->{manager}} : "";
    my $mgr_name = $mgr_rec ? $mgr_rec->{name} : "";
    print "$number | $opened | $grp_name | $mgr_name\n";
}
