066798f084a2d59ebeb7ef078363cafcb13262d3
[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
13 $me = '[FS::TicketSystem::RT_External]';
14 $DEBUG = 0;
15
16 FS::UID->install_callback( sub { 
17   $conf = new FS::Conf;
18   $default_queueid = $conf->config('ticket_system-default_queueid');
19   $priority_reverse = $conf->exists('ticket_system-priority_reverse');
20   $priority_field =
21     $conf->config('ticket_system-custom_priority_field');
22   if ( $priority_field ) {
23     $priority_field_queue =
24       $conf->config('ticket_system-custom_priority_field_queue');
25
26     $field = $priority_field_queue
27                   ? $priority_field_queue. '.%7B'. $priority_field. '%7D'
28                   : $priority_field;
29   } else {
30     $priority_field_queue = '';
31     $field = '';
32   }
33
34   $external_url = '';
35   $dbh = dbh;
36   if ($conf->config('ticket_system') eq 'RT_External') {
37     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
38     $dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 })
39       or die "RT_External DBI->connect error: $DBI::errstr\n";
40
41     $external_url = $conf->config('ticket_system-rt_external_url');
42   }
43
44   #kludge... should *use* the id... but good enough for now
45   if ( $priority_field_queue =~ /^(\d+)$/ ) {
46     my $id = $1;
47     my $sql = 'SELECT Name FROM Queues WHERE Id = ?';
48     my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
49     $sth->execute($id)            or die $sth->errstr. " executing $sql";
50
51     $priority_field_queue = $sth->fetchrow_arrayref->[0];
52
53   }
54
55 } );
56
57 sub num_customer_tickets {
58   my( $self, $custnum, $priority ) = @_;
59
60   my( $from_sql, @param) = $self->_from_customer( $custnum, $priority );
61
62   my $sql = "SELECT COUNT(*) $from_sql";
63   warn "$me $sql (@param)" if $DEBUG;
64   my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
65   $sth->execute(@param)         or die $sth->errstr. " executing $sql";
66
67   $sth->fetchrow_arrayref->[0];
68
69 }
70
71 sub customer_tickets {
72   my( $self, $custnum, $limit, $priority ) = @_;
73   $limit ||= 0;
74
75   my( $from_sql, @param) = $self->_from_customer( $custnum, $priority );
76   my $sql="SELECT Tickets.*, Queues.name, ".
77           "position(Tickets.status in 'newopenstalledresolvedrejecteddeleted')".
78           " AS svalue " .
79           ( length($priority) ? ", objectcustomfieldvalues.content" : '' ).
80           " $from_sql ".
81           " ORDER BY svalue, ".
82           "          priority ". ( $priority_reverse ? 'ASC' : 'DESC' ). ", ".
83           "          id DESC ".
84           " LIMIT $limit";
85   warn "$me $sql (@param)" if $DEBUG;
86   my $sth = $dbh->prepare($sql) or die $dbh->errstr. "preparing $sql";
87   $sth->execute(@param)         or die $sth->errstr. "executing $sql";
88
89   #munge column names???  #httemplate/view/cust_main/tickets.html has column
90   #names that might not make sense now...
91   $sth->fetchall_arrayref({});
92
93 }
94
95 sub _from_customer {
96   my( $self, $custnum, $priority ) = @_;
97
98   my @param = ();
99   my $join = '';
100   my $where = '';
101   if ( defined($priority) ) {
102
103     my $queue_sql = " ObjectCustomFields.ObjectId = ( SELECT id FROM Queues
104                                                        WHERE Queues.name = ? )
105                       OR ( ? = '' AND ObjectCustomFields.ObjectId = 0 )";
106
107     my $customfield_sql =
108       "customfield = ( 
109         SELECT CustomFields.Id FROM CustomFields
110                   JOIN ObjectCustomFields
111                     ON ( CustomFields.id = ObjectCustomFields.CustomField )
112          WHERE LookupType = 'RT::Queue-RT::Ticket'
113            AND name = ?
114            AND ( $queue_sql )
115        )";
116
117     push @param, $priority_field,
118                  $priority_field_queue,
119                  $priority_field_queue;
120
121     if ( length($priority) ) {
122       #$where = "    
123       #  and ? = ( select content from TicketCustomFieldValues
124       #             where ticket = tickets.id
125       #               and customfield = ( select id from customfields
126       #                                    where name = ?
127       #                                      and ( $queue_sql )
128       #                                 )
129       #          )
130       #";
131       unshift @param, $priority;
132
133       $join = "JOIN ObjectCustomFieldValues
134                  ON ( Tickets.id = ObjectCustomFieldValues.ObjectId )";
135       
136       $where = " AND content = ?
137                  AND ObjectCustomFieldValues.disabled != 1
138                  AND ObjectType = 'RT::Ticket'
139                  AND $customfield_sql";
140
141     } else {
142
143       $where =
144                "AND 0 = ( SELECT count(*) FROM ObjectCustomFieldValues
145                            WHERE ObjectId    = Tickets.id
146                              AND ObjectType  = 'RT::Ticket'
147                              AND $customfield_sql
148                         )
149                ";
150     }
151
152   }
153
154   my $sql = "
155                     FROM Tickets
156                     JOIN Queues ON ( Tickets.queue = Queues.id )
157                     JOIN Links ON ( Tickets.id = Links.localbase )
158                     $join 
159        WHERE ( ". join(' OR ', map "status = '$_'", $self->statuses ). " )
160          AND target = 'freeside://freeside/cust_main/$custnum'
161          $where
162   ";
163
164   ( $sql, @param );
165
166 }
167
168 sub statuses {
169   #my $self = shift;
170   my @statuses = grep { ! /^\s*$/ } $conf->config('cust_main-ticket_statuses');
171   @statuses = (qw( new open stalled )) unless scalar(@statuses);
172   @statuses;
173 }
174
175 sub href_customer_tickets {
176   my( $self, $custnum ) = ( shift, shift );
177   my( $priority, @statuses);
178   if ( ref($_[0]) ) {
179     my $opt = shift;
180     $priority = $opt->{'priority'};
181     @statuses = $opt->{'statuses'} ? @{$opt->{'statuses'}} : $self->statuses;
182   } else {
183     $priority = shift;
184     @statuses = $self->statuses;
185   }
186
187   #my $href = $self->baseurl;
188
189   #i snarfed this from an RT bookmarked search, then unescaped (some of) it with
190   #perl -npe 's/%([0-9A-F]{2})/pack('C', hex($1))/eg;'
191
192   #$href .= 
193   my $href = 
194     "Search/Results.html?Order=ASC&".
195     "Query= MemberOf = 'freeside://freeside/cust_main/$custnum' ".
196     #" AND ( Status = 'open'  OR Status = 'new'  OR Status = 'stalled' )"
197     " AND ( ". join(' OR ', map "Status = '$_'", @statuses ). " ) "
198   ;
199
200   if ( defined($priority) && $field && $priority_field_queue ) {
201     $href .= " AND Queue = '$priority_field_queue' ";
202   }
203   if ( defined($priority) && $field ) {
204     $href .= " AND 'CF.$field' ";
205     if ( $priority ) {
206       $href .= "= '$priority' ";
207     } else {
208       $href .= "IS 'NULL' "; #this is "RTQL", not SQL
209     }
210   }
211
212   #$href = 
213   uri_escape($href);
214   #eventually should unescape all of it...
215
216   $href .= '&Rows=100'.
217            '&OrderBy=id&Page=1'.
218            '&Format=%27%20%20%20%3Cb%3E%3Ca%20href%3D%22'.
219            $self->baseurl.
220            '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'.
221            $self->baseurl.
222            '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';
223
224   if ( defined($priority) && $field ) {
225     $href .= '%0A%27__CustomField.'. $field. '__%2FTITLE%3ASeverity%27%2C%20';
226   }
227
228   $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';
229
230   if ( defined($priority) && $field ) {
231     $href .=   '%20%0A%27__-__%27%2C';
232   }
233
234   $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';
235
236   #$href =
237   #uri_escape($href);
238
239   $self->baseurl. $href;
240
241 }
242
243 sub href_new_ticket {
244   my( $self, $custnum_or_cust_main, $requestors ) = @_;
245
246   my( $custnum, $cust_main );
247   if ( ref($custnum_or_cust_main) ) {
248     $cust_main = $custnum_or_cust_main;
249     $custnum = $cust_main->custnum;
250   } else {
251     $custnum = $custnum_or_cust_main;
252     $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
253   }
254   my $queueid = $cust_main->agent->ticketing_queueid || $default_queueid;
255
256   $self->baseurl.
257   'Ticket/Create.html?'.
258     "Queue=$queueid".
259     "&new-MemberOf=freeside://freeside/cust_main/$custnum".
260     ( $requestors ? '&Requestors='. uri_escape($requestors) : '' )
261     ;
262 }
263
264 sub href_ticket {
265   my($self, $ticketnum) = @_;
266   $self->baseurl. 'Ticket/Display.html?id='.$ticketnum;
267 }
268
269 sub queues {
270   my($self) = @_;
271
272   my $sql = "SELECT id, name FROM Queues WHERE disabled = 0";
273   my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
274   $sth->execute()               or die $sth->errstr. " executing $sql";
275
276   map { $_->[0] => $_->[1] } @{ $sth->fetchall_arrayref([]) };
277
278 }
279
280 sub queue {
281   my($self, $queueid) = @_;
282
283   return '' unless $queueid;
284
285   my $sql = "SELECT name FROM Queues WHERE id = ?";
286   my $sth = $dbh->prepare($sql) or die $dbh->errstr. " preparing $sql";
287   $sth->execute($queueid)       or die $sth->errstr. " executing $sql";
288
289   my $rows = $sth->fetchrow_arrayref;
290   $rows ? $rows->[0] : '';
291
292 }
293
294 sub baseurl {
295   #my $self = shift;
296   $external_url. '/';
297 }
298
299 sub _retrieve_single_value {
300   my( $self, $sql ) = @_;
301
302   warn "$me $sql" if $DEBUG;
303   my $sth = $dbh->prepare($sql) or die $dbh->errstr. "preparing $sql";
304   $sth->execute                 or die $sth->errstr. "executing $sql";
305
306   my $arrayref = $sth->fetchrow_arrayref;
307   $arrayref ? $arrayref->[0] : $arrayref;
308 }
309
310 sub transaction_creator {
311   my( $self, $transaction_id ) = @_;
312
313   my $sql = "SELECT name from transactions JOIN users ON ".
314             "transactions.creator=users.id WHERE transactions.id = ".
315             $transaction_id;
316
317   $self->_retrieve_single_value($sql);
318 }
319
320 sub transaction_ticketid {
321   my( $self, $transaction_id ) = @_;
322
323   my $sql = "SELECT objectid from transactions WHERE transactions.id = ".
324             $transaction_id;
325   
326   $self->_retrieve_single_value($sql);
327 }
328
329 sub transaction_subject {
330   my( $self, $transaction_id ) = @_;
331
332   my $sql = "SELECT subject from Transactions JOIN Tickets ON objectid=".
333             "Tickets.id WHERE transactions.id = ".  $transaction_id;
334   
335   $self->_retrieve_single_value($sql);
336 }
337
338 sub transaction_status {
339   my( $self, $transaction_id ) = @_;
340
341   my $sql = "SELECT status from Transactions JOIN Tickets ON objectid=".
342             "Tickets.id WHERE transactions.id = ".  $transaction_id;
343   
344   $self->_retrieve_single_value($sql);
345 }
346
347 1;
348