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