%# Surprise your boss.  Get to work on time.

<%INIT>
if ($Type eq 'approval') {
    $QueueField = 'IssueStatement';
    $DelegateField = 'Approver';
}

$Tickets->Limit( FIELD => 'Type', VALUE => $Type );

if ($Categories) {
    my $Queues = RT::Queues->new($session{'CurrentUser'});
    $Queues->OrderBy(FIELD => 'Name');
    $Queues->UnLimit;
    while (my $queue = $Queues->Next) {
	my $descr = ($RT::OIN104 ? $queue->Description : $queue->Name);
	$Categories->{$descr}++ if length $descr;
	next unless (length($Category) and $descr eq $Category);

	$Tickets->Limit( FIELD => $QueueField, VALUE => $queue->Id, ENTRYAGGREGATOR => 'OR');
    }
}

if ($Status eq 'resolved') {
    $Tickets->Limit( FIELD => 'Status', VALUE => $_)
	for grep !/^deleted$/, RT::Queue->InactiveStatusArray;
}
elsif ($Type eq 'approval') {
    $Tickets->Limit( FIELD => 'Status', VALUE => $_) for qw( open stalled );
}
else {
    $Tickets->Limit( FIELD => 'Status', VALUE => $_)
	for RT::Queue->ActiveStatusArray;
}

if ( $CreatedBefore ) {
    $CreatedBefore =~ s{/}{-}g;
    my $created_before = RT::Date->new( $session{'CurrentUser'} );
    $created_before->Set( Format => 'unknown', Value => $CreatedBefore );
    my $ISO = $created_before->ISO; $ISO =~ s{/}{-}g;
    $Tickets->Limit( FIELD => 'Created', OPERATOR => "<=", VALUE => $ISO, ENTRYAGGREGATOR => 'AND' );
}

if ( $CreatedAfter ) {
    $CreatedAfter =~ s{/}{-}g;
    my $created_after = RT::Date->new( $session{'CurrentUser'} );
    $created_after->Set( Format => 'unknown', Value => $CreatedAfter );
    my $ISO = $created_after->ISO; $ISO =~ s{/}{-}g;
    $Tickets->Limit( FIELD => 'Created', OPERATOR => ">=", VALUE => $ISO, ENTRYAGGREGATOR => 'AND' );
}

if ( $Owner ) {
    $Tickets->Limit(
	FIELD	=> "Delegate.$DelegateField",
	VALUE	=> $Owner,
    );
}

# Requestor's ExternalAuthId
if ($RT::OIN104 and $Requestor and $Requestor =~ /^[-\w]+$/) {
    # if it looks like a employee_no, try to identify it as such.
    $Tickets->Limit(
	FIELD	=> 'Requestor.ExternalAuthId',
	VALUE	=> RT::User->no_to_id($Requestor),
    );
    $Requestor = undef;
}

# Requestor's Name
if ($Requestor) {
    $Tickets->Limit(
	FIELD	    => 'Requestor.Name',
	OPERATOR    => 'LIKE',
	VALUE	    => $Requestor,
    );
}

if (defined $Approving) {
    $Approving
	? $Tickets->LimitToApproving
	: $Tickets->LimitToNotApproving;
}

$Tickets->OrderBy(FIELD => 'Id', ORDER => 'DESC');

</%INIT>
<%ARGS>
$Tickets
$Status		=> 'unresolved'
$CreatedBefore	=> ''
$CreatedAfter	=> ''
$Requestor	=> ''
$Category	=> ''
$Categories	=> undef
$QueueField	=> 'Queue'
$DelegateField	=> 'Owner'
$Owner		=> undef
$Approving	=> undef
$Type		=> 'ticket'
</%ARGS>
