RT 4.0.22
[freeside.git] / rt / share / html / REST / 1.0 / Forms / ticket / default
1 %# BEGIN BPS TAGGED BLOCK {{{
2 %#
3 %# COPYRIGHT:
4 %#
5 %# This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
6 %#                                          <sales@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 %# REST/1.0/Forms/ticket/default
49 %#
50 <%ARGS>
51 $id
52 $changes => {}
53 $fields => undef
54 $args => undef
55 </%ARGS>
56 <%INIT>
57 use MIME::Entity;
58 use RT::Interface::REST;
59
60 my $cf_spec = RT::Interface::REST->custom_field_spec(1);
61
62 my @comments;
63 my ($c, $o, $k, $e) = ("", [], {}, 0);
64 my %data   = %$changes;
65 my $ticket = RT::Ticket->new($session{CurrentUser});
66 my @dates  = qw(Created Starts Started Due Resolved Told LastUpdated);
67 my @people = qw(Requestors Cc AdminCc);
68 my @create = qw(Queue Requestor Subject Cc AdminCc Owner Status Priority
69                 InitialPriority FinalPriority TimeEstimated TimeWorked
70                 TimeLeft Starts Started Due Resolved Content-Type);
71 my @simple = qw(Subject Status Priority Disabled TimeEstimated TimeWorked
72                 TimeLeft InitialPriority FinalPriority);
73 my %dates  = map {lc $_ => $_} @dates;
74 my %people = map {lc $_ => $_} @people;
75 my %create = map {lc $_ => $_} @create;
76 my %simple = map {lc $_ => $_} @simple;
77
78 # Are we dealing with an existing ticket?
79 if ($id ne 'new') {
80     $ticket->Load($id);
81     if (!$ticket->Id) {
82         return [ "# Ticket $id does not exist.", [], {}, 1 ];
83     }
84     elsif ( %data ) {
85         if ( $data{status} && lc $data{status} eq 'deleted' && ! grep { $_ ne 'id' && $_ ne 'status' } keys %data ) {
86             if ( !$ticket->CurrentUserHasRight('DeleteTicket') ) {
87                 return [ "# You are not allowed to delete ticket $id.", [], {}, 1 ];
88             }
89         }
90         elsif ( !$ticket->CurrentUserHasRight('ModifyTicket') ) {
91                 return [ "# You are not allowed to modify ticket $id.", [], {}, 1 ];
92         }
93     }
94     elsif (!$ticket->CurrentUserHasRight('ShowTicket')) {
95         return [ "# You are not allowed to display ticket $id.", [], {}, 1 ];
96     }
97 }
98 else {
99     if (!keys(%data)) {
100         # GET ticket/new: Return a suitable default form.
101         # We get defaults from queue/1 (XXX: What if it isn't there?).
102         my $due = RT::Date->new($session{CurrentUser});
103         my $queue = RT::Queue->new($session{CurrentUser});
104         my $starts = RT::Date->new($session{CurrentUser});
105         $queue->Load(1);
106         $due->SetToNow;
107         $due->AddDays($queue->DefaultDueIn) if $queue->DefaultDueIn;
108         $starts->SetToNow;
109
110         return [
111             "# Required: id, Queue",
112             [ qw(id Queue Requestor Subject Cc AdminCc Owner Status Priority
113                  InitialPriority FinalPriority TimeEstimated Starts Due Attachment Text) ],
114             {
115                 id               => "ticket/new",
116                 Queue            => $queue->Name,
117                 Requestor        => $session{CurrentUser}->Name,
118                 Subject          => "",
119                 Cc               => [],
120                 AdminCc          => [],
121                 Owner            => "",
122                 Status           => "new",
123                 Priority         => $queue->InitialPriority,
124                 InitialPriority  => $queue->InitialPriority,
125                 FinalPriority    => $queue->FinalPriority,
126                 TimeEstimated    => 0,
127                 Starts           => $starts->ISO,
128                 Due              => $due->ISO,
129                 Attachment       => '',
130                 Text             => "",
131             },
132             0
133         ];
134     }
135     else {
136         # We'll create a new ticket, and fall through to set fields that
137         # can't be set in the call to Create().
138         my (%v, $text, @atts);
139
140         foreach my $k (keys %data) {
141             # flexibly parse any dates
142             if ($dates{lc $k}) {
143                 my $time = RT::Date->new($session{CurrentUser});
144                 $time->Set(Format => 'unknown', Value => $data{$k});
145                 $data{$k} = $time->ISO;
146             }
147
148             if (exists $create{lc $k}) {
149                 $v{$create{lc $k}} = delete $data{$k};
150             }
151             # Set custom field
152             elsif ($k =~ /^$cf_spec/) {
153                 my $key = $1 || $2;
154
155                 my $cf = RT::CustomField->new( $session{CurrentUser} );
156                 $cf->LoadByName( Name => $key, Queue => $data{Queue} || $v{Queue} );
157                 unless ( $cf->id ) {
158                     $cf->LoadByName( Name => $key, Queue => 0 );
159                 }
160
161                 if (not $cf->id) {
162                     push @comments, "# Invalid custom field name ($key)";
163                     delete $data{$k};
164                     next;
165                 }
166                 $v{"CustomField-".$cf->Id()} = delete $data{$k};
167             }
168             elsif (lc $k eq 'text') {
169                 $text = delete $data{$k};
170             }
171             elsif (lc $k eq 'attachment') {
172                 push @atts, @{ vsplit(delete $data{$k}) };
173             }
174             elsif ( $k !~ /^(?:id|requestors)$/i ) {
175                 $e = 1;
176                 push @$o, $k;
177                 push(@comments, "# $k: Unknown field");
178             }
179         }
180
181         if ( $e ) {
182             unshift @comments, "# Could not create ticket.";
183             $k = \%data;
184             goto DONE;
185         }
186
187         # people fields allow multiple values
188         $v{$_} = vsplit($v{$_}) foreach ( grep $create{lc $_}, @people );
189
190         if ($text || @atts) {
191             $v{MIMEObj} =
192                 MIME::Entity->build(
193                     Type => "multipart/mixed",
194                     From => Encode::encode( "UTF-8", $session{CurrentUser}->EmailAddress ),
195                     Subject => Encode::encode( "UTF-8", $v{Subject}),
196                     'X-RT-Interface' => 'REST',
197                 );
198             $v{MIMEObj}->attach(
199                 Type    => $v{'Content-Type'} || 'text/plain',
200                 Charset => "UTF-8",
201                 Data    => Encode::encode( "UTF-8", $text ),
202             ) if $text;
203             my ($status, $msg) = process_attachments($v{'MIMEObj'}, @atts);
204             unless ($status) {
205                 push(@comments, "# $msg");
206                 goto DONE;
207             }
208             $v{MIMEObj}->make_singlepart;
209         }
210
211         my($tid,$trid,$terr) = $ticket->Create(%v);    
212         unless ($tid) {
213             push(@comments, "# Could not create ticket.");
214             push(@comments, "# " . $terr);
215             goto DONE;
216         }
217
218         delete $data{id};
219         $id = $ticket->Id;
220         push(@comments, "# Ticket $id created.");
221         # see if the hash is empty
222         goto DONE if ! keys(%data);
223     }
224 }
225
226 # Now we know we're dealing with an existing ticket.
227 if (!keys(%data)) {
228     my ($time, $key, $val, @data);
229
230     push @data, [ id    => "ticket/".$ticket->Id   ];
231     push @data, [ Queue => $ticket->QueueObj->Name ] 
232         if (!%$fields || exists $fields->{lc 'Queue'});
233     push @data, [ Owner => $ticket->OwnerObj->Name ]
234         if (!%$fields || exists $fields->{lc 'Owner'});
235     push @data, [ Creator => $ticket->CreatorObj->Name ]
236         if (!%$fields || exists $fields->{lc 'Creator'});
237
238     foreach (qw(Subject Status Priority InitialPriority FinalPriority)) {
239         next unless (!%$fields || (exists $fields->{lc $_}));
240         push @data, [$_ => $ticket->$_ ];
241     }
242
243     foreach $key (@people) {
244         next unless (!%$fields || (exists $fields->{lc $key}));
245         push @data, [ $key => [ $ticket->$key->MemberEmailAddresses ] ];
246     }
247
248     $time = RT::Date->new ($session{CurrentUser});
249     foreach $key (@dates) {
250         next unless (!%$fields || (exists $fields->{lc $key}));
251         $time->Set(Format => 'sql', Value => $ticket->$key);
252         push @data, [ $key => $time->AsString ];
253     }
254
255     $time = RT::Date->new ($session{CurrentUser});
256     foreach $key (qw(TimeEstimated TimeWorked TimeLeft)) {
257         next unless (!%$fields || (exists $fields->{lc $key}));
258         $val = $ticket->$key || 0;
259         $val = "$val minutes" if $val;
260         push @data, [ $key => $val ];
261     }
262
263     # Display custom fields
264     my $CustomFields = $ticket->CustomFields;
265     while (my $cf = $CustomFields->Next()) {
266         next unless !%$fields
267                  || exists $fields->{"cf.{".lc($cf->Name)."}"}
268                  || exists $fields->{"cf-".lc $cf->Name};
269
270         my $vals = $ticket->CustomFieldValues($cf->Id());
271         my @out = ();
272         if ( $cf->SingleValue ) {
273             my $v = $vals->Next;
274             push @out, $v->Content if $v;
275         }
276         else {
277             while (my $v = $vals->Next()) {
278                 my $content = $v->Content;
279                 $content =~ s/'/\\'/g;
280                 if ( $v->Content =~ /,/ ) {
281                     push @out, q{'} . $content . q{'};
282                 }
283                 else {
284                     push @out, $content;
285                 }
286             }
287         }
288         push @data, [ ('CF.{' . $cf->Name . '}') => join ',', @out ];
289     }
290
291     my %k = map {@$_} @data;
292     $o = [ map {$_->[0]} @data ];
293     $k = \%k;
294 }
295 else {
296     my ($get, $set, $key, $val, $n, $s);
297     my $updated;
298
299     foreach $key (keys %data) {
300         $val = $data{$key};
301         $key = lc $key;
302         $n = 1;
303
304         if (ref $val eq 'ARRAY') {
305             unless ($key =~ /^(?:Requestors|Cc|AdminCc)$/i) {
306                 $n = 0;
307                 $s = "$key may have only one value.";
308                 goto SET;
309             }
310         }
311
312         if ($key =~ /^queue$/i) {
313             next if $val eq $ticket->QueueObj->Name;
314             ($n, $s) = $ticket->SetQueue($val);
315         }
316         elsif ($key =~ /^owner$/i) {
317             next if $val eq $ticket->OwnerObj->Name;
318             ($n, $s) = $ticket->SetOwner($val);
319         }
320         elsif (exists $simple{$key}) {
321             $key = $simple{$key};
322             $set = "Set$key";
323             my $current = $ticket->$key;
324             $current = '' unless defined $current;
325
326             next if ($val eq $current) or ($current =~ /^\d+$/ && $val =~ /^\d+$/ && $val == $current);
327             ($n, $s) = $ticket->$set("$val");
328         }
329         elsif (exists $dates{$key}) {
330             $key = $dates{$key};
331
332             # We try to detect whether it should update a field by checking
333             # whether its current value equals the entered value. Since the
334             # LastUpdated field is automatically updated as other columns are
335             # changed, it is not properly skipped. Users cannot update this
336             # field anyway.
337             next if $key eq 'LastUpdated';
338
339             $set = "Set$key";
340
341             my $time = RT::Date->new($session{CurrentUser});
342             $time->Set(Format => 'sql', Value => $ticket->$key);
343             next if ($val =~ /^not set$/i || $val eq $time->AsString);
344
345             $time->Set(Format => 'unknown', Value => $val);
346             ($n, $s) = $ticket->$set($time->ISO);
347         }
348         elsif (exists $people{$key}) {
349             $key = $people{$key};
350             my ($p, @msgs);
351
352             my %new  = map {$_=>1} @{ vsplit($val) };
353             my %old  = map {$_=>1} $ticket->$key->MemberEmailAddresses;
354             my $type = $key eq 'Requestors' ? 'Requestor' : $key;
355
356             foreach $p (keys %old) {
357                 unless (exists $new{$p}) {
358                     ($s, $n) = $ticket->DeleteWatcher(Type => $type,
359                                                       Email => $p);
360                     push @msgs, [ $s, $n ];
361                 }
362             }
363             foreach $p (keys %new) {
364                 unless ($ticket->IsWatcher(Type => $type, Email => $p)) {
365                     ($s, $n) = $ticket->AddWatcher(Type => $type,
366                                                    Email => $p);
367                     push @msgs, [ $s, $n ];
368                 }
369             }
370
371             $n = 1;
372             if (@msgs = grep {$_->[0] == 0} @msgs) {
373                 $n = 0;
374                 $s = join "\n", map {"# ".$_->[1]} @msgs;
375                 $s =~ s/^# //;
376             }
377         }
378         # Set custom field
379         elsif ($key =~ /^$cf_spec/) {
380             $key = $1 || $2;
381
382             my $cf = RT::CustomField->new( $session{CurrentUser} );
383             $cf->LoadByName( Name => $key, Queue => $ticket->Queue );
384             unless ( $cf->id ) {
385                 $cf->LoadByName( Name => $key, Queue => 0 );
386             }
387
388             if (not $cf->id) {
389                 $n = 0;
390                 $s = "Unknown custom field.";
391             }
392             else {
393                 my $vals = $ticket->CustomFieldValues($cf->id);
394
395                 if ( !defined $val || !length $val ) {
396                     while ( my $val = $vals->Next ) {
397                         ($n, $s) = $ticket->DeleteCustomFieldValue(
398                             Field => $cf, ValueId => $val->id,
399                         );
400                         $s =~ s/^# // if defined $s;
401                     }
402                 }
403                 elsif ( $cf->SingleValue ) {
404                     my $old = $vals->Next;
405                     if ( $old ) {
406                         if ( $val ne $old->Content ) {
407                             ($n, $s) = $ticket->AddCustomFieldValue(
408                                  Field => $cf, Value => $val );
409                             $s =~ s/^# // if defined $s;
410                         }
411                     }
412                     else {
413                         ($n, $s) = $ticket->AddCustomFieldValue(
414                              Field => $cf, Value => $val );
415                         $s =~ s/^# // if defined $s;
416                     }
417                 }
418                 else {
419                     my @new;
420                     my ( $a, $b ) = split /\s*,\s*/, $val, 2;
421                     while ($a) {
422                         no warnings 'uninitialized';
423                         if ( $a =~ /^'/ ) {
424                             my $s = $a;
425                             while ( $a !~ /'$/ || ( $a !~ /(\\\\)+'$/
426                                             && $a =~ /(\\)+'$/ ) ) {
427                                 ( $a, $b ) = split /\s*,\s*/, $b, 2;
428                                 $s .= ',' . $a;
429                             }
430                             $s =~ s/^'//;
431                             $s =~ s/'$//;
432                             $s =~ s/\\'/'/g;
433                             push @new, $s;
434                         }
435                         elsif ( $a =~ /^q\{/ ) {
436                             my $s = $a;
437                             while ( $a !~ /\}$/ ) {
438                                 ( $a, $b ) = split /\s*,\s*/, $b, 2;
439                                 $s .= ',' . $a;
440                             }
441                             $s =~ s/^q\{//;
442                             $s =~ s/\}//;
443                             push @new, $s;
444                         }
445                         else {
446                             push @new, $a;
447                         }
448                         ( $a, $b ) = split /\s*,\s*/, $b, 2;
449                     }
450
451                     my %new;
452                     $new{$_}++ for @new;
453
454                     while (my $v = $vals->Next()) {
455                         my $c = $v->Content;
456                         if ( $new{$c} ) {
457                             $new{$c}--;
458                         }
459                         else {
460                             $ticket->DeleteCustomFieldValue( Field => $cf, ValueId => $v->id );
461                         }
462                     }
463                     for ( @new ) {
464                         while ( $new{$_} && $new{$_}-- ) {
465                             ($n, $s) = $ticket->AddCustomFieldValue(
466                                 Field => $cf, Value => $_ );
467                             $s =~ s/^# // if defined $s;
468                         }
469                     }
470                 }
471             }
472         }
473         elsif ($key ne 'id' && $key ne 'type' && $key ne 'creator' && $key ne 'content-type' ) {
474             $n = 0;
475             $s = "Unknown field.";
476         }
477
478     SET:
479         if ($n == 0) {
480             $e = 1;
481             push @comments, "# $key: $s";
482             unless (@$o) {
483                 # move id forward
484                 @$o = ("id", grep { $_ ne 'id' } keys %$changes);
485                 $k = $changes;
486             }
487         }
488         else {
489             $updated ||= 1;
490         }
491     }
492     push(@comments, "# Ticket ".$ticket->id." updated.") if $updated;
493 }
494
495 DONE:
496 $c ||= join("\n", @comments) if @comments;
497 return [$c, $o, $k, $e];
498
499 </%INIT>