Merge branch 'patch-18' of https://github.com/gjones2/Freeside
[freeside.git] / FS / FS / part_svc.pm
1 package FS::part_svc;
2
3 use strict;
4 use vars qw( @ISA $DEBUG );
5 use Tie::IxHash;
6 use FS::Record qw( qsearch qsearchs fields dbh );
7 use FS::Schema qw( dbdef );
8 use FS::part_svc_column;
9 use FS::part_export;
10 use FS::export_svc;
11 use FS::cust_svc;
12 use FS::part_svc_class;
13
14 @ISA = qw(FS::Record);
15
16 $DEBUG = 0;
17
18 =head1 NAME
19
20 FS::part_svc - Object methods for part_svc objects
21
22 =head1 SYNOPSIS
23
24   use FS::part_svc;
25
26   $record = new FS::part_svc \%hash
27   $record = new FS::part_svc { 'column' => 'value' };
28
29   $error = $record->insert;
30   $error = $record->insert( [ 'pseudofield' ] );
31   $error = $record->insert( [ 'pseudofield' ], \%exportnums );
32
33   $error = $new_record->replace($old_record);
34   $error = $new_record->replace($old_record, '1.3-COMPAT', [ 'pseudofield' ] );
35   $error = $new_record->replace($old_record, '1.3-COMPAT', [ 'pseudofield' ], \%exportnums );
36
37   $error = $record->delete;
38
39   $error = $record->check;
40
41 =head1 DESCRIPTION
42
43 An FS::part_svc represents a service definition.  FS::part_svc inherits from
44 FS::Record.  The following fields are currently supported:
45
46 =over 4
47
48 =item svcpart - primary key (assigned automatically for new service definitions)
49
50 =item svc - text name of this service definition
51
52 =item svcdb - table used for this service.  See L<FS::svc_acct>,
53 L<FS::svc_domain>, and L<FS::svc_forward>, among others.
54
55 =item classnum - Optional service class (see L<FS::svc_class>)
56
57 =item disabled - Disabled flag, empty or `Y'
58
59 =item preserve - Preserve after cancellation, empty or 'Y'
60
61 =item selfservice_access - Access allowed to the service via self-service:
62 empty for full access, "readonly" for read-only, "hidden" to hide it entirely
63
64 =item restrict_edit_password - Require the "Provision customer service" access
65 right to change the password field, rather than just "Edit password".  Only
66 relevant to svc_acct for now.
67
68 =back
69
70 =head1 METHODS
71
72 =over 4
73
74 =item new HASHREF
75
76 Creates a new service definition.  To add the service definition to the
77 database, see L<"insert">.
78
79 =cut
80
81 sub table { 'part_svc'; }
82
83 =item insert [ EXTRA_FIELDS_ARRAYREF [ , EXPORTNUMS_HASHREF [ , JOB ] ] ] 
84
85 Adds this service definition to the database.  If there is an error, returns
86 the error, otherwise returns false.
87
88 The following pseudo-fields may be defined, and will be maintained in
89 the part_svc_column table appropriately (see L<FS::part_svc_column>).
90
91 =over 4
92
93 =item I<svcdb>__I<field> - Default or fixed value for I<field> in I<svcdb>.
94
95 =item I<svcdb>__I<field>_flag - defines I<svcdb>__I<field> action: null or empty (no default), `D' for default, `F' for fixed (unchangeable), , `S' for selectable choice, `M' for manual selection from inventory, or `A' for automatic selection from inventory.  For virtual fields, can also be 'X' for excluded.
96
97 =back
98
99 If you want to add part_svc_column records for fields that do not exist as
100 fields in the I<svcdb> table, make sure to list then in 
101 EXTRA_FIELDS_ARRAYREF also.
102
103 If EXPORTNUMS_HASHREF is specified (keys are exportnums and values are
104 boolean), the appopriate export_svc records will be inserted.
105
106 TODOC: JOB
107
108 =cut
109
110 sub insert {
111   my $self = shift;
112   my @fields = ();
113   my @exportnums = ();
114   @fields = @{shift(@_)} if @_;
115   if ( @_ ) {
116     my $exportnums = shift;
117     @exportnums = grep $exportnums->{$_}, keys %$exportnums;
118   }
119   my $job = '';
120   $job = shift if @_;
121
122   local $SIG{HUP} = 'IGNORE';
123   local $SIG{INT} = 'IGNORE';
124   local $SIG{QUIT} = 'IGNORE';
125   local $SIG{TERM} = 'IGNORE';
126   local $SIG{TSTP} = 'IGNORE';
127   local $SIG{PIPE} = 'IGNORE';
128
129   my $oldAutoCommit = $FS::UID::AutoCommit;
130   local $FS::UID::AutoCommit = 0;
131   my $dbh = dbh;
132
133   my $error = $self->SUPER::insert;
134   if ( $error ) {
135     $dbh->rollback if $oldAutoCommit;
136     return $error;
137   }
138
139   # add part_svc_column records
140
141   my $svcdb = $self->svcdb;
142 #  my @rows = map { /^${svcdb}__(.*)$/; $1 }
143 #    grep ! /_flag$/,
144 #      grep /^${svcdb}__/,
145 #        fields('part_svc');
146   foreach my $field (
147     grep { $_ ne 'svcnum'
148            && ( defined( $self->getfield($svcdb.'__'.$_.'_flag') )
149                 || $self->getfield($svcdb.'__'.$_.'_label') !~ /^\s*$/ )
150          } (fields($svcdb), @fields)
151   ) {
152     my $part_svc_column = $self->part_svc_column($field);
153     my $previous = qsearchs('part_svc_column', {
154       'svcpart'    => $self->svcpart,
155       'columnname' => $field,
156     } );
157
158     my $flag  = $self->getfield($svcdb.'__'.$field.'_flag');
159     my $label = $self->getfield($svcdb.'__'.$field.'_label');
160     if ( uc($flag) =~ /^([A-Z])$/ || $label !~ /^\s*$/ ) {
161
162       if ( uc($flag) =~ /^([A-Z])$/ ) {
163         my $parser = FS::part_svc->svc_table_fields($svcdb)->{$field}->{parse}
164                      || sub { shift };
165         $part_svc_column->setfield('columnflag', $1);
166         $part_svc_column->setfield('columnvalue',
167           &$parser($self->getfield($svcdb.'__'.$field))
168         );
169       }
170
171       $part_svc_column->setfield('columnlabel', $label)
172         if $label !~ /^\s*$/;
173
174       if ( $previous ) {
175         $error = $part_svc_column->replace($previous);
176       } else {
177         $error = $part_svc_column->insert;
178       }
179
180     } else {
181       $error = $previous ? $previous->delete : '';
182     }
183     if ( $error ) {
184       $dbh->rollback if $oldAutoCommit;
185       return $error;
186     }
187
188   }
189
190   # add export_svc records
191   my $slice = 100/scalar(@exportnums) if @exportnums;
192   my $done = 0;
193   foreach my $exportnum ( @exportnums ) {
194     my $export_svc = new FS::export_svc ( {
195       'exportnum' => $exportnum,
196       'svcpart'   => $self->svcpart,
197     } );
198     $error = $export_svc->insert($job, $slice*$done++, $slice);
199     if ( $error ) {
200       $dbh->rollback if $oldAutoCommit;
201       return $error;
202     }
203   }
204
205   # XXX shouldn't this update fixed values?
206
207   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
208
209   '';
210 }
211
212 =item delete
213
214 Currently unimplemented.  Set the "disabled" field instead.
215
216 =cut
217
218 sub delete {
219   return "Can't (yet?) delete service definitions.";
220 # check & make sure the svcpart isn't in cust_svc or pkg_svc (in any packages)?
221 }
222
223 =item replace OLD_RECORD [ '1.3-COMPAT' [ , EXTRA_FIELDS_ARRAYREF [ , EXPORTNUMS_HASHREF [ , JOB ] ] ] ]
224
225 Replaces OLD_RECORD with this one in the database.  If there is an error,
226 returns the error, otherwise returns false.
227
228 TODOC: 1.3-COMPAT
229
230 TODOC: EXTRA_FIELDS_ARRAYREF (same as insert method)
231
232 TODOC: JOB
233
234 =cut
235
236 sub replace {
237   my ( $new, $old ) = ( shift, shift );
238   my $compat = '';
239   my @fields = ();
240   my $exportnums;
241   my $job = '';
242   if ( @_ && $_[0] eq '1.3-COMPAT' ) {
243     shift;
244     $compat = '1.3';
245     @fields = @{shift(@_)} if @_;
246     $exportnums = @_ ? shift : '';
247     $job = shift if @_;
248   } else {
249     return 'non-1.3-COMPAT interface not yet written';
250     #not yet implemented
251   }
252
253   return "Can't change svcdb for an existing service definition!"
254     unless $old->svcdb eq $new->svcdb;
255
256   local $SIG{HUP} = 'IGNORE';
257   local $SIG{INT} = 'IGNORE';
258   local $SIG{QUIT} = 'IGNORE';
259   local $SIG{TERM} = 'IGNORE';
260   local $SIG{TSTP} = 'IGNORE';
261   local $SIG{PIPE} = 'IGNORE';
262
263   my $oldAutoCommit = $FS::UID::AutoCommit;
264   local $FS::UID::AutoCommit = 0;
265   my $dbh = dbh;
266
267   my $error = $new->SUPER::replace( $old );
268   if ( $error ) {
269     $dbh->rollback if $oldAutoCommit;
270     return $error;
271   }
272
273   if ( $compat eq '1.3' ) {
274
275    # maintain part_svc_column records
276
277     my $svcdb = $new->svcdb;
278     foreach my $field (
279       grep { $_ ne 'svcnum'
280              && ( defined( $new->getfield($svcdb.'__'.$_.'_flag') )
281                   || $new->getfield($svcdb.'__'.$_.'_label') !~ /^\s*$/ )
282            } (fields($svcdb),@fields)
283     ) {
284
285       my $part_svc_column = $new->part_svc_column($field);
286       my $previous = qsearchs('part_svc_column', {
287         'svcpart'    => $new->svcpart,
288         'columnname' => $field,
289       } );
290
291       my $flag  = $new->getfield($svcdb.'__'.$field.'_flag');
292       my $label = $new->getfield($svcdb.'__'.$field.'_label');
293  
294       if ( uc($flag) =~ /^([A-Z])$/ || $label !~ /^\s*$/ ) {
295
296         if ( uc($flag) =~ /^([A-Z])$/ ) {
297           $part_svc_column->setfield('columnflag', $1);
298           my $parser = FS::part_svc->svc_table_fields($svcdb)->{$field}->{parse}
299                      || sub { shift };
300           $part_svc_column->setfield('columnvalue',
301             &$parser($new->getfield($svcdb.'__'.$field))
302           );
303         } else {
304           $part_svc_column->setfield('columnflag',  '');
305           $part_svc_column->setfield('columnvalue', '');
306         }
307
308         $part_svc_column->setfield('columnlabel', $label)
309           if $label !~ /^\s*$/;
310
311         if ( $previous ) {
312           $error = $part_svc_column->replace($previous);
313         } else {
314           $error = $part_svc_column->insert;
315         }
316       } else {
317         $error = $previous ? $previous->delete : '';
318       }
319       if ( $error ) {
320         $dbh->rollback if $oldAutoCommit;
321         return $error;
322       }
323     }
324
325     # maintain export_svc records
326
327     if ( $exportnums ) {
328
329       #false laziness w/ edit/process/agent_type.cgi
330       my @new_export_svc = ();
331       foreach my $part_export ( qsearch('part_export', {}) ) {
332         my $exportnum = $part_export->exportnum;
333         my $hashref = {
334           'exportnum' => $exportnum,
335           'svcpart'   => $new->svcpart,
336         };
337         my $export_svc = qsearchs('export_svc', $hashref);
338
339         if ( $export_svc && ! $exportnums->{$exportnum} ) {
340           $error = $export_svc->delete;
341           if ( $error ) {
342             $dbh->rollback if $oldAutoCommit;
343             return $error;
344           }
345         } elsif ( ! $export_svc && $exportnums->{$exportnum} ) {
346           push @new_export_svc, new FS::export_svc ( $hashref );
347         }
348
349       }
350
351       my $slice = 100/scalar(@new_export_svc) if @new_export_svc;
352       my $done = 0;
353       foreach my $export_svc (@new_export_svc) {
354         $error = $export_svc->insert($job, $slice*$done++, $slice);
355         if ( $error ) {
356           $dbh->rollback if $oldAutoCommit;
357           return $error;
358         }
359         if ( $job ) {
360           $error = $job->update_statustext( int( $slice * $done ) );
361           if ( $error ) {
362             $dbh->rollback if $oldAutoCommit;
363             return $error;
364           }
365         }
366       }
367
368     }
369
370   } else {
371     $dbh->rollback if $oldAutoCommit;
372     return 'non-1.3-COMPAT interface not yet written';
373     #not yet implemented
374   }
375
376   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
377
378   '';
379 }
380
381 =item check
382
383 Checks all fields to make sure this is a valid service definition.  If there is
384 an error, returns the error, otherwise returns false.  Called by the insert
385 and replace methods.
386
387 =cut
388
389 sub check {
390   my $self = shift;
391
392   my $error;
393   $error=
394     $self->ut_numbern('svcpart')
395     || $self->ut_text('svc')
396     || $self->ut_alpha('svcdb')
397     || $self->ut_enum('disabled', [ '', 'Y' ] )
398     || $self->ut_enum('preserve', [ '', 'Y' ] )
399     || $self->ut_enum('selfservice_access', [ '', 'hidden', 'readonly' ] )
400     || $self->ut_foreign_keyn('classnum', 'part_svc_class', 'classnum' )
401     || $self->ut_enum('restrict_edit_password', [ '', 'Y' ] )
402 ;
403   return $error if $error;
404
405   my @fields = eval { fields( $self->svcdb ) }; #might die
406   return "Unknown svcdb: ". $self->svcdb. " (Error: $@)"
407     unless @fields;
408
409   $self->SUPER::check;
410 }
411
412 =item part_svc_column COLUMNNAME
413
414 Returns the part_svc_column object (see L<FS::part_svc_column>) for the given
415 COLUMNNAME, or a new part_svc_column object if none exists.
416
417 =cut
418
419 sub part_svc_column {
420   my( $self, $columnname) = @_;
421   $self->svcpart &&
422     qsearchs('part_svc_column',  {
423                                    'svcpart'    => $self->svcpart,
424                                    'columnname' => $columnname,
425                                  }
426   ) or new FS::part_svc_column {
427                                  'svcpart'    => $self->svcpart,
428                                  'columnname' => $columnname,
429                                };
430 }
431
432 =item all_part_svc_column
433
434 =cut
435
436 sub all_part_svc_column {
437   my $self = shift;
438   qsearch('part_svc_column', { 'svcpart' => $self->svcpart } );
439 }
440
441 =item part_export [ EXPORTTYPE ]
442
443 Returns a list of all exports (see L<FS::part_export>) for this service, or,
444 if an export type is specified, only returns exports of the given type.
445
446 =cut
447
448 sub part_export {
449   my $self = shift;
450   my %search;
451   $search{'exporttype'} = shift if @_;
452   map { $_ } #behavior of sort undefined in scalar context
453     sort { $a->weight <=> $b->weight }
454       map { qsearchs('part_export', { 'exportnum'=>$_->exportnum, %search } ) }
455         qsearch('export_svc', { 'svcpart'=>$self->svcpart } );
456 }
457
458 =item part_export_usage
459
460 Returns a list of any exports (see L<FS::part_export>) for this service that
461 are capable of reporting usage information.
462
463 =cut
464
465 sub part_export_usage {
466   my $self = shift;
467   grep $_->can('usage_sessions'), $self->part_export;
468 }
469
470 =item part_export_did
471
472 Returns a list of any exports (see L<FS::part_export>) for this service that
473 are capable of returing available DID (phone number) information.
474
475 =cut
476
477 sub part_export_did {
478   my $self = shift;
479   grep $_->can('get_dids'), $self->part_export;
480 }
481
482 =item part_export_dsl_pull
483
484 Returns a list of any exports (see L<FS::part_export>) for this service that
485 are capable of pulling/pushing DSL orders.
486
487 =cut
488
489 sub part_export_dsl_pull {
490     my $self = shift;
491     grep $_->can('dsl_pull'), $self->part_export;
492 }
493
494 =item cust_svc [ PKGPART ] 
495
496 Returns a list of associated customer services (FS::cust_svc records).
497
498 If a PKGPART is specified, returns the customer services which are contained
499 within packages of that type (see L<FS::part_pkg>).  If PKGPARTis specified as
500 B<0>, returns unlinked customer services.
501
502 =cut
503
504 sub cust_svc {
505   my $self = shift;
506
507   my $hashref = { 'svcpart' => $self->svcpart };
508
509   my( $addl_from, $extra_sql ) = ( '', '' );
510   if ( @_ ) {
511     my $pkgpart = shift;
512     if ( $pkgpart =~ /^(\d+)$/ ) {
513       $addl_from = 'LEFT JOIN cust_pkg USING ( pkgnum )';
514       $extra_sql = "AND pkgpart = $1";
515     } elsif ( $pkgpart eq '0' ) {
516       $hashref->{'pkgnum'} = '';
517     }
518   }
519
520   qsearch({
521     'table'     => 'cust_svc',
522     'addl_from' => $addl_from,
523     'hashref'   => $hashref,
524     'extra_sql' => $extra_sql,
525   });
526 }
527
528 =item num_cust_svc [ PKGPART ] 
529
530 Returns the number of associated customer services (FS::cust_svc records).
531
532 If a PKGPART is specified, returns the number of customer services which are
533 contained within packages of that type (see L<FS::part_pkg>).  If PKGPART
534 is specified as B<0>, returns the number of unlinked customer services.
535
536 =cut
537
538 sub num_cust_svc {
539   my $self = shift;
540
541   my @param = ( $self->svcpart );
542
543   my( $join, $and ) = ( '', '' );
544   if ( @_ ) {
545     my $pkgpart = shift;
546     if ( $pkgpart ) {
547       $join = 'LEFT JOIN cust_pkg USING ( pkgnum )';
548       $and = 'AND pkgpart = ?';
549       push @param, $pkgpart;
550     } elsif ( $pkgpart eq '0' ) {
551       $and = 'AND pkgnum IS NULL';
552     }
553   }
554
555   my $sth = dbh->prepare(
556     "SELECT COUNT(*) FROM cust_svc $join WHERE svcpart = ? $and"
557   ) or die dbh->errstr;
558   $sth->execute(@param)
559     or die $sth->errstr;
560   $sth->fetchrow_arrayref->[0];
561 }
562
563 =item svc_x
564
565 Returns a list of associated FS::svc_* records.
566
567 =cut
568
569 sub svc_x {
570   my $self = shift;
571   map { $_->svc_x } $self->cust_svc;
572 }
573
574 =back
575
576 =head1 CLASS METHODS
577
578 =over 4
579
580 =cut
581
582 my $svc_defs;
583 sub _svc_defs {
584
585   return $svc_defs if $svc_defs; #cache
586
587   my $conf = new FS::Conf;
588
589   #false laziness w/part_pkg.pm::plan_info
590
591   my %info;
592   foreach my $INC ( @INC ) {
593     warn "globbing $INC/FS/svc_*.pm\n" if $DEBUG;
594     foreach my $file ( glob("$INC/FS/svc_*.pm") ) {
595
596       warn "attempting to load service table info from $file\n" if $DEBUG;
597       $file =~ /\/(\w+)\.pm$/ or do {
598         warn "unrecognized file in $INC/FS/: $file\n";
599         next;
600       };
601       my $mod = $1;
602
603       if ( $mod =~ /^svc_[A-Z]/ or $mod =~ /^(svc_acct_pop|svc_export_machine)$/ ) {
604         warn "skipping FS::$mod" if $DEBUG;
605         next;
606       }
607
608       eval "use FS::$mod;";
609       if ( $@ ) {
610         die "error using FS::$mod (skipping): $@\n" if $@;
611         next;
612       }
613       unless ( UNIVERSAL::can("FS::$mod", 'table_info') ) {
614         warn "FS::$mod has no table_info method; skipping";
615         next;
616       }
617
618       my $info = "FS::$mod"->table_info;
619       unless ( keys %$info ) {
620         warn "FS::$mod->table_info doesn't return info, skipping\n";
621         next;
622       }
623       warn "got info from FS::$mod: $info\n" if $DEBUG;
624       if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
625         warn "skipping disabled service FS::$mod" if $DEBUG;
626         next;
627       }
628       $info{$mod} = $info;
629     }
630   }
631
632   tie my %svc_defs, 'Tie::IxHash', 
633     map  { $_ => $info{$_}->{'fields'} }
634     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
635     keys %info,
636   ;
637   
638   $svc_defs = \%svc_defs; #cache
639   
640 }
641
642 =item svc_tables
643
644 Returns a list of all svc_ tables.
645
646 =cut
647
648 sub svc_tables {
649   my $class = shift;
650   my $svc_defs = $class->_svc_defs;
651   grep { defined( dbdef->table($_) ) } keys %$svc_defs;
652 }
653
654 =item svc_table_fields TABLE
655
656 Given a table name, returns a hashref of field names.  The field names
657 returned are those with additional (service-definition related) information,
658 not necessarily all database fields of the table.  Pseudo-fields may also
659 be returned (i.e. svc_acct.usergroup).
660
661 Each value of the hashref is another hashref, which can have one or more of
662 the following keys:
663
664 =over 4
665
666 =item label - Description of the field
667
668 =item def_label - Optional description of the field in the context of service definitions
669
670 =item type - Currently "text", "select", "checkbox", "textarea", "disabled", 
671 some components specified by "select-.*.html", and a bunch more...
672
673 =item disable_default - This field should not allow a default value in service definitions
674
675 =item disable_fixed - This field should not allow a fixed value in service definitions
676
677 =item disable_inventory - This field should not allow inventory values in service definitions
678
679 =item select_list - If type is "text", this can be a listref of possible values.
680
681 =item select_table - An alternative to select_list, this defines a database table with the possible choices.
682
683 =item select_key - Used with select_table, this is the field name of keys
684
685 =item select_label - Used with select_table, this is the field name of labels
686
687 =back
688
689 =cut
690
691 #maybe this should move and be a class method in svc_Common.pm
692 sub svc_table_fields {
693   my($class, $table) = @_;
694   my $svc_defs = $class->_svc_defs;
695   my $def = $svc_defs->{$table};
696
697   foreach ( grep !ref($def->{$_}), keys %$def ) {
698
699     #normalize the shortcut in %info hash
700     $def->{$_} = { 'label' => $def->{$_} };
701
702     $def->{$_}{'type'} ||= 'text';
703
704   }
705
706   $def;
707 }
708
709 =back
710
711 =head1 SUBROUTINES
712
713 =over 4
714
715 =item process
716
717 Job-queue processor for web interface adds/edits
718
719 =cut
720
721 use Storable qw(thaw);
722 use Data::Dumper;
723 use MIME::Base64;
724 sub process {
725   my $job = shift;
726
727   my $param = thaw(decode_base64(shift));
728   warn Dumper($param) if $DEBUG;
729
730   my $old = qsearchs('part_svc', { 'svcpart' => $param->{'svcpart'} }) 
731     if $param->{'svcpart'};
732
733   #unmunge cgp_accessmodes (falze laziness-ish w/edit/process/svc_acct.cgi)
734   $param->{'svc_acct__cgp_accessmodes'} ||=
735     join(' ', sort
736       grep { $_ !~ /^(flag|label)$/ }
737            map { /^svc_acct__cgp_accessmodes_([\w\/]+)$/ or die "no way"; $1; }
738                grep $param->{$_},
739                     grep /^svc_acct__cgp_accessmodes_([\w\/]+)$/,
740                          keys %$param
741         );
742   
743
744   my $new = new FS::part_svc ( {
745     map {
746       $_ => $param->{$_};
747   #  } qw(svcpart svc svcdb)
748     } ( fields('part_svc'),
749         map { my $svcdb = $_;
750               my @fields = fields($svcdb);
751               push @fields, 'usergroup' if $svcdb eq 'svc_acct'
752                                         or $svcdb eq 'svc_broadband'; #kludge
753
754               map {
755                     my $f = $svcdb.'__'.$_;
756                     my $flag = $param->{ $f.'_flag' } || ''; #silence warnings
757                     if ( $flag =~ /^[MAH]$/ ) {
758                       $param->{ $f } = delete( $param->{ $f.'_classnum' } );
759                     }
760                     if ( ( $flag =~ /^[MAHS]$/ or $_ eq 'usergroup' )
761                          and ref($param->{ $f }) ) {
762                       $param->{ $f } = join(',', @{ $param->{ $f } });
763                     }
764                     ( $f, $f.'_flag', $f.'_label' );
765                   }
766                   @fields;
767
768             } FS::part_svc->svc_tables()
769       )
770   } );
771   
772   my %exportnums =
773     map { $_->exportnum => ( $param->{'exportnum'.$_->exportnum} || '') }
774         qsearch('part_export', {} );
775
776   my $error;
777   if ( $param->{'svcpart'} ) {
778     $error = $new->replace( $old,
779                             '1.3-COMPAT',    #totally bunk, as jeff noted
780                             [ 'usergroup' ],
781                             \%exportnums,
782                             $job
783                           );
784   } else {
785     $error = $new->insert( [ 'usergroup' ],
786                            \%exportnums,
787                            $job,
788                          );
789     $param->{'svcpart'} = $new->getfield('svcpart');
790   }
791
792   die "$error\n" if $error;
793 }
794
795 =item process_bulk_cust_svc
796
797 Job-queue processor for web interface bulk customer service changes
798
799 =cut
800
801 use Storable qw(thaw);
802 use Data::Dumper;
803 use MIME::Base64;
804 sub process_bulk_cust_svc {
805   my $job = shift;
806
807   my $param = thaw(decode_base64(shift));
808   warn Dumper($param) if $DEBUG;
809
810   local($FS::svc_Common::noexport_hack) = 1
811     if $param->{'noexport'};
812
813   my $old_part_svc =
814     qsearchs('part_svc', { 'svcpart' => $param->{'old_svcpart'} } );
815
816   die "Must select a new service definition\n" unless $param->{'new_svcpart'};
817
818   #the rest should be abstracted out to to its own subroutine?
819
820   local $SIG{HUP} = 'IGNORE';
821   local $SIG{INT} = 'IGNORE';
822   local $SIG{QUIT} = 'IGNORE';
823   local $SIG{TERM} = 'IGNORE';
824   local $SIG{TSTP} = 'IGNORE';
825   local $SIG{PIPE} = 'IGNORE';
826
827   my $oldAutoCommit = $FS::UID::AutoCommit;
828   local $FS::UID::AutoCommit = 0;
829   my $dbh = dbh;
830
831   local( $FS::cust_svc::ignore_quantity ) = 1;
832
833   my $total = $old_part_svc->num_cust_svc( $param->{'pkgpart'} );
834
835   my $n = 0;
836   foreach my $old_cust_svc ( $old_part_svc->cust_svc( $param->{'pkgpart'} ) ) {
837
838     my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
839
840     $new_cust_svc->svcpart( $param->{'new_svcpart'} );
841     my $error = $new_cust_svc->replace($old_cust_svc);
842     if ( $error ) {
843       $dbh->rollback if $oldAutoCommit;
844       die "$error\n" if $error;
845     }
846
847     $error = $job->update_statustext( int( 100 * ++$n / $total ) );
848     if ( $error ) {
849       $dbh->rollback if $oldAutoCommit;
850       die $error if $error;
851     }
852
853   }
854
855   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
856
857   '';
858
859 }
860
861 sub _upgrade_data {  #class method
862   my ($class, %opts) = @_;
863
864   my @part_svc_column = qsearch('part_svc_column', { 'columnname' => 'usergroup' });
865   foreach my $col ( @part_svc_column ) {
866     next if $col->columnvalue =~ /^[\d,]+$/ || !$col->columnvalue;
867     my @groupnames = split(',',$col->columnvalue);
868     my @groupnums;
869     my $error = '';
870     foreach my $groupname ( @groupnames ) {
871         my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
872         unless ( $g ) {
873             $g = new FS::radius_group {
874                             'groupname' => $groupname,
875                             'description' => $groupname,
876                             };
877             $error = $g->insert;
878             die "Error inserting new radius_group for service definition group \"$groupname\": $error"
879               if $error;
880         }
881         push @groupnums, $g->groupnum;
882     }
883     $col->columnvalue(join(',',@groupnums));
884     $error = $col->replace;
885     die $error if $error;
886   }
887
888   my @badlabels = qsearch({
889     'table' => 'part_svc_column',
890     'hashref' => {},
891     'extra_sql' => 'WHERE columnlabel IN ('.
892       "'Descriptive label for this particular device.',".
893       "'IP address.  Leave blank for automatic assignment.',".
894       "'Maximum upload speed for this service in Kbps.  0 denotes unlimited.',".
895       "'Maximum download speed for this service in Kbps.  0 denotes unlimited.')"
896   });
897   foreach my $col ( @badlabels ) {
898     $col->columnlabel('');
899     my $error = $col->replace;
900     die $error if $error;
901   }
902
903 }
904
905 =head1 BUGS
906
907 Delete is unimplemented.
908
909 The list of svc_* tables is no longer hardcoded, but svc_acct_pop is skipped
910 as a special case until it is renamed.
911
912 all_part_svc_column methods should be documented
913
914 =head1 SEE ALSO
915
916 L<FS::Record>, L<FS::part_svc_column>, L<FS::part_pkg>, L<FS::pkg_svc>,
917 L<FS::cust_svc>, L<FS::svc_acct>, L<FS::svc_forward>, L<FS::svc_domain>,
918 schema.html from the base documentation.
919
920 =cut
921
922 1;
923