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