avoid creating duplicate scrips in some cases, #14449
[freeside.git] / FS / FS / TicketSystem.pm
1 package FS::TicketSystem;
2
3 use strict;
4 use vars qw( $conf $system $AUTOLOAD );
5 use FS::Conf;
6 use FS::UID qw( dbh driver_name );
7 use FS::Record qw( dbdef );
8
9 FS::UID->install_callback( sub { 
10   $conf = new FS::Conf;
11   $system = $conf->config('ticket_system');
12 } );
13
14 sub AUTOLOAD {
15   my $self = shift;
16
17   my($sub)=$AUTOLOAD;
18   $sub =~ s/.*://;
19
20   my $conf = new FS::Conf;
21   die "FS::TicketSystem::$AUTOLOAD called, but no ticket system configured\n"
22     unless $system;
23
24   eval "use FS::TicketSystem::$system;";
25   die $@ if $@;
26
27   $self .= "::$system";
28   $self->$sub(@_);
29 }
30
31 # Our schema changes
32 my %columns = (
33   Tickets => {
34     WillResolve => { type => 'timestamp', null => 1, default => '', },
35   },
36   CustomFields => {
37     Required => { type => 'integer', default => 0, null => 0 },
38   },
39 );
40
41 sub _upgrade_schema {
42   my $system = FS::Conf->new->config('ticket_system');
43   return if !defined($system) || $system ne 'RT_Internal';
44   my ($class, %opts) = @_;
45
46   my $dbh = dbh;
47   my @sql;
48   my $case = driver_name eq 'mysql' ? sub {@_} : sub {map lc, @_};
49   foreach my $tablename (keys %columns) {
50     my $table = dbdef->table(&$case($tablename));
51     if ( !$table ) {
52       warn 
53       "$tablename table does not exist.  Your RT installation is incomplete.\n";
54       next;
55     }
56     foreach my $colname (keys %{ $columns{$tablename} }) {
57       if ( !$table->column(&$case($colname)) ) {
58         my $col = new DBIx::DBSchema::Column {
59             table_obj => $table,
60             name => &$case($colname),
61             %{ $columns{$tablename}->{$colname} }
62           };
63         $col->table_obj($table);
64         push @sql, $col->sql_add_column($dbh);
65       }
66     } #foreach $colname
67   } #foreach $tablename
68
69   return if !@sql;
70   warn "Upgrading RT schema:\n";
71   foreach my $statement (@sql) {
72     warn "$statement\n";
73     $dbh->do( $statement )
74       or die "Error: ". $dbh->errstr. "\n executing: $statement";
75   }
76   return;
77 }
78
79 sub _upgrade_data {
80   return if !defined($system) || $system ne 'RT_Internal';
81   my ($class, %opts) = @_;
82
83   # go ahead and use the RT API for this
84   
85   FS::TicketSystem->init;
86   my $session = FS::TicketSystem->session();
87   # bypass RT ACLs--we're going to do lots of things
88   my $CurrentUser = $RT::SystemUser;
89
90   # selfservice user
91   my $User = RT::User->new($CurrentUser);
92   $User->Load('%%%SELFSERVICE_USER%%%');
93   if (!defined($User->Id)) {
94     my ($val, $msg) = $User->Create(
95       'Name' => '%%%SELFSERVICE_USER%%%',
96       'Gecos' => '%%%SELFSERVICE_USER%%%',
97       'Privileged' => 1,
98       # any other fields needed?
99     );
100     die $msg if !$val;
101   }
102   my $Principal = $User->PrincipalObj; # can this ever fail?
103   my @rights = ( qw(ShowTicket SeeQueue ModifyTicket ReplyToTicket 
104                     CreateTicket SeeCustomField) );
105   foreach (@rights) {
106     next if $Principal->HasRight( 'Right' => $_, Object => $RT::System );
107     my ($val, $msg) = $Principal->GrantRight(
108       'Right' => $_,
109       'Object' => $RT::System,
110     );
111     die $msg if !$val;
112   }
113
114   # EscalateQueue custom field and friends
115   my $CF = RT::CustomField->new($CurrentUser);
116   $CF->Load('EscalateQueue');
117   if (!defined($CF->Id)) {
118     my ($val, $msg) = $CF->Create(
119       'Name' => 'EscalateQueue',
120       'Type' => 'Select',
121       'MaxValues' => 1,
122       'LookupType' => 'RT::Queue',
123       'Description' => 'Escalate to Queue',
124       'ValuesClass' => 'RT::CustomFieldValues::Queues', #magic!
125     );
126     die $msg if !$val;
127     my $OCF = RT::ObjectCustomField->new($CurrentUser);
128     ($val, $msg) = $OCF->Create(
129       'CustomField' => $CF->Id,
130       'ObjectId' => 0,
131     );
132     die $msg if !$val;
133   }
134
135   # Load from RT data file
136   our (@Groups, @Users, @ACL, @Queues, @ScripActions, @ScripConditions,
137        @Templates, @CustomFields, @Scrips, @Attributes, @Initial, @Final);
138   my $datafile = '%%%RT_PATH%%%/etc/initialdata';
139   eval { require $datafile };
140   if ( $@ ) {
141     warn "Couldn't load RT data from '$datafile': $@\n(skipping)\n";
142     return;
143   }
144
145   # Cache existing ScripCondition, ScripAction, and Template IDs.
146   # Complicated because we don't want to just step on multiple IDs 
147   # with the same name.
148   my $cachify = sub {
149     my ($class, $hash) = @_;
150     my $search = $class->new($CurrentUser);
151     $search->UnLimit;
152     while ( my $item = $search->Next ) {
153       my $ids = $hash->{lc($item->Name)} ||= [];
154       if ( $item->Creator == 1 ) { # RT::SystemUser
155         unshift @$ids, $item->Id;
156       }
157       else {
158         push @$ids, $item->Id;
159       }
160     }
161   };
162
163   my (%condition, %action, %template);
164   &$cachify('RT::ScripConditions', \%condition);
165   &$cachify('RT::ScripActions', \%action);
166   &$cachify('RT::Templates', \%template);
167   # $condition{name} = [ ids... ]
168   # with the id of the system-created object first, if there is one
169
170   # ScripConditions
171   my $ScripCondition = RT::ScripCondition->new($CurrentUser);
172   foreach my $sc (@ScripConditions) {
173     # $sc: Name, Description, ApplicableTransTypes, ExecModule, Argument
174     next if exists( $condition{ lc($sc->{Name}) } );
175     my ($val, $msg) = $ScripCondition->Create( %$sc );
176     die $msg if !$val;
177     $condition{ lc($ScripCondition->Name) } = [ $ScripCondition->Id ];
178   }
179
180   # ScripActions
181   my $ScripAction = RT::ScripAction->new($CurrentUser);
182   foreach my $sa (@ScripActions) {
183     # $sa: Name, Description, ExecModule, Argument
184     next if exists( $action{ lc($sa->{Name}) } );
185     my ($val, $msg) = $ScripAction->Create( %$sa );
186     die $msg if !$val;
187     $action{ lc($ScripAction->Name) } = [ $ScripAction->Id ];
188   }
189
190   # Templates
191   my $Template = RT::Template->new($CurrentUser);
192   foreach my $t (@Templates) {
193     # $t: Queue, Name, Description, Content
194     next if exists( $template{ lc($t->{Name}) } );
195     my ($val, $msg) = $Template->Create( %$t );
196     die $msg if !$val;
197     $template{ lc($Template->Name) } = [ $Template->Id ];
198   }
199
200   # Scrips
201   my %scrip; # $scrips{condition}{action}{template} = id
202   my $search = RT::Scrips->new($CurrentUser);
203   $search->Limit(FIELD => 'Queue', VALUE => 0);
204   while (my $item = $search->Next) {
205     my ($c, $a, $t) = map {lc $item->$_->Name} 
206       ('ScripConditionObj', 'ScripActionObj', 'TemplateObj');
207     if ( exists $scrip{$c}{$a}{$t} and $item->Creator == 1 ) {
208       warn "Deleting duplicate scrip $c $a [$t]\n";
209       my ($val, $msg) = $item->Delete;
210       warn "error deleting scrip: $msg\n" if !$val;
211     }
212     else {
213       $scrip{$c}{$a}{$t} = $item->id;
214     }
215   }
216   my $Scrip = RT::Scrip->new($CurrentUser);
217   foreach my $s ( @Scrips ) {
218     my $desc = $s->{'Description'};
219     my ($c, $a, $t) = map lc,
220       @{ $s }{'ScripCondition', 'ScripAction', 'Template'};
221     # skip existing scrips
222     next if ( exists($scrip{$c}{$a}{$t}) );
223     if ( !exists($condition{$c}) ) {
224       warn "ScripCondition '$c' not found.\n";
225       next;
226     }
227     if ( !exists($action{$a}) ) {
228       warn "ScripAction '$a' not found.\n";
229       next;
230     }
231     if ( !exists($template{$t}) ) {
232       warn "Template '$t' not found.\n";
233       next;
234     }
235     my %new_param = (
236       ScripCondition => $condition{$c}->[0],
237       ScripAction => $action{$a}->[0],
238       Template => $template{$t}->[0],
239       Queue => 0,
240       Description => $desc,
241     );
242     warn "Creating scrip: $c $a [$t]\n";
243     my ($val, $msg) = $Scrip->Create(%new_param);
244     die $msg if !$val;
245   } #foreach (@Scrips)
246
247   return;
248 }
249
250 1;