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