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