This commit was generated by cvs2svn to compensate for changes in r8690,
[freeside.git] / rt / lib / RT / Graph / Tickets.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2
3 # COPYRIGHT:
4
5 # This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC
6 #                                          <jesse@bestpractical.com>
7
8 # (Except where explicitly superseded by other copyright notices)
9
10
11 # LICENSE:
12
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28
29
30 # CONTRIBUTION SUBMISSION POLICY:
31
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46
47 # END BPS TAGGED BLOCK }}}
48
49 package RT::Graph::Tickets;
50
51 use strict;
52 use warnings;
53
54 =head1 NAME
55
56 RT::Graph::Tickets - view relations between tickets as graphs
57
58 =cut
59
60 unless ($RT::DisableGraphViz) {
61     require IPC::Run;
62     IPC::Run->import;
63     require IPC::Run::SafeHandles;
64     IPC::Run::SafeHandles->import;
65     require GraphViz;
66     GraphViz->import;
67 }
68
69 our %ticket_status_style = (
70     new      => { fontcolor => '#FF0000', fontsize => 10 },
71     open     => { fontcolor => '#000000', fontsize => 10 },
72     stalled  => { fontcolor => '#DAA520', fontsize => 10 },
73     resolved => { fontcolor => '#00FF00', fontsize => 10 },
74     rejected => { fontcolor => '#808080', fontsize => 10 },
75     deleted  => { fontcolor => '#A9A9A9', fontsize => 10 },
76 );
77
78 our %link_style = (
79     MemberOf  => { style => 'solid' },
80     DependsOn => { style => 'dashed' },
81     RefersTo  => { style => 'dotted' },
82 );
83
84 # We don't use qw() because perl complains about "possible attempt to put comments in qw() list"
85 our @fill_colors = split ' ',<<EOT;
86     #0000FF #8A2BE2 #A52A2A #DEB887 #5F9EA0 #7FFF00 #D2691E #FF7F50
87     #6495ED #FFF8DC #DC143C #00FFFF #00008B #008B8B #B8860B #A9A9A9
88     #A9A9A9 #006400 #BDB76B #8B008B #556B2F #FF8C00 #9932CC #8B0000
89     #E9967A #8FBC8F #483D8B #2F4F4F #2F4F4F #00CED1 #9400D3 #FF1493
90     #00BFFF #696969 #696969 #1E90FF #B22222 #FFFAF0 #228B22 #FF00FF
91     #DCDCDC #F8F8FF #FFD700 #DAA520 #808080 #808080 #008000 #ADFF2F
92     #F0FFF0 #FF69B4 #CD5C5C #4B0082 #FFFFF0 #F0E68C #E6E6FA #FFF0F5
93     #7CFC00 #FFFACD #ADD8E6 #F08080 #E0FFFF #FAFAD2 #D3D3D3 #D3D3D3
94     #90EE90 #FFB6C1 #FFA07A #20B2AA #87CEFA #778899 #778899 #B0C4DE
95     #FFFFE0 #00FF00 #32CD32 #FAF0E6 #FF00FF #800000 #66CDAA #0000CD
96     #BA55D3 #9370D8 #3CB371 #7B68EE #00FA9A #48D1CC #C71585 #191970
97     #F5FFFA #FFE4E1 #FFE4B5 #FFDEAD #000080 #FDF5E6 #808000 #6B8E23
98     #FFA500 #FF4500 #DA70D6 #EEE8AA #98FB98 #AFEEEE #D87093 #FFEFD5
99     #FFDAB9 #CD853F #FFC0CB #DDA0DD #B0E0E6 #800080 #FF0000 #BC8F8F
100     #4169E1 #8B4513 #FA8072 #F4A460 #2E8B57 #FFF5EE #A0522D #C0C0C0
101     #87CEEB #6A5ACD #708090 #708090 #FFFAFA #00FF7F #4682B4 #D2B48C
102     #008080 #D8BFD8 #FF6347 #40E0D0 #EE82EE #F5DEB3 #FFFF00 #9ACD32
103 EOT
104
105 sub gv_escape($) {
106     my $value = shift;
107     $value =~ s{(?=")}{\\}g;
108     return $value;
109 }
110
111 our (%fill_cache, @available_colors) = ();
112
113 our %property_cb = (
114     Queue => sub { return $_[0]->QueueObj->Name || $_[0]->Queue },
115     CF    => sub {
116         my $values = $_[0]->CustomFieldValues( $_[1] );
117         return join ', ', map $_->Content, @{ $values->ItemsArrayRef };
118     },
119 );
120 foreach my $field (qw(Subject Status TimeLeft TimeWorked TimeEstimated)) {
121     $property_cb{ $field } = sub { return $_[0]->$field },
122 }
123 foreach my $field (qw(Creator LastUpdatedBy Owner)) {
124     $property_cb{ $field } = sub {
125         my $method = $field .'Obj';
126         return $_[0]->$method->Name;
127     };
128 }
129 foreach my $field (qw(Requestor Cc AdminCc)) {
130     $property_cb{ $field."s" } = sub {
131         my $method = $field .'Addresses';
132         return $_[0]->$method;
133     };
134 }
135 foreach my $field (qw(Told Starts Started Due Resolved LastUpdated Created)) {
136     $property_cb{ $field } = sub {
137         my $method = $field .'Obj';
138         return $_[0]->$method->AsString;
139     };
140 }
141 foreach my $field (qw(Members DependedOnBy ReferredToBy)) {
142     $property_cb{ $field } = sub {
143         return join ', ', map $_->BaseObj->id, @{ $_[0]->$field->ItemsArrayRef };
144     };
145 }
146 foreach my $field (qw(MemberOf DependsOn RefersTo)) {
147     $property_cb{ $field } = sub {
148         return join ', ', map $_->TargetObj->id, @{ $_[0]->$field->ItemsArrayRef };
149     };
150 }
151
152
153 sub TicketProperties {
154     my $self = shift;
155     my $user = shift;
156     my @res = (
157         Basics => [qw(Subject Status Queue TimeLeft TimeWorked TimeEstimated)], # loc_qw
158         People => [qw(Owner Requestors Ccs AdminCcs Creator LastUpdatedBy)], # loc_qw
159         Dates  => [qw(Created Starts Started Due Resolved Told LastUpdated)], # loc_qw
160         Links  => [qw(MemberOf Members DependsOn DependedOnBy RefersTo ReferredToBy)], # loc_qw
161     );
162     my $cfs = RT::CustomFields->new( $user );
163     $cfs->LimitToLookupType('RT::Queue-RT::Ticket');
164     $cfs->OrderBy( FIELD => 'Name' );
165     my ($first, %seen) = (1);
166     while ( my $cf = $cfs->Next ) {
167         next if $seen{ lc $cf->Name }++;
168         next if $cf->Type eq 'Image';
169         if ( $first ) {
170             push @res, 'CustomFields', [];
171             $first = 0;
172         }
173         push @{ $res[-1] }, 'CF.{'. $cf->Name .'}';
174     }
175     return @res;
176 }
177
178 sub _SplitProperty {
179     my $self = shift;
180     my $property = shift;
181     my ($key, @subkeys) = split /\./, $property;
182     foreach ( grep /^{.*}$/, @subkeys ) {
183         s/^{//;
184         s/}$//;
185     }
186     return $key, @subkeys;
187 }
188
189 sub _PropertiesToFields {
190     my $self = shift;
191     my %args = (
192         Ticket       => undef,
193         Graph        => undef,
194         CurrentDepth => 1,
195         @_
196     );
197
198     my @properties;
199     if ( my $tmp = $args{ 'Level-'. $args{'CurrentDepth'} .'-Properties' } ) {
200         @properties = ref $tmp? @$tmp : ($tmp);
201     }
202
203     my @fields;
204     foreach my $property( @properties ) {
205         my ($key, @subkeys) = $self->_SplitProperty( $property );
206         unless ( $property_cb{ $key } ) {
207             $RT::Logger->error("Couldn't find property handler for '$key' and '@subkeys' subkeys");
208             next;
209         }
210         push @fields, ($subkeys[0] || $key) .': '. $property_cb{ $key }->( $args{'Ticket'}, @subkeys );
211     }
212
213     return @fields;
214 }
215
216 sub AddTicket {
217     my $self = shift;
218     my %args = (
219         Ticket       => undef,
220         Properties   => [],
221         Graph        => undef,
222         CurrentDepth => 1,
223         @_
224     );
225
226     my %node_style = (
227         style => 'filled,rounded',
228         %{ $ticket_status_style{ $args{'Ticket'}->Status } || {} },
229         URL   => $RT::WebPath .'/Ticket/Display.html?id='. $args{'Ticket'}->id,
230         tooltip => gv_escape( $args{'Ticket'}->Subject || '#'. $args{'Ticket'}->id ),
231     );
232
233     my @fields = $self->_PropertiesToFields( %args );
234     if ( @fields ) {
235         unshift @fields, $args{'Ticket'}->id;
236         my $label = join ' | ', map { s/(?=[{}|])/\\/g; $_ } @fields;
237         $label = "{ $label }" if ($args{'Direction'} || 'TB') =~ /^(?:TB|BT)$/;
238         $node_style{'label'} = gv_escape( $label );
239         $node_style{'shape'} = 'record';
240     }
241     
242     if ( $args{'FillUsing'} ) {
243         my ($key, @subkeys) = $self->_SplitProperty( $args{'FillUsing'} );
244         my $value;
245         if ( $property_cb{ $key } ) {
246             $value = $property_cb{ $key }->( $args{'Ticket'}, @subkeys );
247         } else {
248             $RT::Logger->error("Couldn't find property callback for '$key'");
249         }
250         if ( defined $value && length $value && $value =~ /\S/ ) {
251             my $fill = $fill_cache{ $value };
252             $fill = $fill_cache{ $value } = shift @available_colors
253                 unless $fill;
254             if ( $fill ) {
255                 $node_style{'fillcolor'} = $fill;
256                 $node_style{'style'} ||= '';
257                 $node_style{'style'} = join ',', split( ',', $node_style{'style'} ), 'filled'
258                     unless $node_style{'style'} =~ /\bfilled\b/;
259             }
260         }
261     }
262
263     $args{'Graph'}->add_node( $args{'Ticket'}->id, %node_style );
264 }
265
266 sub TicketLinks {
267     my $self = shift;
268     my %args = (
269         Ticket               => undef,
270
271         Graph                => undef,
272         Direction            => 'TB',
273         Seen                 => undef,
274         SeenEdge             => undef,
275
276         LeadingLink          => 'Members',
277         ShowLinks            => [],
278
279         MaxDepth             => 0,
280         CurrentDepth         => 1,
281
282         ShowLinkDescriptions => 0,
283         @_
284     );
285     unless ( $args{'Graph'} ) {
286         $args{'Graph'} = GraphViz->new(
287             name    => 'ticket_links_'. $args{'Ticket'}->id,
288             bgcolor => "transparent",
289 # TODO: patch GraphViz to support all posible RDs
290             rankdir => ($args{'Direction'} || "TB") eq "LR",
291             node => { shape => 'box', style => 'filled,rounded', fillcolor => 'white' },
292         );
293         %fill_cache = ();
294         @available_colors = @fill_colors;
295     }
296
297     $args{'Seen'} ||= {};
298     return $args{'Graph'} if $args{'Seen'}{ $args{'Ticket'}->id }++;
299
300     $self->AddTicket( %args );
301
302     return $args{'Graph'} if $args{'MaxDepth'} && $args{'CurrentDepth'} >= $args{'MaxDepth'};
303
304     $args{'SeenEdge'} ||= {};
305
306     my $show_link_descriptions = $args{'ShowLinkDescriptions'}
307         && RT::Link->can('Description');
308
309     foreach my $type ( $args{'LeadingLink'}, @{ $args{'ShowLinks'} } ) {
310         my $links = $args{'Ticket'}->$type();
311         $links->GotoFirstItem;
312         while ( my $link = $links->Next ) {
313             next if $args{'SeenEdge'}{ $link->id }++;
314
315             my $target = $link->TargetObj;
316             next unless $target && $target->isa('RT::Ticket');
317
318             my $base = $link->BaseObj;
319             next unless $base && $base->isa('RT::Ticket');
320
321             my $next = $target->id == $args{'Ticket'}->id? $base : $target;
322
323             $self->TicketLinks(
324                 %args,
325                 Ticket => $next,
326                 $type eq $args{'LeadingLink'}
327                     ? ( CurrentDepth => $args{'CurrentDepth'} + 1 )
328                     : ( MaxDepth => $args{'CurrentDepth'} + 1,
329                         CurrentDepth => $args{'CurrentDepth'} + 1 ),
330             );
331
332             my $desc;
333             $desc = $link->Description if $show_link_descriptions;
334             $args{'Graph'}->add_edge(
335                 # we revers order of member links to get better layout
336                 $link->Type eq 'MemberOf'
337                     ? ($target->id => $base->id, dir => 'back')
338                     : ($base->id => $target->id),
339                 %{ $link_style{ $link->Type } || {} },
340                 $desc? (label => gv_escape $desc): (),
341             );
342         }
343     }
344
345     return $args{'Graph'};
346 }
347
348 eval "require RT::Graph::Tickets_Vendor";
349 if ($@ && $@ !~ qr{^Can't locate RT/Graph/Tickets_Vendor.pm}) {
350     die $@;
351 };
352
353 eval "require RT::Graph::Tickets_Local";
354 if ($@ && $@ !~ qr{^Can't locate RT/Graph/Tickets_Local.pm}) {
355     die $@;
356 };
357
358 1;