rt 4.0.23
[freeside.git] / rt / lib / RT / Scrips.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2015 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
49 =head1 NAME
50
51   RT::Scrips - a collection of RT Scrip objects
52
53 =head1 SYNOPSIS
54
55   use RT::Scrips;
56
57 =head1 DESCRIPTION
58
59
60 =head1 METHODS
61
62
63
64 =cut
65
66
67 package RT::Scrips;
68
69 use strict;
70 use warnings;
71
72 use RT::Scrip;
73
74 use base 'RT::SearchBuilder';
75
76 sub Table { 'Scrips'}
77
78
79 =head2 LimitToQueue
80
81 Takes a queue id (numerical) as its only argument. Makes sure that 
82 Scopes it pulls out apply to this queue (or another that you've selected with
83 another call to this method
84
85 =cut
86
87 sub LimitToQueue  {
88    my $self = shift;
89   my $queue = shift;
90  
91   $self->Limit (ENTRYAGGREGATOR => 'OR',
92                 FIELD => 'Queue',
93                 VALUE => "$queue")
94       if defined $queue;
95   
96 }
97
98
99 =head2 LimitToGlobal
100
101 Makes sure that 
102 Scopes it pulls out apply to all queues (or another that you've selected with
103 another call to this method or LimitToQueue
104
105 =cut
106
107
108 sub LimitToGlobal  {
109    my $self = shift;
110  
111   $self->Limit (ENTRYAGGREGATOR => 'OR',
112                 FIELD => 'Queue',
113                 VALUE => 0);
114   
115 }
116
117 =head2 AddRecord
118
119 Overrides the collection to ensure that only scrips the user can see are
120 returned.
121
122 =cut
123
124 sub AddRecord {
125     my $self = shift;
126     my ($record) = @_;
127
128     return unless $record->CurrentUserHasRight('ShowScrips');
129     return $self->SUPER::AddRecord( $record );
130 }
131
132 =head2 Apply
133
134 Run through the relevant scrips.  Scrips will run in order based on 
135 description.  (Most common use case is to prepend a number to the description,
136 forcing the scrips to run in ascending alphanumerical order.)
137
138 =cut
139
140 sub Apply {
141     my $self = shift;
142
143     my %args = ( TicketObj      => undef,
144                  Ticket         => undef,
145                  Transaction    => undef,
146                  TransactionObj => undef,
147                  Stage          => undef,
148                  Type           => undef,
149                  @_ );
150
151     $self->Prepare(%args);
152     $self->Commit();
153
154 }
155
156 =head2 Commit
157
158 Commit all of this object's prepared scrips
159
160 =cut
161
162 sub Commit {
163     my $self = shift;
164
165     foreach my $scrip (@{$self->Prepared}) {
166         $RT::Logger->debug(
167             "Committing scrip #". $scrip->id
168             ." on txn #". $self->{'TransactionObj'}->id
169             ." of ticket #". $self->{'TicketObj'}->id
170         );
171
172         $scrip->Commit( TicketObj      => $self->{'TicketObj'},
173                         TransactionObj => $self->{'TransactionObj'} );
174     }
175
176 }
177
178
179 =head2 Prepare
180
181 Only prepare the scrips, returning an array of the scrips we're interested in
182 in order of preparation, not execution
183
184 =cut
185
186 sub Prepare { 
187     my $self = shift;
188     my %args = ( TicketObj      => undef,
189                  Ticket         => undef,
190                  Transaction    => undef,
191                  TransactionObj => undef,
192                  Stage          => undef,
193                  Type           => undef,
194                  @_ );
195
196     #We're really going to need a non-acled ticket for the scrips to work
197     $self->_SetupSourceObjects( TicketObj      => $args{'TicketObj'},
198                                 Ticket         => $args{'Ticket'},
199                                 TransactionObj => $args{'TransactionObj'},
200                                 Transaction    => $args{'Transaction'} );
201
202
203     $self->_FindScrips( Stage => $args{'Stage'}, Type => $args{'Type'} );
204
205
206     #Iterate through each script and check it's applicability.
207     while ( my $scrip = $self->Next() ) {
208
209           unless ( $scrip->IsApplicable(
210                                      TicketObj      => $self->{'TicketObj'},
211                                      TransactionObj => $self->{'TransactionObj'}
212                    ) ) {
213                    $RT::Logger->debug("Skipping Scrip #".$scrip->Id." because it isn't applicable");
214                    next;
215                }
216
217         #If it's applicable, prepare and commit it
218           unless ( $scrip->Prepare( TicketObj      => $self->{'TicketObj'},
219                                     TransactionObj => $self->{'TransactionObj'}
220                    ) ) {
221                    $RT::Logger->debug("Skipping Scrip #".$scrip->Id." because it didn't Prepare");
222                    next;
223                }
224         push @{$self->{'prepared_scrips'}}, $scrip;
225
226     }
227
228     return (@{$self->Prepared});
229
230 };
231
232 =head2 Prepared
233
234 Returns an arrayref of the scrips this object has prepared
235
236
237 =cut
238
239 sub Prepared {
240     my $self = shift;
241     return ($self->{'prepared_scrips'} || []);
242 }
243
244 =head2  _SetupSourceObjects { TicketObj , Ticket, Transaction, TransactionObj }
245
246 Setup a ticket and transaction for this Scrip collection to work with as it runs through the 
247 relevant scrips.  (Also to figure out which scrips apply)
248
249 Returns: nothing
250
251 =cut
252
253
254 sub _SetupSourceObjects {
255
256     my $self = shift;
257     my %args = ( 
258             TicketObj => undef,
259             Ticket => undef,
260             Transaction => undef,
261             TransactionObj => undef,
262             @_ );
263
264
265     if ( $args{'TicketObj'} ) {
266         # This loads a clean copy of the Ticket object to ensure that we
267         # don't accidentally escalate the privileges of the passed in
268         # ticket (this function can be invoked from the UI).
269         # We copy the TransactionBatch transactions so that Scrips
270         # running against the new Ticket will have access to them. We
271         # use RanTransactionBatch to guard against running
272         # TransactionBatch Scrips more than once.
273         $self->{'TicketObj'} = RT::Ticket->new( $self->CurrentUser );
274         $self->{'TicketObj'}->Load( $args{'TicketObj'}->Id );
275         if ( $args{'TicketObj'}->TransactionBatch ) {
276             # try to ensure that we won't infinite loop if something dies, triggering DESTROY while 
277             # we have the _TransactionBatch objects;
278             $self->{'TicketObj'}->RanTransactionBatch(1);
279             $self->{'TicketObj'}->{'_TransactionBatch'} = $args{'TicketObj'}->{'_TransactionBatch'};
280         }
281     }
282     else {
283         $self->{'TicketObj'} = RT::Ticket->new( $self->CurrentUser );
284         $self->{'TicketObj'}->Load( $args{'Ticket'} )
285           || $RT::Logger->err("$self couldn't load ticket $args{'Ticket'}");
286     }
287
288     if ( ( $self->{'TransactionObj'} = $args{'TransactionObj'} ) ) {
289         $self->{'TransactionObj'}->CurrentUser( $self->CurrentUser );
290     }
291     else {
292         $self->{'TransactionObj'} = RT::Transaction->new( $self->CurrentUser );
293         $self->{'TransactionObj'}->Load( $args{'Transaction'} )
294           || $RT::Logger->err( "$self couldn't load transaction $args{'Transaction'}");
295     }
296
297
298
299
300 =head2 _FindScrips
301
302 Find only the apropriate scrips for whatever we're doing now.  Order them 
303 by their description.  (Most common use case is to prepend a number to the
304 description, forcing the scrips to display and run in ascending alphanumerical 
305 order.)
306
307 =cut
308
309 sub _FindScrips {
310     my $self = shift;
311     my %args = (
312                  Stage => undef,
313                  Type => undef,
314                  @_ );
315
316
317     $self->LimitToQueue( $self->{'TicketObj'}->QueueObj->Id )
318       ;    #Limit it to  $Ticket->QueueObj->Id
319     $self->LimitToGlobal();
320       # or to "global"
321
322     $self->Limit( FIELD => "Stage", VALUE => $args{'Stage'} );
323
324     my $ConditionsAlias = $self->NewAlias('ScripConditions');
325
326     $self->Join(
327         ALIAS1 => 'main',
328         FIELD1 => 'ScripCondition',
329         ALIAS2 => $ConditionsAlias,
330         FIELD2 => 'id'
331     );
332
333     #We only want things where the scrip applies to this sort of transaction
334     # TransactionBatch stage can define list of transaction
335     foreach( split /\s*,\s*/, ($args{'Type'} || '') ) {
336         $self->Limit(
337             ALIAS           => $ConditionsAlias,
338             FIELD           => 'ApplicableTransTypes',
339             OPERATOR        => 'LIKE',
340             VALUE           => $_,
341             ENTRYAGGREGATOR => 'OR',
342         )
343     }
344
345     # Or where the scrip applies to any transaction
346     $self->Limit(
347         ALIAS           => $ConditionsAlias,
348         FIELD           => 'ApplicableTransTypes',
349         OPERATOR        => 'LIKE',
350         VALUE           => "Any",
351         ENTRYAGGREGATOR => 'OR',
352     );
353
354     # Promise some kind of ordering
355     $self->OrderBy( FIELD => 'Description' );
356
357     # we call Count below, but later we always do search
358     # so just do search and get count from results
359     $self->_DoSearch if $self->{'must_redo_search'};
360
361     $RT::Logger->debug(
362         "Found ". $self->Count ." scrips for $args{'Stage'} stage"
363         ." with applicable type(s) $args{'Type'}"
364         ." for txn #".$self->{TransactionObj}->Id
365         ." on ticket #".$self->{TicketObj}->Id
366     );
367 }
368
369
370
371
372 =head2 NewItem
373
374 Returns an empty new RT::Scrip item
375
376 =cut
377
378 sub NewItem {
379     my $self = shift;
380     return(RT::Scrip->new($self->CurrentUser));
381 }
382 RT::Base->_ImportOverlays();
383
384 1;