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