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