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