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