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