b5414b97cfdcb9b2c643e7f72197dda656cf5b24
[freeside.git] / FS / FS / TicketSystem / RT_External.pm
1 package FS::TicketSystem::RT_External;
2
3 use strict;
4 use vars qw( $DEBUG $me $conf $dbh $default_queueid $external_url
5              $priority_reverse
6              $priority_field $priority_field_queue $field
7            );
8 use URI::Escape;
9 use FS::UID qw(dbh);
10 use FS::Record qw(qsearchs);
11 use FS::cust_main;
12 use Carp qw(cluck);
13
14 $me = '[FS::TicketSystem::RT_External]';
15 $DEBUG = 0;
16
17 FS::UID->install_callback( sub { 
18   $conf = new FS::Conf;
19   $default_queueid = $conf->config('ticket_system-default_queueid');
20   $priority_reverse = $conf->exists('ticket_system-priority_reverse');
21   $priority_field =
22     $conf->config('ticket_system-custom_priority_field');
23   if ( $priority_field ) {
24     $priority_field_queue =
25       $conf->config('ticket_system-custom_priority_field_queue');
26
27     $field = $priority_field_queue
28                   ? $priority_field_queue. '.%7B'. $priority_field. '%7D'
29                   : $priority_field;
30   } else {
31     $priority_field_queue = '';
32     $field = '';
33   }
34
35   $external_url = '';
36   $dbh = dbh;
37   if ($conf->config('ticket_system') eq 'RT_External') {
38     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
39     $dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 })
40       or die "RT_External DBI->connect error: $DBI::errstr\n";
41
42     $external_url = $conf->config('ticket_system-rt_external_url');
43   }
44
45   #kludge... should *use* the id... but good enough for now
46   if ( $priority_field_queue =~ /^(\d+)$/ ) {
47     my $id = $1;
48     my $sql = 'SELECT Name FROM Queues WHERE Id = ?';
49     my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
50     $sth->execute($id)            or die $sth->errstr. " executing $sql";
51
52     $priority_field_queue = $sth->fetchrow_arrayref->[0];
53
54   }
55
56 } );
57
58 sub num_customer_tickets {
59   my( $self, $custnum, $priority ) = @_;
60
61   my( $from_sql, @param) = $self->_from_customer( $custnum, $priority );
62
63   my $sql = "SELECT COUNT(*) $from_sql";
64   warn "$me $sql (@param)" if $DEBUG;
65   my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
66   $sth->execute(@param)         or die $sth->errstr. " executing $sql";
67
68   $sth->fetchrow_arrayref->[0];
69
70 }
71
72 sub customer_tickets {
73   my( $self, $custnum, $limit, $priority ) = @_;
74   $limit ||= 0;
75
76   my( $from_sql, @param) = $self->_from_customer( $custnum, $priority );
77   my $sql = "
78     SELECT Tickets.*,
79            Queues.Name AS Queue,
80            Users.Name  AS Owner,
81            position(Tickets.Status in 'newopenstalledresolvedrejecteddeleted')
82              AS svalue
83            ". ( length($priority) ? ", ObjectCustomFieldValues.Content" : '' )."
84       $from_sql
85       ORDER BY svalue,
86                Priority ". ( $priority_reverse ? 'ASC' : 'DESC' ). ",
87                id DESC
88       LIMIT $limit
89   ";
90   warn "$me $sql (@param)" if $DEBUG;
91   my $sth = $dbh->prepare($sql) or die $dbh->errstr. "preparing $sql";
92   $sth->execute(@param)         or die $sth->errstr. "executing $sql";
93
94   #munge column names???  #httemplate/view/cust_main/tickets.html has column
95   #names that might not make sense now...
96   $sth->fetchall_arrayref({});
97
98 }
99
100 sub service_tickets {
101   warn "service_tickets not available with RT_External.\n";
102   return;
103 }
104
105 sub comments_on_tickets {
106   my ($self, $custnum, $limit, $time ) = @_;
107   $limit ||= 0;
108
109   my( $from_sql, @param) = $self->_from_customer( $custnum );
110   my $sql = qq{
111     SELECT transactions.*, Attachments.content, Tickets.subject
112     FROM transactions
113       JOIN Attachments ON( Attachments.transactionid = transactions.id )
114       JOIN Tickets ON ( Tickets.id = transactions.objectid )
115       JOIN Links  ON ( Tickets.id    = Links.LocalBase
116                        AND Links.Base LIKE '%/ticket/' || Tickets.id )
117        
118
119     WHERE ( Status = 'new' OR Status = 'open' OR Status = 'stalled' )
120       AND Target = 'freeside://freeside/cust_main/$custnum'
121        AND transactions.type = 'Comment'
122        AND transactions.created >= (SELECT TIMESTAMP WITH TIME ZONE 'epoch' + $time * INTERVAL '1 second')
123      LIMIT $limit
124   };
125   cluck $sql if $DEBUG > 0;
126   #AND created > 
127   $dbh->selectall_arrayref( $sql, { Slice => {} } ) or die $dbh->errstr . " $sql";
128 }
129
130 sub _from_customer {
131   my( $self, $custnum, $priority ) = @_;
132
133   my @param = ();
134   my $join = '';
135   my $where = '';
136   if ( defined($priority) ) {
137
138     my $queue_sql = " ObjectCustomFields.ObjectId = ( SELECT id FROM Queues
139                                                        WHERE Queues.Name = ? )
140                       OR ( ? = '' AND ObjectCustomFields.ObjectId = 0 )";
141
142     my $customfield_sql =
143       "customfield = ( 
144         SELECT CustomFields.Id FROM CustomFields
145                   JOIN ObjectCustomFields
146                     ON ( CustomFields.id = ObjectCustomFields.CustomField )
147          WHERE LookupType = 'RT::Queue-RT::Ticket'
148            AND Name = ?
149            AND ( $queue_sql )
150        )";
151
152     push @param, $priority_field,
153                  $priority_field_queue,
154                  $priority_field_queue;
155
156     if ( length($priority) ) {
157       #$where = "    
158       #  and ? = ( select content from TicketCustomFieldValues
159       #             where ticket = tickets.id
160       #               and customfield = ( select id from customfields
161       #                                    where name = ?
162       #                                      and ( $queue_sql )
163       #                                 )
164       #          )
165       #";
166       unshift @param, $priority;
167
168       $join = "JOIN ObjectCustomFieldValues
169                  ON ( Tickets.id = ObjectCustomFieldValues.ObjectId )";
170       
171       $where = " AND Content = ?
172                  AND ObjectCustomFieldValues.Disabled != 1
173                  AND ObjectType = 'RT::Ticket'
174                  AND $customfield_sql";
175
176     } else {
177
178       $where = " AND NOT EXISTS ( SELECT 1 FROM ObjectCustomFieldValues
179                                     WHERE ObjectId    = Tickets.id
180                                       AND ObjectType  = 'RT::Ticket'
181                                       AND $customfield_sql
182                                 )
183                ";
184     }
185
186   }
187
188   my $sql = "
189     FROM Tickets
190       JOIN Queues ON ( Tickets.Queue = Queues.id )
191       JOIN Users  ON ( Tickets.Owner = Users.id  )
192       JOIN Links  ON ( Tickets.id    = Links.LocalBase
193                        AND Links.Base LIKE '%/ticket/' || Tickets.id )
194       $join 
195
196     WHERE ( ". join(' OR ', map "Status = '$_'", $self->statuses ). " )
197       AND Target = 'freeside://freeside/cust_main/$custnum'
198       $where
199   ";
200
201   ( $sql, @param );
202
203 }
204
205 sub statuses {
206   #my $self = shift;
207   my @statuses = grep { ! /^\s*$/ } $conf->config('cust_main-ticket_statuses');
208   @statuses = (qw( new open stalled )) unless scalar(@statuses);
209   @statuses;
210 }
211
212 sub href_customer_tickets {
213   my($self, $custnum) = (shift, shift);
214   if ( $custnum =~ /^(\d+)$/ ) {
215     return $self->href_search_tickets("MemberOf = 'freeside://freeside/cust_main/$1'");
216   }
217   warn "bad custnum $custnum"; return '';
218 }
219
220 sub href_service_tickets {
221   warn "service_tickets not available with RT_External.\n";
222   '';
223 }
224
225 sub href_search_tickets {
226   my( $self, $where ) = ( shift, shift );
227   my( $priority, @statuses);
228   if ( ref($_[0]) ) {
229     my $opt = shift;
230     $priority = $opt->{'priority'};
231     @statuses = $opt->{'statuses'} ? @{$opt->{'statuses'}} : $self->statuses;
232   } else {
233     $priority = shift;
234     @statuses = $self->statuses;
235   }
236
237   #my $href = $self->baseurl;
238
239   #i snarfed this from an RT bookmarked search, then unescaped (some of) it with
240   #perl -npe 's/%([0-9A-F]{2})/pack('C', hex($1))/eg;'
241
242   #$href .= 
243   my $href = 
244     "Search/Results.html?Order=ASC&".
245     "Query= $where" .
246     #MemberOf = 'freeside://freeside/cust_main/$custnum' ".
247     " AND ( ". join(' OR ', map "Status = '$_'", @statuses ). " ) "
248   ;
249
250   if ( defined($priority) && $field && $priority_field_queue ) {
251     $href .= " AND Queue = '$priority_field_queue' ";
252   }
253   if ( defined($priority) && $field ) {
254     $href .= " AND 'CF.$field' ";
255     if ( $priority ) {
256       $href .= "= '$priority' ";
257     } else {
258       $href .= "IS 'NULL' "; #this is "RTQL", not SQL
259     }
260   }
261
262   #$href = 
263   uri_escape($href);
264   #eventually should unescape all of it...
265
266   $href .= '&RowsPerPage=50'.
267            '&OrderBy=id&Page=1'.
268            '&Format=%27%20%20%20%3Cb%3E%3Ca%20href%3D%22'.
269            $self->baseurl.
270            'Ticket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%20%0A%27%3Cb%3E%3Ca%20href%3D%22'.
271            $self->baseurl.
272            'Ticket%2FDisplay.html%3Fid%3D__id__%22%3E__Subject__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3ASubject%27%2C%20%0A%27__Status__%27%2C%20';
273
274   if ( defined($priority) && $field ) {
275     $href .= '%0A%27__CustomField.'. $field. '__%2FTITLE%3ASeverity%27%2C%20';
276   }
277
278   $href .= '%0A%27__QueueName__%27%2C%20%0A%27__OwnerName__%27%2C%20%0A%27__Priority__%27%2C%20%0A%27__NEWLINE__%27%2C%20%0A%27%27%2C%20%0A%27%3Csmall%3E__Requestors__%3C%2Fsmall%3E%27%2C%20%0A%27%3Csmall%3E__CreatedRelative__%3C%2Fsmall%3E%27%2C';
279
280   if ( defined($priority) && $field ) {
281     $href .=   '%20%0A%27__-__%27%2C';
282   }
283
284   $href .= '%20%0A%27%3Csmall%3E__ToldRelative__%3C%2Fsmall%3E%27%2C%20%0A%27%3Csmall%3E__LastUpdatedRelative__%3C%2Fsmall%3E%27%2C%20%0A%27%3Csmall%3E__TimeLeft__%3C%2Fsmall%3E%27';
285
286   #$href =
287   #uri_escape($href);
288
289   $self->baseurl. $href;
290
291 }
292
293 sub href_params_new_ticket {
294   # my( $self, $custnum_or_cust_main, $requestors ) = @_;
295   # no longer takes $custnum--it must be an object
296   my ( $self, $object, $requestors ) = @_;
297   my $cust_main; # for default requestors
298   if ( $object->isa('FS::cust_main') ) {
299     $cust_main = $object;
300   }
301   elsif ( $object->isa('FS::svc_Common') ) {
302     $object = $object->cust_svc;
303     $cust_main = $object->cust_pkg->cust_main if ( $object->cust_pkg );
304   }
305   elsif ( $object->isa('FS::cust_svc') ) {
306     $cust_main = $object->cust_pkg->cust_main if ( $object->cust_pkg );
307   }
308
309   # explicit $requestors > config option > invoicing_list
310   $requestors = $conf->config('ticket_system-requestor')
311       if !$requestors;
312   $requestors = $cust_main->invoicing_list_emailonly_scalar
313       if (!$requestors) and defined($cust_main);
314
315   my $subtype = $object->table;
316   my $pkey = $object->get($object->primary_key);
317
318   my @param = (
319     'Queue'       => ($cust_main->agent->ticketing_queueid || $default_queueid),
320     'new-MemberOf'=> "freeside://freeside/$subtype/$pkey",
321     'Requestors'  => $requestors,
322   );
323
324   ( $self->baseurl.'Ticket/Create.html', @param );
325 }
326
327 sub href_new_ticket {
328   my $self = shift;
329
330   my( $base, @param ) = $self->href_params_new_ticket(@_);
331
332   my $uri = new URI $base;
333   $uri->query_form(@param);
334   $uri;
335
336 }
337
338 sub href_ticket {
339   my($self, $ticketnum) = @_;
340   $self->baseurl. 'Ticket/Display.html?id='.$ticketnum;
341 }
342
343 sub queues {
344   my($self) = @_;
345
346   my $sql = "SELECT id, Name FROM Queues WHERE Disabled = 0";
347   my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
348   $sth->execute()               or die $sth->errstr. " executing $sql";
349
350   map { $_->[0] => $_->[1] } @{ $sth->fetchall_arrayref([]) };
351
352 }
353
354 sub queue {
355   my($self, $queueid) = @_;
356
357   return '' unless $queueid;
358
359   my $sql = "SELECT Name FROM Queues WHERE id = ?";
360   my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
361   $sth->execute($queueid)       or die $sth->errstr. " executing $sql";
362
363   my $rows = $sth->fetchrow_arrayref;
364   $rows ? $rows->[0] : '';
365
366 }
367
368 sub baseurl {
369   #my $self = shift;
370   $external_url. '/';
371 }
372
373 sub _retrieve_single_value {
374   my( $self, $sql ) = @_;
375
376   warn "$me $sql" if $DEBUG;
377   my $sth = $dbh->prepare($sql) or die $dbh->errstr. "preparing $sql";
378   $sth->execute                 or die $sth->errstr. "executing $sql";
379
380   my $arrayref = $sth->fetchrow_arrayref;
381   $arrayref ? $arrayref->[0] : $arrayref;
382 }
383
384 sub transaction_creator {
385   my( $self, $transaction_id ) = @_;
386
387   my $sql = "SELECT Name FROM Transactions JOIN Users ON ".
388             "Transactions.Creator=Users.id WHERE Transactions.id = ".
389             $transaction_id;
390
391   $self->_retrieve_single_value($sql);
392 }
393
394 sub transaction_ticketid {
395   my( $self, $transaction_id ) = @_;
396
397   my $sql = "SELECT ObjectId FROM Transactions WHERE Transactions.id = ".
398             $transaction_id;
399   
400   $self->_retrieve_single_value($sql);
401 }
402
403 sub transaction_subject {
404   my( $self, $transaction_id ) = @_;
405
406   my $sql = "SELECT Subject FROM Transactions JOIN Tickets ON ObjectId=".
407             "Tickets.id WHERE Transactions.id = ".  $transaction_id;
408   
409   $self->_retrieve_single_value($sql);
410 }
411
412 sub transaction_status {
413   my( $self, $transaction_id ) = @_;
414
415   my $sql = "SELECT Status FROM Transactions JOIN Tickets ON ObjectId=".
416             "Tickets.id WHERE Transactions.id = ".  $transaction_id;
417   
418   $self->_retrieve_single_value($sql);
419 }
420
421 sub access_right {
422   warn "WARNING: no access rights available w/ external RT";
423   0;
424 }
425
426 sub create_ticket {
427   return 'create_ticket unimplemented w/external RT (write something w/RT::Client::REST?)';
428 }
429
430 sub init { } #unimplemented
431
432 sub selfservice_priority { '' } #unimplemented
433
434 1;
435