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