CustomActionSnippets

From Request Tracker Wiki
Revision as of 13:08, 15 February 2013 by 199.19.138.103 (talk) (Add script for logging fields)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

This page introduce you with some code that can be used in ScripActions and is part of CodeSnippets series of articles.

Custom actions specifics

You better read WriteCustomAction before to understand basics.

Code snippets

Change ticket's queue

my $TargetQueueName = 'MyQueue';
my ($status, $msg) = $TicketObj->SetQueue( $TargetQueueName );
...

Set current actor as Ticket owner

my $Actor = $self->TransactionObj->CreatorObj->Id;
if( $Actor != $self->TicketObj->OwnerObj->Id ) {
  $RT::Logger->info("Auto assign ticket #". $self->TicketObj->id ." to user #". $Actor );

  my ($status, $msg) = $self->TicketObj->SetOwner( $Actor );
  unless( $status ) {
    die "Error: $msg";
  }
}
return 1;

Set owner to nobody

We want to be able to assign cases to unprivileged customers, once they have replied the case should be released:

$self->TicketObj->SetOwner( $RT::Nobody->id );
return 1;
 

Log custom fields and standard fields to syslog

We want to log all custom and standard fields to syslog, so we can generate reports and audit logs, i.e. with Splunk. This would go in transaction batch

#On ticket creation, log standard and custom fields
my $ticket = $self->TicketObj;

#create a hash with all the standard fields we want
my %tkt_props;
$tkt_props{ticket} = $self->TicketObj->id;
$tkt_props{queue} = $self->TicketObj->QueueObj->Name;
$tkt_props{status} = $self->TicketObj->Status;
$tkt_props{subject} = $self->TicketObj->Subject;
$tkt_props{priority} = $self->TicketObj->Priority;
$tkt_props{owner} = $self->TicketObj->OwnerObj->Name;
$tkt_props{requestor_email} = $ticket->RequestorAddresses;

#add custom fields to the hash as well
my $CustomFields = $ticket->QueueObj->TicketCustomFields();
while (my $CustomField = $CustomFields->Next()) {
	my $name = $CustomField->Name;
	my $val = $ticket->FirstCustomFieldValue($name);
	$tkt_props{$name} = $val;
}

#create the string to log: RT4 transaction detected: field="value" field_2="value with spaces"
my $log_string = "RT4 transaction detected:";
foreach my $k (sort keys %tkt_props) {
	my $val = $tkt_props{$k}; #easier than each if you want them sorted
	$k =~ s/\s+/_/g; #remove spaces from name field and replace with _
	$k =~ tr/"//; #there really shouldn't be any quotes in the name, but strip them anyway
	$val =~ s/\s+/ /; #replace all whitespace with a single space char for Splunk
	$val =~ tr/"/'/; #replace double quotes with single for Splunk
	$log_string .= qq| $k="$val"|; #wrap values in quotes
}

$RT::Logger->info( $log_string );
return 1;

More examples

CodeSnippets

See also

WriteCustomAction, CodeSnippets, Scrips