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